【问题标题】:Scala, Exercise with recursive functionScala,递归函数练习
【发布时间】:2014-03-26 12:59:00
【问题描述】:

试图解决“不耐烦的Scala”一书中的练习,我有一个小问题。 (以下是我的解决方案)

1:编写一个for循环来计算字符串中所有字母的Unicode代码的乘积。例如,“你好”中的字符的乘积是 825152896

    var p = 1; val S = "Hello"                          
    for (i <- S) p*= i
    println(p)

2:在不编写循环的情况下解决前面的练习。 (提示:查看 String0ps Scaladoc。)

    val St="Hello".map(_.toInt).product ; println(St)

3:编写一个计算乘积的函数 product(s : String),如前面练习中所述。

    def product(s: String)={
      val S=s; println(S.map(_.toInt).product)
    }
    product("Hello")
  1. 使前面练习的函数成为递归函数。

    ??? I do not know how to do it
    

我希望有人可以帮助我。 最好的祝福, 弗朗切斯科

【问题讨论】:

  • 递归函数是一个调用自身的函数,但在调用之前会检查终止条件以避免无限递归。要递归计算乘积,您需要在函数式语言中实现类似于fold 函数的函数,并将 1 作为累加器的初始值和字符串传递。然后该函数将检查字符串是否为空,并使用字符串的尾部调用自身,如果不是,则使用调整后的累加器。终止时,累加器的值就是结果。

标签: scala


【解决方案1】:

使用众所周知的递归函数并修改它们以适应不同的问题可能证明是一种非常有用的方法。

将阶乘递归函数视为一种启动模式,

def factorial(n: Int): Int = 
  if (n <= 1) 1 else n * factorial (n-1)

现在考虑阶乘递归函数,其中假设输入是从 1 到 n 的整数列表,因此请注意输入列表被简化为基本情况的方式,

def factorial(xs: List[Int]): Int = 
  if (xs.isEmpty) 1 else xs.head * factorial (xs.tail)

这种转换现在更接近于字符串输入的原始问题的解决方案。

【讨论】:

    【解决方案2】:

    好的……我的代码终于可以工作了:

    def prodRec(s: String): Int = { 
        if (s.toList.isEmpty) 1     
        else {                  
          s.toList.head * prodRec(s.tail)
        }
    }
    println(prodRec("Hello"))
    

    我希望这段代码 sn-p 可以帮助其他人...... 最好的祝福 法国

    【讨论】:

      【解决方案3】:

      下面是另一种编写产品递归解决方案的方法:

      def getProduct(s: String):Int = {
      
          def accumulate(acc:Int,ch:Array[Char]):Int = {
              ch.headOption match {
                  case None => acc
                  case Some(x) => accumulate(acc*x.toInt,ch.tail)
              }
          }
          accumulate(1,s.toArray)
      }
      

      【讨论】:

        【解决方案4】:

        也许我解决了:

        def prodRec(s: String): Int = {
            var s2 =s.toList
            if (s2.isEmpty) 1 
            else {
              s2.head * prodRec (s.tail)
            }
        }
        

        【讨论】:

        • 对不起,我犯了一个错误。甚至不以这种方式工作。我仍在寻找一些提示。
        【解决方案5】:

        我的尾递归函数变体。没有使用任何变量,这是一个优点。

          def product(s: String): Unit = {
            @tailrec
            def help(z: Long, array: Array[Char]): Long = {
              if (array.isEmpty) z else help(z * array.head.toInt, array.tail)
            }
            print(help(1L, s.toCharArray))
          }
        

        【讨论】:

          【解决方案6】:
          def product (s:String): Long ={
            if (s.length==1) s(0) else s.head * s.product (s.tail)
          }
          

          【讨论】:

          • 纯代码答案不如带有解释性文本的代码有用。对于一个像这个一样古老的问题,已经有这么多答案,指出你的答案与任何/所有之前的答案有何不同是特别有帮助的。
          猜你喜欢
          • 1970-01-01
          • 2017-11-12
          • 2015-03-01
          • 1970-01-01
          • 2012-07-02
          • 1970-01-01
          • 2017-02-10
          • 1970-01-01
          • 2017-11-28
          相关资源
          最近更新 更多