Created
February 15, 2013 09:39
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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