我正在尝试在 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)
}
}
有人可以帮忙吗?