-
-
Save eng-atwijukire/4cb95e4223e7c2774660314ad174f04e to your computer and use it in GitHub Desktop.
Coursera, progfun1: Solution to the Example assignment
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package example | |
import java.util.NoSuchElementException | |
object Lists { | |
/** | |
* This method computes the sum of all elements in the list xs. There are | |
* multiple techniques that can be used for implementing this method, and | |
* you will learn during the class. | |
* | |
* For this example assignment you can use the following methods in class | |
* `List`: | |
* | |
* - `xs.isEmpty: Boolean` returns `true` if the list `xs` is empty | |
* - `xs.head: Int` returns the head element of the list `xs`. If the list | |
* is empty an exception is thrown | |
* - `xs.tail: List[Int]` returns the tail of the list `xs`, i.e. the the | |
* list `xs` without its `head` element | |
* | |
* ''Hint:'' instead of writing a `for` or `while` loop, think of a recursive | |
* solution. | |
* | |
* @param xs A list of natural numbers | |
* @return The sum of all elements in `xs` | |
*/ | |
def sum(xs: List[Int]): Int = { | |
def loop(xs: List[Int], sum: Int = 0): Int = | |
if (xs.isEmpty) sum | |
else loop(xs.tail, sum + xs.head) | |
loop(xs) | |
} | |
/** | |
* This method returns the largest element in a list of integers. If the | |
* list `xs` is empty it throws a `java.util.NoSuchElementException`. | |
* | |
* You can use the same methods of the class `List` as mentioned above. | |
* | |
* ''Hint:'' Again, think of a recursive solution instead of using looping | |
* constructs. You might need to define an auxiliary method. | |
* | |
* @param xs A list of natural numbers | |
* @return The largest element in `xs` | |
* @throws java.util.NoSuchElementException if `xs` is an empty list | |
*/ | |
def max(xs: List[Int]): Int = { | |
def loop(xs: List[Int], max: Int = 0): Int = | |
if (xs.isEmpty) max | |
else loop(xs.tail, if (xs.head > max) xs.head else max) | |
if (xs.isEmpty) throw new NoSuchElementException() | |
else loop(xs) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment