Scala,用递归函数练习

时间:2014-03-26 12:59:01

标签: scala

试图解决书中的练习" Scala for the Impatient",我有一点问题。 (以下是我的解决方案)

1:编写for循环,用于计算字符串中所有字母的Unicode代码的乘积。例如," Hello"中的字符的乘积。是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:编写一个计算产品的函数产品(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
    
  2. 我希望有人可以帮助我。 最好的祝福, 弗朗西斯

6 个答案:

答案 0 :(得分:0)

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

考虑作为启动模式的阶乘递归函数,

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)

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

答案 1 :(得分:0)

也许我解决了:

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

答案 2 :(得分:0)

好的......最后我的代码可以运行:

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

我希望此代码段可以帮助其他人... 最好的祝福 弗朗西斯科

答案 3 :(得分:0)

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

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 :(得分:0)

我的尾递归函数的变体。没有使用过vars,这是一个加号。

  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))
  }

答案 5 :(得分:0)

def product (s:String): Long ={
  if (s.length==1) s(0) else s.head * s.product (s.tail)
}