Example done

This commit is contained in:
Charles 2020-02-27 14:32:59 +01:00
parent 3813542c4e
commit 142189b317
2 changed files with 13 additions and 5 deletions

View File

@ -22,8 +22,10 @@ object Lists {
* @param xs A list of natural numbers * @param xs A list of natural numbers
* @return The sum of all elements in `xs` * @return The sum of all elements in `xs`
*/ */
def sum(xs: List[Int]): Int = ??? def sum(list: List[Int]): Int = list match {
case Nil => 0
case x :: xs => x + sum(xs)
}
/** /**
* This method returns the largest element in a list of integers. If the * This method returns the largest element in a list of integers. If the
* list `xs` is empty it throws a `java.util.NoSuchElementException`. * list `xs` is empty it throws a `java.util.NoSuchElementException`.
@ -37,5 +39,11 @@ object Lists {
* @return The largest element in `xs` * @return The largest element in `xs`
* @throws java.util.NoSuchElementException if `xs` is an empty list * @throws java.util.NoSuchElementException if `xs` is an empty list
*/ */
def max(xs: List[Int]): Int = ??? def max(xs: List[Int]): Int = {
def loop(ys: List[Int], max: Int): Int = ys match{
case head::tail => loop(tail, if(head>max) then head else max)
case Nil => max
}
loop(xs, Int.MinValue)
}
} }

View File

@ -24,7 +24,7 @@ class ListsSuite {
assert(1 + 1 == 2) assert(1 + 1 == 2)
@Test def `one plus one is three (0pts)?`: Unit = @Test def `one plus one is three (0pts)?`: Unit =
assert(1 + 1 == 3) // This assertion fails! Go ahead and fix it. assert(1 + 1 != 3) // This assertion fails! Go ahead and fix it.
/** /**
* One problem with the previous (failing) test is that JUnit will * One problem with the previous (failing) test is that JUnit will
@ -48,7 +48,7 @@ class ListsSuite {
* when writing tests. * when writing tests.
*/ */
@Test def `details why one plus one is not three (0pts)`: Unit = @Test def `details why one plus one is not three (0pts)`: Unit =
Assert.assertEquals(3, 1 + 1) // Fix me, please! Assert.assertEquals(2, 1 + 1) // Fix me, please!
/** /**
* Exceptional behavior of a methods can be tested using a try/catch * Exceptional behavior of a methods can be tested using a try/catch