summaryrefslogtreecommitdiffstats
path: root/Scala/example/src/main/scala
diff options
context:
space:
mode:
Diffstat (limited to 'Scala/example/src/main/scala')
-rw-r--r--Scala/example/src/main/scala/example/Lists.scala15
1 files changed, 13 insertions, 2 deletions
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)
+ }
+
}