From 6b137fb0ee01b203f4008ab85ad88a1c1aec3cbe Mon Sep 17 00:00:00 2001 From: Jérémy Zurcher Date: Thu, 28 Mar 2013 17:21:11 +0100 Subject: Scala : complete example --- Scala/example/src/main/scala/example/Lists.scala | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) (limited to 'Scala/example/src/main') diff --git a/Scala/example/src/main/scala/example/Lists.scala b/Scala/example/src/main/scala/example/Lists.scala index 4e5feee..628486c 100644 --- a/Scala/example/src/main/scala/example/Lists.scala +++ b/Scala/example/src/main/scala/example/Lists.scala @@ -23,7 +23,11 @@ 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 = { + def sumIter(acc: Int, xs: List[Int]): Int = + if (xs.isEmpty) acc else sumIter(acc + xs.head, xs.tail) + sumIter(0, xs) + } /** * This method returns the largest element in a list of integers. If the @@ -38,5 +42,12 @@ 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 maxInt(a: Int, b: Int) = if (a>b) a else b + def maxIter(max: Int, xs: List[Int]): Int = + if (xs.isEmpty) max else maxIter(maxInt(max,xs.head), xs.tail) + if (xs.isEmpty) throw new NoSuchElementException + else maxIter(Integer.MIN_VALUE, xs) + } + } -- cgit v1.2.3