How to create LazyList Scala using LazyList.iterate?

1.2k Views Asked by At

My task:

  1. Implement a function to calculate the Look-and-say sequence.

This is done and the tests pass successfully:

import scala.collection.immutable.LazyList
import scala.language.implicitConversions
import scala.collection.mutable.ListBuffer

object CountAndSay extends App {
  def nextLine(currentLine: List[BigInt]): List[BigInt] = {
    ...

  println(nextLine(List(1, 2, 1, 1)) == List(1, 1, 1, 2, 2, 1))
  println(nextLine(List(1, 1, 1, 2, 2, 1)) == List(3, 1, 2, 2, 1, 1))
  println(nextLine(List(3, 1, 2, 2, 1, 1)) == List(1, 3, 1, 1, 2, 2, 2, 1))
}
  1. Implement a lazy list that generates the given sequence.
val funSeq: LazyList[List[Int]] = ...
println(funSeq(5) === List(3, 1, 2, 2, 1, 1))

To create a LazyList with nested lists, I want to use LazyList.iterate. LazyList.iterate description But I get a Cannot resolve overloaded method 'iterate' error:

val funSeq: LazyList[List[BigInt]] = LazyList.iterate(List(1), nextLine(List(1)))

I would appreciate any help.

1

There are 1 best solutions below

0
Vladislav Kievski On BEST ANSWER

It looks like you do not use LazyList syntax correctly. You need to use it as follow:

LazyList.iterate(List(BigInt(1)))(nextLine).take(4).force

First parameter of iterate is start element that will passed in the function - second parameter of iterate. The take need to do several iterations and force need to evaluate result.