I've recently started learning scala and as a part of an assignment, I need to write a function with following requirements: it has to be recursive and throw an exception in case of empty list. Tried this code, but the exception is always thrown.
def max(xs: List[Int]): Int =
if (xs.isEmpty) {
throw new NoSuchElementException("empty list")
} else {
if (xs.head > max(xs.tail)) xs.head else max(xs.tail)
}
}
edited: sorry for a mistake, of course the exception needs to be created with new. However, the function always fails with exception. tried require(), but it returns a Unit type, hence the compiler says it cannot be put in there. Is there a simple way of throwing an exception from a recursive function in scala whithout resolving to Try, Option and others?
Your code will always throw the exception because the recursion will always reduce to an empty list. My assumption is that you do not want to initiate any recursion if the list is empty. In that case, you can define an inner function to do the actual recursion.
def max(xs: List[Int]): Int = {
if (xs.isEmpty) {
throw new NoSuchElementException("empty list")
}
def iter(xs: List[Int], currMax: Int): Int = {
if(xs.isEmpty) {
currMax
}
else {
iter(xs.tail, if(xs.head > currMax) xs.head else currMax)
}
}
iter(xs.tail, xs.head)
}
Note: the above is just an quick, dirty example that has not been tested completed. And stylistically, both examples would benefit with the use of pattern matching as others have suggested.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다