Scala如何返回功能

时间:2016-12-23 06:24:43

标签: 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 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)
}

当它遍历到List的末尾时,应该返回cur_max值 然而,它只是继续前进。为什么不返回cur_max。
为了解决这个问题,我把Scala不推荐的'return'表达式('return cur_max')。

2 个答案:

答案 0 :(得分:2)

在Scala中,不应该只删除值 - 方法返回最后一次计算的语句。在您的情况下,您有两个陈述:

if(xs.isEmpty)
  cur_max

if(cur_max < xs.head)
  f(xs.head,xs.tail)
else
  f(cur_max,xs.tail)

因此返回第二个表达式的结果。 要修复它,请添加else语句:

if(xs.isEmpty)
  cur_max
else if(cur_max < xs.head)
  f(xs.head,xs.tail)
else
  f(cur_max,xs.tail)

答案 1 :(得分:0)

做了一些改变。其中一些只是代码样式更易读,就像在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)
        }

      }

基本上你的内部函数有一些例子,你命名为f

  • 列表为空 - &gt;你应该返回当前的最大值
  • 列表不为空且当前最大值小于剩余列表的第一个元素 - &gt;更新当前最大值并使用list tail
  • 调用该函数
  • 列表不为空且当前最大值>> =剩余列表的第一个元素 - &gt;使用列表尾部和相同的当前最大值
  • 调用该函数