Pagini
Workshops
Parteneri
Today we cover some of the more advanced functional programming concepts in Scala.
We did tease you in previous courses on various topics. Now we cover them in depth.
You can find today's contents here.
We'll practice a simple implementation of an infinite sequence.
Define a trait Stream[+A]
(although we did explain what the + does, you don't need to worry about it now).
cons
and empty
. The object should look something like this: object Stream { def cons[A](h: A, t: => Stream[A]): Stream[A] = new Stream[A] { // your implementation here def head = ... } def empty: Stream[Nothing] = new Stream[Nothing] { // your implementation here } }
Notice how your code now stays inside an anonymous instance - the anonymous instantiation and on-the-spot method overriding works exactly as in Java.
If you'd like, you can alternatively define two subclasses, much like the Cons-based list you implemented a few labs ago.
Notice the call-by-name scheme at the cons
method. This is fundamentally important. Why?
map
, flatMap
and filter
methods in the trait and implement them in the subclasses.def tail
with a lazy val
? If there is a benefit, do it.Stream
trait and object with some functional primitives.take(k)
which takes an int and returns a stream of the first k elementsdrop(k)
which returns a stream that starts from the k+1'th elementStream.flatten[A](s: Stream[Stream[A]])
which returns a single stream with all the elements in the nested streams, in orderzipWith[B](s: Stream[B], f: (A, B) ⇒ C): Stream[C]
which takes another stream and a function, and returns a zipped stream with the application of the function on the corresponding elements, in order; test ittoList
which converts a finite stream to a listfromList(l: List[A])
which converts a list to a streamfromRange(a, b)
which receives two integers and returns a stream of numbers from a to b, in increasing order; this should not belong to the Stream object or traitstreamOfPrimes(n)
which returns a stream of the first n prime numbers; this should not belong to the Stream object or trait