Skip to content

Instantly share code, notes, and snippets.

@erlinis
Last active August 29, 2015 14:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save erlinis/8a4e427849cb7ea0012b to your computer and use it in GitHub Desktop.
Save erlinis/8a4e427849cb7ea0012b to your computer and use it in GitHub Desktop.
// Initial Exercises:
def sum(xs: List[Int]): Int = {
def calculate(total :Int, xs: List[Int]) :Int = {
if(xs.isEmpty) total
else calculate((total + xs.head), xs.tail)
}
calculate(0,xs)
}
def max(xs: List[Int]): Int = {
def findMax(max :Int, xs: List[Int]) :Int = {
if (xs.isEmpty) max
else if (max >= xs.head) findMax(max, xs.tail)
else findMax(xs.head, xs.tail)
}
findMax(xs.head, xs.tail)
}
// == Tests ==
test("sum of a few numbers") {
assert(sum(List(1,2,0)) === 3)
}
test("sum when the list contains negative elements") {
assert(sum(List(1,-2,5,-8)) === -4)
}
test("max of a few numbers") {
assert(max(List(3, 7, 2)) === 7)
}
test("max when the list contains repeated elements") {
assert(max(List(3, 17, 2,17, 16)) === 17)
}
test("max when the list contains negative elements") {
assert(max(List(-3, -4, -10, -2, -9)) === -2)
}
test("max when the list contains only one element") {
assert(max(List(6)) === 6)
}
test("max throws an exception if the xs List is empty") {
intercept[NoSuchElementException] {
max(List())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment