ecolban (3) [Avatar] Offline
#1
Solution provided for flatMap results in stack overflow. If I run the following code:

package fpinscala.chap5

import Stream._ // copied as is from answers project into current package

object Main extends App {

println(Stream(1, 2, 3).flatMap(x => Stream(x, x)) toList)

def from(n: Int): Stream[Int] = cons(n, from(n + 1))

from(1).flatMap(x => Stream(x, x))
}

I get:

List(1, 1, 2, 2, 3, 3)
Exception in thread "main" java.lang.StackOverflowError
at scala.collection.AbstractTraversable.<init>(Traversable.scala:105)
at scala.collection.AbstractIterable.<init>(Iterable.scala:54)
at scala.collection.AbstractSeq.<init>(Seq.scala:40)
at scala.collection.mutable.AbstractSeq.<init>(Seq.scala:47)
at scala.collection.mutable.WrappedArray.<init>(WrappedArray.scala:35)
at scala.collection.mutable.WrappedArray$ofInt.<init>(WrappedArray.scala:151)
at scala.LowPriorityImplicits.wrapIntArray(LowPriorityImplicits.scala:76)
at fpinscala.chap5.Main$$anonfun$2.apply(Main.scala:11)
at fpinscala.chap5.Main$$anonfun$2.apply(Main.scala:11)
at fpinscala.chap5.Stream$$anonfun$flatMap$2.apply(Stream.scala:102)
at fpinscala.chap5.Stream$$anonfun$flatMap$2.apply(Stream.scala:102)
at fpinscala.chap5.Stream.foldRight(Stream.scala:72)
at fpinscala.chap5.Stream$$anonfun$foldRight$1.apply(Stream.scala:72)
at fpinscala.chap5.Stream$$anonfun$flatMap$2.apply(Stream.scala:102)
at fpinscala.chap5.Stream$$anonfun$flatMap$2.apply(Stream.scala:102)
at fpinscala.chap5.Stream.foldRight(Stream.scala:72)
at fpinscala.chap5.Stream$$anonfun$foldRight$1.apply(Stream.scala:72)
at fpinscala.chap5.Stream$$anonfun$flatMap$2.apply(Stream.scala:102)
at fpinscala.chap5.Stream$$anonfun$flatMap$2.apply(Stream.scala:102)
...
ecolban (3) [Avatar] Offline
#2
Re: Exercise 5.7