Type Lambdas
A type lambda is a type-level function that builds a type from a type argument. It is written in brackets with an arrow, like [T] =>> List[T].
A List lambda fills the maker slot
The maker slot expects a type that takes an argument. The List lambda builds a List from the given item.
trait Maker[F[_]]:
def make[A](a: A): F[A]
class ListMaker extends Maker[[T] =>> List[T]]:
def make[A](a: A): List[A] = List(a)
@main def main(): Unit =
val maker = ListMaker()
println(maker.make(3).head * 3)An Option lambda fills the maker slot
The Option lambda builds an Option from the given item. The program reads the length of the stored text.
trait Maker[F[_]]:
def make[A](a: A): F[A]
class OptionMaker extends Maker[[T] =>> Option[T]]:
def make[A](a: A): Option[A] = Some(a)
@main def main(): Unit =
val maker = OptionMaker()
println(maker.make("hi").map(s => s.length).getOrElse(0))A named lambda can fill the maker slot
The named lambda stands for the List lambda. The program doubles the head of the built list.
trait Maker[F[_]]:
def make[A](a: A): F[A]
type MyList = [T] =>> List[T]
class NamedMaker extends Maker[MyList]:
def make[A](a: A): List[A] = List(a)
@main def main(): Unit =
val maker = NamedMaker()
println(maker.make(6).head * 2)Example
trait Maker[F[_]]:
def make[A](a: A): F[A]
class ListMaker extends Maker[[T] =>> List[T]]:
def make[A](a: A): List[A] = List(a)
class OptionMaker extends Maker[[T] =>> Option[T]]:
def make[A](a: A): Option[A] = Some(a)
@main def main(): Unit =
val listHead = ListMaker().make(8).head
val optValue = OptionMaker().make(3).getOrElse(0)
println(listHead + optValue)Key points
- Type-level function: A type-level function takes a type and returns a type.
- Higher-kinded slot: A higher-kinded slot is a placeholder for a type that takes its own type argument.
- List lambda: The lambda [T] =>> List[T] builds a List for any item type.
- Option lambda: The lambda [T] =>> Option[T] builds an Option for any item type.
In this example, the program builds a List holding 8 and an Option holding 3. It reads 8 from the list head and 3 from the Option. It adds them to get 11.
Note
A type lambda differs from a plain type alias because it still waits for a type argument.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Scastie
Exercise
What does the lambda [T] =>> List[T] build for the item type Int?