From 142189b3175d4890e8ca1d4afab90eb6a943b0f5 Mon Sep 17 00:00:00 2001 From: Charles Date: Thu, 27 Feb 2020 14:32:59 +0100 Subject: [PATCH] Example done --- src/main/scala/example/Lists.scala | 14 +++++++++++--- src/test/scala/example/ListsSuite.scala | 4 ++-- 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/src/main/scala/example/Lists.scala b/src/main/scala/example/Lists.scala index 861f40e..8481c66 100644 --- a/src/main/scala/example/Lists.scala +++ b/src/main/scala/example/Lists.scala @@ -22,8 +22,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(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 * list `xs` is empty it throws a `java.util.NoSuchElementException`. @@ -37,5 +39,11 @@ 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 = { + 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) + } } 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