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) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The tail recursive version of sum function is: