Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Scala如何在函数中返回_Scala_Function_Functional Programming_Return - Fatal编程技术网

Scala如何在函数中返回

Scala如何在函数中返回,scala,function,functional-programming,return,Scala,Function,Functional Programming,Return,我实现了在列表中查找最大值。 我知道在Scala中,您不必使用“return”,只需放弃它即可。 所以我就这样写, def max(xs: List[Int]):Int={ if(xs.isEmpty) throw new java.util.NoSuchElementException def f(cur_max:Int, xs:List[Int]):Int={ if(xs.isEmpty) cur_max // <- it doesn't return va

我实现了在列表中查找最大值。 我知道在Scala中,您不必使用“return”,只需放弃它即可。 所以我就这样写,

def max(xs: List[Int]):Int={
  if(xs.isEmpty) throw new java.util.NoSuchElementException
  def f(cur_max:Int, xs:List[Int]):Int={
    if(xs.isEmpty)
      cur_max // <- it doesn't return value but just keep going below code.
    if(cur_max < xs.head)
      f(xs.head,xs.tail)
    else
      f(cur_max,xs.tail)
  }
  f(xs.head,xs)
}
defmax(xs:List[Int]):Int={
如果(xs.isEmpty)抛出新的java.util.NoSuchElementException
def(cur_max:Int,xs:List[Int]):Int={
if(xs.isEmpty)

cur_umax/在Scala中,不应该仅仅是drop value-method返回最后一个求值语句。在您的情况下,您有两个语句:

if(xs.isEmpty)
  cur_max

if(电流最大值
因此返回第二个表达式1的结果。 要修复它,请添加else语句:

if(xs.isEmpty)
  cur_max
else if(cur_max < xs.head)
  f(xs.head,xs.tail)
else
  f(cur_max,xs.tail)
if(xs.isEmpty)
cur_max
否则,如果(电流最大值
做了一些更改。其中一些更改只是将样式编码为更具可读性,比如在
if
表达式上加括号

def max(xs: List[Int]): Int = {

        def f(cur_max: Int, xs: List[Int]): Int = {
          if (xs.isEmpty) {
            cur_max // <- it doesn't return value but just keep going below code.
          } else {
            if (cur_max < xs.head) {
              f(xs.head, xs.tail)
            }
            else {
              f(cur_max, xs.tail)
            }
          }
        }

        if (xs.isEmpty) {
          throw new java.util.NoSuchElementException
        } else {
          f(xs.head, xs.tail)
        }

      }
defmax(xs:List[Int]):Int={
def(cur_max:Int,xs:List[Int]):Int={
if(xs.isEmpty){

cur_max//第二个if块应该是else-if而不是单独的if块吗?
def max(xs: List[Int]): Int = {

        def f(cur_max: Int, xs: List[Int]): Int = {
          if (xs.isEmpty) {
            cur_max // <- it doesn't return value but just keep going below code.
          } else {
            if (cur_max < xs.head) {
              f(xs.head, xs.tail)
            }
            else {
              f(cur_max, xs.tail)
            }
          }
        }

        if (xs.isEmpty) {
          throw new java.util.NoSuchElementException
        } else {
          f(xs.head, xs.tail)
        }

      }