我实现了在列表中查找最大值。 我知道在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')。
答案 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
: