From 756f674f57faf984b53d13fa40df5f353c27b8c9 Mon Sep 17 00:00:00 2001 From: beauvill Date: Thu, 19 Sep 2019 16:35:55 +0200 Subject: [PATCH] Fixed the sum and max functions of Lists --- src/main/scala/example/Lists.scala | 8 ++++++-- src/test/scala/example/ListsSuite.scala | 4 ++-- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/src/main/scala/example/Lists.scala b/src/main/scala/example/Lists.scala index 861f40e..76fb011 100644 --- a/src/main/scala/example/Lists.scala +++ b/src/main/scala/example/Lists.scala @@ -22,7 +22,7 @@ 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 = if xs.isEmpty then 0 else xs.head + sum(xs.tail) /** * 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` * @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 } diff --git a/src/test/scala/example/ListsSuite.scala b/src/test/scala/example/ListsSuite.scala index ed42759..5b6930d 100644 --- a/src/test/scala/example/ListsSuite.scala +++ b/src/test/scala/example/ListsSuite.scala @@ -24,7 +24,7 @@ class ListsSuite { assert(1 + 1 == 2) @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 @@ -48,7 +48,7 @@ class ListsSuite { * when writing tests. */ @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