Skip to content

Instantly share code, notes, and snippets.

@alexanderscott
Created September 14, 2012 13:05
Show Gist options
  • Save alexanderscott/3721802 to your computer and use it in GitHub Desktop.
Save alexanderscott/3721802 to your computer and use it in GitHub Desktop.
Tail recursive functions written in Scala
/**
* 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)
}
@humayun0156
Copy link

humayun0156 commented Aug 31, 2016

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