2

我开始使用 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)
      }

    }
}
4

1 回答 1

1

如果你真的想打印结果,那么你可以这样做

def calculateSum(mainlist: List[Int]): Int = {
   def sum(currentElem: Int, thislist: List[Int]): Int = {
      if (thislist.isEmpty) curentElem
      else sum(currentElem + thislist.head, thislist.tail)
      //curentElem
   }
   val s = sum(0, mainlist)
   println("returned from Sum : " + s)
   s
}

如果您不这样做:

def calculateSum(mainlist: List[Int]): Int = {
   def sum(currentElem: Int, thislist: List[Int]): Int = {
      if (thislist.isEmpty) curentElem
      else sum(currentElem + thislist.head, thislist.tail)
      //curentElem
   }
   sum(0, mainlist)
}

一种使用模式匹配的方法(您将在 scala 中经常使用):

def calculateSum2(mainlist: List[Int]): Int = {
    def sum(currentElem: Int, thislist: List[Int]): Int = {
      thislist match {
        case Nil => currentElem
        case head :: tail => sum(currentElem + head, tail)
      }
    }
    sum(0, mainlist)
}

Nil是一个空列表。

于 2013-10-30T22:11:12.763 回答