此函数应该返回列表中所有数字的总和,但是当我运行它时,我总是返回ans=0
。
def sum(st: List[Int]): Int = {
var ans=0
def combine(st: List[Int], ans:Int): Int = {
if (st.isEmpty) ans else combine(st.tail, ans)
}
ans
}
它出了什么问题?
答案 0 :(得分:5)
您需要将列表的头部添加到ans
。目前你正在递归但实际上没有使用列表的头部。
e.g。我认为你需要类似下面的内容,你可以将列表的头部添加到余数的总和中。
scala> def sum(st: List[Int]): Int =
| {
| if (st.isEmpty) {
| 0
| }
| else {
| st.head + sum(st.tail)
| }
| }
sum: (st: List[Int])Int
答案 1 :(得分:3)
1)你没有调用内部方法组合 - 你只是回复了ans,因为它被非正式化为0。
2)联合收割机并没有真正做任何事情
我认为您要编写的代码如下:
def sum(st: List[Int]): Int = {
def combine(st: List[Int], ans:Int): Int = {
if (st.isEmpty) ans else combine(st.tail, ans + st.head)
}
combine(st, 0)
}
但当然较短的版本是:
st.foldLeft(0)(_ + _)
或只是
st.sum
使用Numeric的标准类型类实例:IntIsIntegral:
http://www.scala-lang.org/api/current/index.html#scala.math.Numeric $$ IntIsIntegral $
答案 2 :(得分:2)
您已在方法combine
中定义了方法sum
,但您没有调用combine
(combine
以外的方法,因此永远不会调用它)。如果不调用该方法,则不会执行该方法;只是定义方法并不意味着它已被执行。
如果你想用函数式编程,你也应该避免使用可变变量(var
);使用不可变值(val
)代替。
此外,您的combine
方法并未对任何内容求和(它不会在任何地方修改ans
或使用列表中的任何值。)
答案 3 :(得分:1)
我同意Brian回答你的解决方案无效的原因。
此外,使用foldLeft:还有更短的方法来使用Scala序列的API(List实现),使用foldLeft:
def sum(st: List[Int]): Int = {
st.foldLeft(0)(_ + _)
}
答案 4 :(得分:0)
foldLeft,甚至更好,sum是hedefalk提到的首选选项。