I would to print out a stream of numbers but the following code only prints out the first number in the sequence:
for ( n <- Stream.from(2) if n % 2 == 0 ) yield println(n)
2
res4: scala.collection.immutable.Stream[Unit] = Stream((), ?)
In Haskell the following keeps printing out numbers until interrupted and I would like similar behaviour in Scala:
naturals = [1..]
[n | n <- naturals, even n]
[2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58,
Instead of yielding just println (why would one want infinite sequence of Unit's?):
for ( n <- Stream.from(2) if n % 2 == 0 ) println(n)
If you really want that infinite sequence of Units, force result:
val infUnit = for ( n <- Stream.from(2) if n % 2 == 0 ) yield println(n)
infUnit.force // or convert to any other non-lazy collection
Though, eventually, it will crash program (due to large length of materialized sequence).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With