Created
September 17, 2014 20:28
-
-
Save ShaneDelmore/a4a6560e5952b20d2e33 to your computer and use it in GitHub Desktop.
sum and max in scala, tail recursive without an inner helper method
This file contains 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
//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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
nice