Let's consider the problem of generating a sequence of random numbers, with the constraint that the final sequence should have a fixed length n
and the preceding/subsequent elements should be different (i.e. neighbors should be different). My first idiomatic approach would be something like:
val seq = Stream.continually{ Random.nextInt(10) }
.foldLeft(Stream[Int]()){ (all: Stream[Int], next: Int) =>
if (all.length > 0 && all.last != next)
all :+ next
else
all
}
.take(n)
Unfortunately, this does not work, since the foldLeft tries to consume the whole infinite stream, resulting in an endless loop. Intuitively and according to this question I would have expected this behavior only for solutions using foldRight
? Maybe I'm just missing another idiomatic solution?