Skip to content

Instantly share code, notes, and snippets.

@tobnee
Created March 7, 2011 08:56
Show Gist options
  • Save tobnee/858249 to your computer and use it in GitHub Desktop.
Save tobnee/858249 to your computer and use it in GitHub Desktop.
Scala script which demonstrates how tail recursion can be applied in Scala
/*
* Scala script which demonstrates how tail recursion can be applied in
* Scala and what the value of tail recursion is in terms of applicability
* The functions in this example add all a values (which can be divided by 3)
* up to a given max.
*/
// help function to find the first value which can be divided by 3
def findStart(upTo:Int):Int = {
if (upTo%3==0 || upTo<0) upTo
else findStart(upTo-1)
}
// recursive implementation
def sumMod(upTo:Int):Int = {
def sumModInt(upTo:Int):Int = {
if(upTo<0) 0
else upTo + sumModInt(upTo-3)
}
sumModInt(findStart(upTo))
}
// implementation using the scala libs
def sumModScalaLib(end:Int) = {
0 to end by 3 sum
}
// tail-recursive implementation
def sumModTail(upTo:Int):Int = {
def sumModInt(upTo:Int, sum:Int):Int = {
if(upTo<0) sum
else sumModInt(upTo-3, upTo + sum)
}
sumModInt(findStart(upTo), 0);
}
// function to measure the time a function application takes
def time[T](code: => T):(Long, T) = {
import System.{currentTimeMillis => cTime}
val start = cTime
val returnValue = code
(cTime-start, returnValue)
}
def run(upTo:Int) {
val tailRec = time{
sumModTail(upTo)
}
printf("tail recusion: %s \n", tailRec)
val lib = time{
sumModScalaLib(upTo)
}
printf("scalaLib: %s \n", lib)
val rec = time{
sumMod(upTo)
}
printf("recusion normal: %s \n", lib)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment