Skip to content

Instantly share code, notes, and snippets.

@cedricbastin
Last active December 8, 2015 07:27
Show Gist options
  • Save cedricbastin/d302e229d31cf01b428a to your computer and use it in GitHub Desktop.
Save cedricbastin/d302e229d31cf01b428a to your computer and use it in GitHub Desktop.
The Pascal triangle implemented recursively by it's cell relation definition using lazy scala streams
import scala.collection.immutable.Stream
//create the Pascal triangle using scala Streams
object Pascal extends App {
def plus(a:Int, b:Int) = a+b
def map2(str:Stream[Int], f:(Int, Int) => Int):Stream[Int] = str match { //pattern matcher doesn't seem to work properly
case Stream.Empty => str
case _ #:: Stream.Empty => str
case a #:: tail => f(a, tail.head) #:: map2(tail, f)
}
val pascal:Stream[Stream[Int]] = (1 #:: Stream.Empty) #:: pascal.map(prev => map2(0 #:: prev, plus))
def printX(a:Any) = print(a+" ")
pascal take 10 foreach {x => x foreach {printX(_)}; println()}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment