diff options
Diffstat (limited to 'Scala/sandbox/recursion.scala')
-rw-r--r-- | Scala/sandbox/recursion.scala | 29 |
1 files changed, 29 insertions, 0 deletions
diff --git a/Scala/sandbox/recursion.scala b/Scala/sandbox/recursion.scala new file mode 100644 index 0000000..e7c29a5 --- /dev/null +++ b/Scala/sandbox/recursion.scala @@ -0,0 +1,29 @@ + +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) + + println(gcd(21, 56)) + + // 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) + + println(fact(4)) + + // 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(factr(4)) + +} |