【发布时间】:2013-10-31 07:23:32
【问题描述】:
我开始使用 Scala 探索“函数式编程”。 我想知道我们如何在函数式编程中返回一个值。我写了一个递归函数
def calculateSum(mainlist: List[Int]): Int = {
def Sum(curentElem:Int = 0,thislist:List[Int],): Int = {
if (list.isEmpty) curentElem
else loop(curentElem + thislist.head, thislist.tail)
//curentElem
}
Sum((List(0,1,2,3,4)))
println ("returned from Sum : " + curentElem)
}
- 我是否应该在函数的最后一行添加“curentElem”(就像我在注释行中所做的那样)!
更新: 我刚刚解决了这个问题:
object HelloScala {
def main(args: Array[String]): Unit = {
val s = sum(0, List(0,1,2,3,4))
println("returned from Sum : " + s )
}
def sum(currentElem: Int, thislist: List[Int]): Int = {
thislist match {
case Nil => currentElem
case head :: tail => sum(currentElem + head, tail)
}
}
}
【问题讨论】:
-
你的意思可能是
println (Sum .... )ascurrentElem没有在 Sum 函数之外定义。
标签: scala functional-programming