Fixed the sum and max functions of Lists

This commit is contained in:
beauvill 2019-09-19 16:35:55 +02:00
parent afa68c33a6
commit 756f674f57
2 changed files with 8 additions and 4 deletions

View File

@ -22,7 +22,7 @@ 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(xs: List[Int]): Int = if xs.isEmpty then 0 else xs.head + sum(xs.tail)
/** /**
* 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
@ -37,5 +37,9 @@ 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 = if xs.isEmpty
then throw new NoSuchElementException
else if xs.size == 1 then xs.head else compare(max(xs.tail), xs.head)
def compare(x: Int, y: Int): Int = if x >= y then x else y
} }

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