Skip to content

Commit

Permalink
Solve 0th assignment
Browse files Browse the repository at this point in the history
  • Loading branch information
alexander-myltsev committed Dec 9, 2013
1 parent 444bf7c commit 6190339
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 6 deletions.
12 changes: 10 additions & 2 deletions a0-example/src/main/scala/example/Lists.scala
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package example

import common._
import scala.collection.immutable.Nil

object Lists {
/**
Expand All @@ -23,7 +24,10 @@ object Lists {
* @param xs A list of natural numbers
* @return The sum of all elements in `xs`
*/
def sum(xs: List[Int]): Int = ???
def sum(xs: List[Int]): Int = xs match {
case Nil => 0
case x :: xs => x + sum(xs)
}

/**
* This method returns the largest element in a list of integers. If the
Expand All @@ -38,5 +42,9 @@ object Lists {
* @return The largest element in `xs`
* @throws java.util.NoSuchElementException if `xs` is an empty list
*/
def max(xs: List[Int]): Int = ???
def max(xs: List[Int]): Int = xs match {
case Nil => throw new java.util.NoSuchElementException()
case x :: Nil => Int.MinValue
case x :: xs => math.max(x, max(xs))
}
}
14 changes: 10 additions & 4 deletions a0-example/src/test/scala/example/ListsSuite.scala
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,8 @@ class ListsSuite extends FunSuite {
*
* This allows tests to be written in a more readable manner:
*/
test("one plus one is three?") {
assert(1 + 1 == 3) // This assertion fails! Go ahead and fix it.
test("one plus two is three") {
assert(1 + 2 == 3) // This assertion fails! Go ahead and fix it.
}


Expand All @@ -72,7 +72,7 @@ class ListsSuite extends FunSuite {
* We recommend to always use the `===` equality operator when writing tests.
*/
test("details why one plus one is not three") {
assert(1 + 1 === 3) // Fix me, please!
assert(1 + 2 === 3) // Fix me, please!
}


Expand Down Expand Up @@ -121,4 +121,10 @@ class ListsSuite extends FunSuite {
test("max of a few numbers") {
assert(max(List(3, 7, 2)) === 7)
}
}

test("no max in empty list") {
intercept[java.util.NoSuchElementException] {
max(List())
}
}
}

0 comments on commit 6190339

Please sign in to comment.