Here's my attempt at Functional Programming in Scala's exercise to write toList
for the Stream
class.
def toList[A](stream: Stream[A]): List[A] = {
def go(s: Stream[A], acc: List[A]): List[A] = s match {
case x #:: xs => go(xs, acc :+ x)
case _ => acc
}
go(stream, Nil)
}
Based on reading (but not understanding all) of this post, I was unsure if my pattern matching was correct. In particular, I was concerned that my first case was resulting in immediately evaluating the tail of stream.
Conceptually, I think that I need to implement toList
where each recursion step adds the head of the stream to the list, not evaluating the tail for each step.
Am I correct in this understanding and the above implementation?