Advertisement
jules0707

Lists

Feb 27th, 2017
459
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 1.86 KB | None | 0 0
  1. package example
  2.  
  3. object Lists {
  4.  
  5.   /**
  6.    * This method computes the sum of all elements in the list xs. There are
  7.    * multiple techniques that can be used for implementing this method, and
  8.    * you will learn during the class.
  9.    *
  10.    * For this example assignment you can use the following methods in class
  11.    * `List`:
  12.    *
  13.    *  - `xs.isEmpty: Boolean` returns `true` if the list `xs` is empty
  14.    *  - `xs.head: Int` returns the head element of the list `xs`. If the list
  15.    *    is empty an exception is thrown
  16.    *  - `xs.tail: List[Int]` returns the tail of the list `xs`, i.e. the the
  17.    *    list `xs` without its `head` element
  18.    *
  19.    *  ''Hint:'' instead of writing a `for` or `while` loop, think of a recursive
  20.    *  solution.
  21.    *
  22.    * @param xs A list of natural numbers
  23.    * @return The sum of all elements in `xs`
  24.    */
  25.   def sum(xs: List[Int]): Int = {
  26.     if (!xs.isEmpty) {
  27.       if (xs.tail.isEmpty) xs.head
  28.       else (xs.head + sum(xs.tail))
  29.     } else 0
  30.   }
  31.  
  32.   /**
  33.    * This method returns the largest element in a list of integers. If the
  34.    * list `xs` is empty it throws a `java.util.NoSuchElementException`.
  35.    *
  36.    * You can use the same methods of the class `List` as mentioned above.
  37.    *
  38.    * ''Hint:'' Again, think of a recursive solution instead of using looping
  39.    * constructs. You might need to define an auxiliary method.
  40.    *
  41.    * @param xs A list of natural numbers
  42.    * @return The largest element in `xs`
  43.    * @throws java.util.NoSuchElementException if `xs` is an empty list
  44.    */
  45.   def max(xs: List[Int]): Int = {
  46.     if (xs.isEmpty) throw new java.util.NoSuchElementException("list must not be empty")
  47.  
  48.     def loop(max: Int, xxs: List[Int]): Int =
  49.       if (!xxs.isEmpty)
  50.         if (max > xxs.head) loop(max, xxs.tail)
  51.         else loop(xxs.head, xxs.tail)
  52.       else max
  53.     loop(xs.head, xs.tail)
  54.   }
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement