This commit is contained in:
Ingy döt Net 2013-04-10 21:29:02 -07:00
parent 764da6cbbb
commit db842d013d
19005 changed files with 197040 additions and 7 deletions

View file

@ -0,0 +1,5 @@
def fib(i:Int):Int = i match{
case 0 => 0
case 1 => 1
case _ => fib(i-1) + fib(i-2)
}

View file

@ -0,0 +1,9 @@
//syntactic sugar for Stream.cons, this is unnecessary but makes the definition prettier
//Stream.cons(head,stream) becomes head::stream
//I think 2.8 will have #::
class PrettyStream[A](str: =>Stream[A]) {
def ::(hd: A) = Stream.cons(hd, str)
}
implicit def streamToPrettyStream[A](str: =>Stream[A]) = new PrettyStream(str)
def fib: Stream[Int] = 0 :: 1 :: fib.zip(fib.tail).map{case (a,b) => a + b}

View file

@ -0,0 +1 @@
def fib: Stream[Int] = 0 #:: 1 #:: fib.zip(fib.tail).map{case (a,b) => a + b}

View file

@ -0,0 +1,7 @@
def fib(i:Int):Int = {
def fib2(i:Int, a:Int, b:Int):Int = i match{
case 1 => b
case _ => fib2(i-1, b, a+b)
}
fib2(i,1,0)
}

View file

@ -0,0 +1,13 @@
// Fibonacci using BigInt with Stream.foldLeft optimized for GC (Scala v2.9 and above)
// Does not run out of memory for very large Fibonacci numbers
def fib(n:Int) = {
def series(i:BigInt,j:BigInt):Stream[BigInt] = i #:: series(j, i+j)
series(1,0).take(n).foldLeft(BigInt("0"))(_+_)
}
// Small test
(0 to 13) foreach {n => print(fib(n).toString + " ")}
// result: 0 1 1 2 3 5 8 13 21 34 55 89 144 233