Newer
Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package laziness
sealed trait Stream[+A] {
import Stream._
def toList: List[A] = ???
def take(n: Int): Stream[A] = ???
//This can be tailrecursive. Uncomment below to let the compiler check
//@annotation.tailrec
def drop(n: Int): Stream[A] = ???
// Methods shown during lecture
def headOption: Option[A] = this match {
case Cons(h, _) => Some(h())
case Empty => None
}
def exists(p: A => Boolean): Boolean = this match {
case Cons(x, xs) => p(x()) || xs().exists(p)
case Empty => false
}
def foldRight[B](z: => B)(f: (A, => B) => B): B = this match {
case Cons(x, xs) => f(x(), xs().foldRight(z)(f))
case Empty => z
}
}
case object Empty extends Stream[Nothing]
case class Cons[+A](h: () => A, t: () => Stream[A]) extends Stream[A]
object Stream { // companion object
def fibs: Stream[Int] = {
// tip: write a recursive def here and call it with some start values
???
}
def unfold[A, S](z: S)(f: S => Option[(A, S)]): Stream[A] = ???
def fibsViaUnfold: Stream[Int] = ???
// Methods shown during Lecture
def cons[A](h: => A, t: => Stream[A]): Stream[A] = {
lazy val head = h
lazy val tail = t
Cons(() => head, () => tail)
}
def empty[A]: Stream[A] = Empty
def apply[A](as: A*): Stream[A] =
if (as.isEmpty) empty
else cons(as.head, apply(as.tail: _*))
val ones: Stream[Int] = cons(1, ones)
}