Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is the Stream-cons #:: translated in Scala?

Tags:

scala

I'm currently learning Scala by working through the "Programming in Scala" book. So far, there have been nice explanations for everything that looks weird (from a Java programmer's perspective), but this one example using a Stream to generate the Fibonacci sequence leaves me kind of puzzled:

def fibFrom(a: Int, b: Int): Stream[Int] =
  a #:: fibFrom(b, a + b)

How is the construction of the Stream done? Of course the #:: operator is somehow responsible for that. I understand that since it ends in :, it is right-associative, but that does not explain the creation of the Stream. I guess it is implicitly translated to a constructor somehow but I don't see why and how exactly.

I've already looked for answers in Predef.scala and LowPriorityImplicits.scala but no luck so far.

Can anyone enlighten me?

like image 895
rolve Avatar asked May 04 '12 10:05

rolve


1 Answers

It is right associative so it works as a method on the right argument:

fibFrom(b, a + b).#::(a)

At least that is what it tries to do syntactically. Stream[Int] does not have such a method. Luckily though, object Stream has an implicit to some class ConsWrapper which has this method (code).

So, what you get after implicit resolution is this:

immutable.this.Stream.consWrapper(fibFrom(b, a + b)).#::(a)
like image 134
Debilski Avatar answered Oct 12 '22 23:10

Debilski