Skip to content

Instantly share code, notes, and snippets.

@ShaneDelmore
Created September 17, 2014 20:28
Show Gist options
  • Save ShaneDelmore/a4a6560e5952b20d2e33 to your computer and use it in GitHub Desktop.
Save ShaneDelmore/a4a6560e5952b20d2e33 to your computer and use it in GitHub Desktop.
sum and max in scala, tail recursive without an inner helper method
//If we have a list with at least two elements sum them and add them to the rest of the list
//else return the head of the list
@tailrec
def sum(xs: List[Int]): Int = xs match {
case h :: i :: rest => sum(h + i :: rest) //we have a list with at least two elements
case _ => xs.head
}
//If we have a list with at least two elements, remove the smallest and recurse
//else return the head of the list/We have
@tailrec
def max(xs: List[Int]): Int = xs match {
case h :: i :: rest => if (h > i) max(h :: rest) else max(i :: rest)
case _ => xs.head
}
@jackghm
Copy link

jackghm commented Feb 18, 2019

nice

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment