Created
September 14, 2012 13:05
-
-
Save alexanderscott/3721802 to your computer and use it in GitHub Desktop.
Tail recursive functions written in Scala
This file contains hidden or 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
/** | |
* Proprietary work of Alex Ehrnschwender | |
*/ | |
def sum(xs: List[Int]): Int = { | |
var i = 0 | |
if (xs.isEmpty) i else i + xs.head + sum(xs.tail) | |
} | |
def max(xs: List[Int]): Int = { | |
def comparator(i: Int, j: List[Int]): Int = { | |
if(j.tail.isEmpty) i else | |
if(i > j.tail.head) comparator(i, j.tail) else | |
max(j.tail) | |
} | |
if(!xs.isEmpty && xs.tail.isEmpty) xs.head else | |
if(xs.head > xs.tail.head) comparator(xs.head, xs.tail) else | |
max(xs.tail) | |
} |
The tail recursive version of sum function is:
def sum(xs: List[Int]): Int = {
def loop(sum: Int, xs: List[Int]): Int = {
if (xs.isEmpty) sum
else loop(sum + xs.head, xs.tail)
}
loop(0, xs)
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I searched google for a scala tail-recursive version of list insert function and landed on this page. But I have to point out your implementation of "sum" is not tail-recursive.
You should use a helper function and an accumulator to achieve it.