MyList - step 7
The lazy list can handle an infinite list.
In the end we take some elements that are calculated
Lazy List Exercises
Exercise 1
We will use MyList as a reference. Refactor the MyList name to a LzList (shift-F6) Nearly all the methods are the same.
Cons
class Cons[A](hd: => A, tl: => LazyList[A]) extends LazyList[A] {
def isEmpty: Boolean = false
override lazy val head: A = hd
override lazy val tail: LazyList[A] = tl
Here we do a call by need on the head and the tail And we need a class because call by name are not allow on case classes.
And new Cons is used in instantiate a Cons
Run the LzList to see if everything still works
Exercise 2
To use the laziness of the list we will create an inifite list and take method
- take
- infinite list
def take(n :Int): LzList[A]
Implement those in Empty and Cons
def generate(start: Int)(next: Int => Int): LzList[Int] = ???
In the companion object a generate method is added of type Int
Solution 2
Empty
override def take(n: Int): LzList[A] = this
Cons
override def take(n: Int): LzList[A] =
def loop(remainder: LzList[A], count: Int): LzList[A] =
if count == 0 then Empty()
else new Cons(remainder.head, loop (remainder.tail, count - 1))
loop(this, n)
object LzList
def generate(start: Int)(next: Int => Int): LzList[Int] =
new Cons[Int](start, generate(next(start))(next))
main
val genList: LzList[Int] = LzList.generate(1)( _ + 1)
val genMap = genList.map(_ * 100)
println(genMap.take(10))
println(genMap.take(100))
println(genMap.take(100000))