Author | Message |
---|---|
Vanquish39
Posts: 134
|
Posted 13:51 Sep 21, 2012 |
Here is also another implementation of max function.
def max(xs: List[Int]): Int =
if(xs.isEmpty) throw new java.util.NoSuchElementException else max(xs.head, xs.tail);
def max(current_head: Int, current_tail: List[Int]) : Int =
if(current_tail.isEmpty) return current_head;
else
if(current_head < current_tail.head)
max(current_tail.head, current_tail.tail);
else
max(current_head, current_tail.tail);
|
M_Hsu
Posts: 19
|
Posted 13:59 Sep 23, 2012 |
Here's another version using try-catch and a structure similar to the example in lecture:
def max(xs: List[Int]): Int = {
def returnLarger(num1: Int, num2: Int): Int = if (num1 >= num2) num1 else num2
def maxIter(list: List[Int], largest: Int): Int = if (list.isEmpty || list.size==1) largest else maxIter(list.tail, returnLarger(list.tail.head, largest))
try {
maxIter(xs, xs.head)
} catch {
case e: Exception => throw new NoSuchElementException
}
}
}
|