Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

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

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))