I realise this is probably a simple question but what is '#::' achieving in below line of code. Is it a special variance of cons ?
def from(n: Int): Stream[Int] = n #:: from(n + 1)
This operator is used to construct streams as opposed to lists. Consider the same code snippet with simple cons:
def from(n: Int): List[Int] = n :: from(n + 1)
running this method will result in StackOverflowError
. But with Stream[Int]
tail is evaluated lazily only when it's needed (and already computed values are remembered).
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