Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the #:: operator in a scala Stream? [duplicate]

Tags:

scala

Possible Duplicate:
Searching the Scala documentation for #::

I'm looking through the docs of Stream

The filter method has this code:

def naturalsFrom(i: Int): Stream[Int] = i #:: naturalsFrom(i + 1)
naturalsFrom(1)  10 } filter { _ % 5 == 0 } take 10 mkString(", ")

What is the #:: operator? Does this map to a function call somewhere?

like image 207
Nathan Feger Avatar asked Nov 23 '12 17:11

Nathan Feger


2 Answers

As SHildebrandt says, #:: is the cons operator for Streams.

In other words, #:: is to streams what :: is to Lists

val x = Stream(1,2,3,4)                   //> x  : scala.collection.immutable.Stream[Int] = Stream(1, ?)
10#::x                                    //> res0: scala.collection.immutable.Stream[Int] = Stream(10, ?)

val y = List(1,2,3,4)                     //> y  : List[Int] = List(1, 2, 3, 4)
10::y                                     //> res1: List[Int] = List(10, 1, 2, 3, 4)
like image 144
Plasty Grove Avatar answered Oct 21 '22 04:10

Plasty Grove


x #:: xs

returns

Stream.cons(x, xs)

which returns a Stream of an element x followed by a Stream xs.

like image 45
SHildebrandt Avatar answered Oct 21 '22 03:10

SHildebrandt