summaryrefslogtreecommitdiffstats
path: root/Scala/example/src/main
diff options
context:
space:
mode:
authorJérémy Zurcher <jeremy@asynk.ch>2013-03-28 17:21:11 +0100
committerJérémy Zurcher <jeremy@asynk.ch>2016-11-10 18:03:20 +0100
commit6b137fb0ee01b203f4008ab85ad88a1c1aec3cbe (patch)
tree761a67b35d4efb8dafb1550fb08eaed00f7fade6 /Scala/example/src/main
parent292a74d4b221e481dfe278feb2c2bef24df60b0b (diff)
downloadcoursera-6b137fb0ee01b203f4008ab85ad88a1c1aec3cbe.zip
coursera-6b137fb0ee01b203f4008ab85ad88a1c1aec3cbe.tar.gz
Scala : complete example
Diffstat (limited to 'Scala/example/src/main')
-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)
+ }
+
}