0

我正在尝试在 scala 中编写一个函数来查找Sum of any (passed) function from a to b. 此外,我正在尝试以尾部递归的方式进行操作。我管理了一个tailwise recursive factorial function,所以现在我想将它传递给“Summation”函数并让它找到从下限a到上限的所有阶乘的总和b。这是我到目前为止所拥有的

object Sum {
  def Summation( f : Double => Double , a: Double , b: Double):Double = {
    def tailwiseSummation(accumulator:Double , count:Double):Double = {
      if(count > b) accumulator
      else tailwiseSummation(accumulator + f, a+1) // i dont know what to do here
    } 
  }

  def Factorial(num: Double): Double = { // i want to pass this function to `Summation`
    def tailwise(accumulator: Double, deprecator: Double): Double = {
      if (deprecator == 0) accumulator
      else tailwise(accumulator * deprecator, deprecator - 1) // deprecator deprecating 1 unit at a time
    }
    tailwise(1, num)
  }
}

有人可以帮忙吗?

4

2 回答 2

1

范围内的通用递归可能是这样的:

def makeSum(f: Double => Double, a:Double, b:Double, step:Double = 1.0):Double = {
  def makeSumAcc(f:Double =>Double, a:Double, b:Double, acc:Double) = {
    if (a>=b) acc
    else makeSumAcc(f, a+step, b, acc+f(a))
  }
  makeSum(f, a, b, 0)
}
于 2013-10-17T16:02:51.430 回答
1

你几乎拥有它。在递归调用中调用f并加count1 。此外,您需要初始化函数,就像.counttailwiseSummationtailwiseSummation(f(a), a + 1)Factorial

object Sum {
  def Summation( f : Double => Double , a: Double , b: Double):Double = {
    def tailwiseSummation(accumulator:Double , count:Double):Double = {
      if(count > b) accumulator
      else tailwiseSummation(accumulator + f(count), count+1)
    } 
    // accumulator starts with f(a) , so count starts from a+1 to remove off-by-one error        
    tailwiseSummation(f(a), a + 1) 
  }

  def Factorial(num: Double): Double = { 
    def tailwise(accumulator: Double, deprecator: Double): Double = {
      if (deprecator == 0) accumulator
      else tailwise(accumulator * deprecator, deprecator - 1) // deprecator deprecating 1 unit at a time
    }
    tailwise(1, num)
  }
}

运行:

scala> Sum.Summation(Sum.Factorial(_), 1, 5)
res0: Double = 153.0
于 2013-10-17T16:07:08.043 回答