Skip to content

Instantly share code, notes, and snippets.

@siliconsenthil
Created February 15, 2013 09:39
Show Gist options
  • Save siliconsenthil/4959395 to your computer and use it in GitHub Desktop.
Save siliconsenthil/4959395 to your computer and use it in GitHub Desktop.
Understanding the differences between Iteraion, Recursion and Tail Recursion using a Scala example.
object RecursionVsTailRecursion extends App {
def iterative_sum(a: Long, b: Long):Long = {
var result = 0L;
for(i <- a until b){result=result+i}
return result+b;
}
def sum(a: Long, b: Long): Long = if(a > b) 0 else a + sum(a+1, b)
def tail_sum(a: Long, b: Long): Long ={
def loop(a: Long, acc: Long): Long = {
if(a > b) acc
else loop(a+1, acc+a)
}
loop(a, 0)
}
val last = 6998
println(iterative_sum(1, last))
println(tail_sum(1, last))
println(sum(1,last))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment