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)
}
@mminer
Copy link

mminer commented May 4, 2014

FYI, neither sum function (yours or @pedrovgs's) is tail recursive. Consider a list of numbers [1, 2, 3, 4, 5]. This expands to:

1 + sum([2, 3, 4, 5])
1 + (2 + sum[3, 4, 5])
1 + (2 + (3 + sum[4, 5]))
1 + (2 + (3 + (4 + sum[5])))
1 + (2 + (3 + (4 + 5)))

i.e. not the pattern you expect in tail recursion.

@jixu
Copy link

jixu commented May 25, 2014

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.

@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