March 2014 update

This commit is contained in:
Ingy döt Net 2014-04-02 16:56:35 +00:00
parent 09687c4926
commit a25938f123
1846 changed files with 21876 additions and 5203 deletions

View file

@ -1,9 +1 @@
//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}
lazy val fib: Stream[Int] = 0 #:: 1 #:: fib.zip(fib.tail).map{case (a,b) => a + b}

View file

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

View file

@ -1,7 +1,13 @@
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)
// 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