Skip to content

Instantly share code, notes, and snippets.

@rupeshtr78
Created October 29, 2020 01:01
Show Gist options
  • Save rupeshtr78/c91018ca51776342c08019c57c53264d to your computer and use it in GitHub Desktop.
Save rupeshtr78/c91018ca51776342c08019c57c53264d to your computer and use it in GitHub Desktop.
tail-recursion
def sum(args:Int *): Int = {
@tailrec
def tailRecursionSum(argSeq: Seq[Int],result: Int): Int = {
if (argSeq == Nil) result
else
tailRecursionSum(argSeq.tail, result + argSeq.head)
}
tailRecursionSum(args,0)
}
sum(1,2,3,5,6,7,8,9)
def sumCase(args:Int *):Int = {
@tailrec
def helper(argsSeq:Seq[Int],result:Int):Int = argsSeq match {
case Nil => result
case ::(head, tl) => helper(tl,result+head)
}
helper(args,0)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment