Skip to content

Instantly share code, notes, and snippets.

@rbobillot
Last active September 30, 2015 21:10
Show Gist options
  • Save rbobillot/bb68c8e07c2634569c77 to your computer and use it in GitHub Desktop.
Save rbobillot/bb68c8e07c2634569c77 to your computer and use it in GitHub Desktop.
def factorial(n:Int):BigInt = ((1 to n) :\ BigInt(1))(_ * _)
// (1 to n).foldLeft(BigInt(1))(_ * _)
def recFactorial(n:Int):BigInt = if (n < 2) n else n * recFactorial(n-1)
def tailRecFactorial(n:Int):BigInt = {
def fac(n:Int, acc:BigInt):BigInt = n match {
case 1 => acc
case _ => fac(n-1, n*acc)
}
fac(n, 1)
}
def iterFactorial(n:BigInt) = {
var (acc,x) = (BigInt(1),n)
while (x > 1)
{
acc *= x
x -= 1
}
acc
}
/******************************************************************************/
/* Thanks to the lazyval system, each val will be printed after instanciation */
/******************************************************************************/
println("Processing...")
lazy val f1 = ("foldLeft, f(9000): ", factorial( 9000 )) //stack friendly
lazy val f2 = ("rec, f(9000): ", recFactorial( 9000 )) //stack killer
lazy val f3 = ("tailRec, f(9000): ", tailRecFactorial( 9000 )) //quite stack friendly
lazy val f4 = ("iter, f(9000): ", iterFactorial( 9000 )) //totally stack friendly
lazy val resList = f1 :: f2 :: f3 :: f4 :: Nil
resList.foreach (
x => {
val st = System.currentTimeMillis
print(
x._1
+ x._2.toString.take(5)
+ "...("
+ x._2.toString.size
+ " nums long)"
)
println( " ==> " + (System.currentTimeMillis - st)/1000.0 + " sec" )
}
)
@rbobillot
Copy link
Author

Je ne sais pas encore ce que je prefere entre
_la beaute de ce langage
_les features de ce langage

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment