【问题标题】:Returning Value in Functional Programming函数式编程中的返回值
【发布时间】: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 .... )as currentElem 没有在 Sum 函数之外定义。

标签: scala functional-programming


【解决方案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 是一个空列表。

【讨论】:

  • 谢谢!我收到一个有线错误:found.error: type mismatch; found : Unit required: Int println("从 Sum 中返回:" + s); ^ 发现一个错误
  • 我做了一些更改。看看吧。
  • 该解决方案的“问题”是可以传递currentElem 的初始值。例如我可以调用sum(1, mainlist),这将导致总和+ 1。您希望currentElem 始终为0。因此,请执行calculateSum2 之类的操作,其中只有一个参数(列表)。
猜你喜欢
  • 2022-12-07
  • 1970-01-01
  • 1970-01-01
  • 2020-06-29
  • 2015-05-19
  • 1970-01-01
  • 2019-01-05
  • 2019-01-27
  • 2021-10-22
相关资源
最近更新 更多