Scala如何在函数中返回
我实现了在列表中查找最大值。 我知道在Scala中,您不必使用“return”,只需放弃它即可。 所以我就这样写,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
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)
}
}