InterviewSolution
| 1. |
What do you mean by tail-recursion? |
|
Answer» Scala supports tail recursion, which sets it apart from other languages. Recursion involves breaking a problem down into smaller sub-problems and calling itself to RESOLVE each of them. Simply put, recursion can be thought of as a function calling itself. Tail recursion REFERS to executing the last statement recursively. As a result, these functions are more performant since they utilize tail call optimization. They do not add another stack frame to memory, but rather keep calling functions. If you are experiencing a stack OVERFLOW with your recursive functions, a tail-recursive function is your remedy. In addition, tail recursion makes your code faster and memory-constant. @tailrecdef FuntionName(Parameter1, Parameter2, ...): type = …Example: import scala.annotation.tailrec object InterviewBit { def SCALER(a: Int, b: Int): Int = { @tailrec def scaler(x:Int, y:Int): Int= { if (y == 0) x else scaler(y, x % y) } scaler(a, b) } def main(args:Array[String]) { println(SCALER(11, 7)) } }Output: 4 |
|