Q1)What is tail-recursion and why in this scenario Scala is Better then Java?
Ans:
If the last action of a function is a call to another (possibly the same)
function, only a single stack frame is needed for both functions. Such calls are called
“tail calls”. In principle, tail calls can always re-use the stack frame of the calling
function. However, some run-time environments (such as the Java VM) lack the
primitives to make stack frame re-use for tail calls efficient. A production quality
Scala implementation is therefore only required to re-use the stack frame of a di-
rectly tail-recursive function whose last action is a call to itself. Other tail calls might
be optimized also, but one should not rely on this across implementations.
Example:
def gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b, a % b)
gcd(14, 21)
→if (21 == 0) 14 else gcd(21, 14 % 21)
→if (false) 14 else gcd(21, 14 % 21)
→gcd(21, 14 % 21)
→gcd(21, 14)
→if (14 == 0) 21 else gcd(14, 21 % 14)
→ → gcd(14, 21 % 14)
→gcd(14, 7)
→if (7 == 0) 14 else gcd(7, 14 % 7)
→ → gcd(7, 14 % 7)
→gcd(7, 0)
→if (0 == 0) 7 else gcd(0, 7 % 0)
→ → 7
No comments:
Post a Comment