How should I use #:: / hash colon colon in Scala?

pattern-matching, scala, scala-collections

Solution

The method `#::` is defined for Streams. It is similar to the `::` method for Lists. The main difference between a List and a Stream is that the elements of a Stream are lazy evaluated.

There's some scala magic happens on the last line. Actually, first you're evaluating the `fibonacci` expression, and it returns a `Stream` object. The first and the second elements of this stream are 0 and 1, as follows from the third line of your example, and the rest of the Stream is defined via recursive call. And then you're extracting tenth element from the stream, and it evaluates to 55.

In the code below, I show similar access to the fourth List's element

val list = List(1,2,3,4,5)
println(list(3)) // prints 4

In a nutshell, think about Streams as infinite Lists. You can find more about Streams here http://www.scala-lang.org/api/current/index.html#scala.collection.immutable.Stream

Problem

In a Stackoverflow post about the creation of Fibonacci numbers I found the method `#::` (What is the fastest way to write Fibonacci function in Scala?). In ScalaDocs I found this entry (see here, 1) describing the hash colon colon method as An extractor that allows to pattern match streams with #::. I realized that I can use the fibonacci function like this ``` def fibonacci: Stream[Long] = { def tail(h: Long, n: Long): Stream[Long] = h #:: tail(n, h + n) tail(0, 1) } fibonacci(10) //res4: Long = 55 ``` How should I understand the ScalaDocs explanation? Can you give an additional example? Why it was not necessary to define a parameter in the `fibonacci` function above?

Original source

Related problems