- def fibonacci(n: Int): Int =
- @tailrec
- def fibHelper(n: Int, a: Int, b: Int): Int = n match
- case 0 => a
- case _ => fibHelper(n - 1, b, a + b)
- end fibHelper
- fibHelper(n, 0, 1)
- end fibonacci
tailrec annotation: compiler error if not tail-recursiveTail-recursive
- def factorial (n:Int) : Int =
- @tailrec
- def loop (m:Int, result:Int) : Int =
- if m > 1 then loop(m-1, m*result)
- else result
- loop(n,1)
Recursive (mutable)
- def factorial (n:Int) : Int =
- var result = 1
- def loop (m:Int) : Unit =
- if m > 1 then
- result = result*m
- loop(m-1)
- loop(n)
- result
- def factorial (n:Int) : Int =
- var result = 1
- var m = n
- def loop () : Unit =
- if m > 1 then
- result = result*m
- m = m-1
- loop()
- loop()
- result
Loop (mutable data)
- def factorial (n:Int) : Int =
- val result = 1
- var m = n
- while m > 1 do
- result = result * m
- m = m - 1
- result
* Time complexity $O(n)$ (additional penalty for activation records) * Space complexity $O(n)$
* Time complexity $O(n)$ (no penalty for creating activation records) * Space complexity $O(1)$