Pagini
Workshops
Parteneri
Today we become Jedi knights.
We'll explore Scala's type system, its features and rules.
You can find today's contents here.
Let us have a small version of the Cons-based list we implemented in the previous labs:
trait CBL { def head: Int def tail: CBL def prepend(i: Int): CBL def append(list: CBL) : CBL def map(f: Int => Int): CBL def flatMap(f: Int => CBL): CBL def filter(f: Int => Boolean): CBL } case object CNil extends CBL { def head: Int = throw new Exception("nothing") def tail: CBL = throw new Exception("nothing") def prepend(i: Int): CBL = Cons(i, this) def append(list: CBL): CBL = list def map(f: Int => Int): CBL = CNil def flatMap(f: Int => CBL): CBL = CNil def filter(f: Int => Boolean): CBL = CNil } case class Cons(h: Int, t: CBL) extends CBL { def head: Int = h def tail: CBL = t def prepend(i: Int): CBL = Cons(i, this) def append(list: CBL): CBL = Cons(h, t append list) def map(f: Int => Int): CBL = Cons(f(h), t map f) def flatMap(f: Int => CBL): CBL = f(h) append (t flatMap f) def filter(f: Int => Boolean): CBL = if (f(h)) Cons(h, t filter f) else t filter f }
{ def head: A }
into a type.def head: A
.f
.=::=
method for types which have the def head: A
method.