How to throw an exception from a recursive function in scala that returns Int

Pri1me

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?

user1591210

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] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

분류에서Dev

Tail Recursive Factorial Function in Scala

분류에서Dev

Python recursive function returns None instead of value

분류에서Dev

how to pass a value from a recursive function into an array in a different method

분류에서Dev

How to make @NotNull throw runtime exception?

분류에서Dev

Returning a value from a recursive function

분류에서Dev

ASP.NET MVC: RouteLink from Area to Root throw Exception

분류에서Dev

ASP.NET MVC : RouteLink from Area to Root throw Exception

분류에서Dev

Modular exponentiation function returns the wrong int value

분류에서Dev

Make custom exception throw automatically

분류에서Dev

JComboBox Null pointer Exception. Need to get Int from box and set int as selected int from box

분류에서Dev

How to type a function that returns the single element in an array that lives in a property from an object

분류에서Dev

Return statement in recursive function with try-except structure not executed / returns NoneType

분류에서Dev

How to throw exception if version of vim is less than a desired target? (.vimrc/init.vim)

분류에서Dev

Quick Sort Python Recursion - how does the recursive function work

분류에서Dev

How to change a function which returns local variable

분류에서Dev

How do I fix a function that returns NAN?

분류에서Dev

scala match from list of Boolean to list of summed Int

분류에서Dev

recursive function building in R

분류에서Dev

Recursive PHP Function

분류에서Dev

argument concatenation in a recursive function

분류에서Dev

Memoise on recursive function

분류에서Dev

Recursive function with IO

분류에서Dev

Discord.js Throw exception in .catch

분류에서Dev

When does an istreambuf_iterator throw an exception?

분류에서Dev

XSLT 2.0 error handling: throw exception to javascript

분류에서Dev

Why does this for loop that iterates an array throw an exception?

분류에서Dev

Int를 반환하는 Scala의 재귀 함수에서 예외를 throw하는 방법

분류에서Dev

How to catch exception from a system() command in python

분류에서Dev

How to throw a ball into a cup?

Related 관련 기사

  1. 1

    Tail Recursive Factorial Function in Scala

  2. 2

    Python recursive function returns None instead of value

  3. 3

    how to pass a value from a recursive function into an array in a different method

  4. 4

    How to make @NotNull throw runtime exception?

  5. 5

    Returning a value from a recursive function

  6. 6

    ASP.NET MVC: RouteLink from Area to Root throw Exception

  7. 7

    ASP.NET MVC : RouteLink from Area to Root throw Exception

  8. 8

    Modular exponentiation function returns the wrong int value

  9. 9

    Make custom exception throw automatically

  10. 10

    JComboBox Null pointer Exception. Need to get Int from box and set int as selected int from box

  11. 11

    How to type a function that returns the single element in an array that lives in a property from an object

  12. 12

    Return statement in recursive function with try-except structure not executed / returns NoneType

  13. 13

    How to throw exception if version of vim is less than a desired target? (.vimrc/init.vim)

  14. 14

    Quick Sort Python Recursion - how does the recursive function work

  15. 15

    How to change a function which returns local variable

  16. 16

    How do I fix a function that returns NAN?

  17. 17

    scala match from list of Boolean to list of summed Int

  18. 18

    recursive function building in R

  19. 19

    Recursive PHP Function

  20. 20

    argument concatenation in a recursive function

  21. 21

    Memoise on recursive function

  22. 22

    Recursive function with IO

  23. 23

    Discord.js Throw exception in .catch

  24. 24

    When does an istreambuf_iterator throw an exception?

  25. 25

    XSLT 2.0 error handling: throw exception to javascript

  26. 26

    Why does this for loop that iterates an array throw an exception?

  27. 27

    Int를 반환하는 Scala의 재귀 함수에서 예외를 throw하는 방법

  28. 28

    How to catch exception from a system() command in python

  29. 29

    How to throw a ball into a cup?

뜨겁다태그

보관