summaryrefslogtreecommitdiffstats
path: root/Scala/sandbox/1-recursion.scala
diff options
context:
space:
mode:
authorJérémy Zurcher <jeremy@asynk.ch>2013-04-03 23:41:42 +0200
committerJérémy Zurcher <jeremy@asynk.ch>2016-11-10 18:03:22 +0100
commitdadc875c05c830d15ee0aebea70aefaea6d3e55e (patch)
tree5e86616033f1cb49749d45ecc33021b99beec97f /Scala/sandbox/1-recursion.scala
parent1242f3e674a2dc1b2a6d4a6597c0d72d0596f469 (diff)
downloadcoursera-dadc875c05c830d15ee0aebea70aefaea6d3e55e.zip
coursera-dadc875c05c830d15ee0aebea70aefaea6d3e55e.tar.gz
Scala : rename files in sandbox
Diffstat (limited to 'Scala/sandbox/1-recursion.scala')
-rw-r--r--Scala/sandbox/1-recursion.scala30
1 files changed, 30 insertions, 0 deletions
diff --git a/Scala/sandbox/1-recursion.scala b/Scala/sandbox/1-recursion.scala
new file mode 100644
index 0000000..5488aea
--- /dev/null
+++ b/Scala/sandbox/1-recursion.scala
@@ -0,0 +1,30 @@
+
+object Recursion {
+
+ // Tail recursion - tail calls
+ // the function calls itself (or another one) as last action
+ // -> the function's stack frame can be reused!
+ // -> this is as efficient as a loop
+ def gcd(a: Int, b: Int): Int =
+ if (b == 0) a else gcd(b, a % b)
+
+ // there is still the multiplication to be performed
+ // -> the stack frame can't be reused
+ def fact(n: Int): Int =
+ if (n == 0) 1 else n * fact(n - 1)
+
+ // tail recursive version of factorial
+ def factr(n: Int): Int = {
+ def factIter(acc: Int, n: Int): Int =
+ if (n == 0) acc else factIter(acc * n, n - 1)
+ factIter(1, n)
+ }
+
+ def run = {
+ println("Recursion")
+ println(gcd(21, 56))
+ println(fact(4))
+ println(factr(4))
+ }
+
+}