Scala和功能编程的新手。具有以下代码段,这意味着要在itext/itext.kernel/itext/kernel/utils/CompareTool.cs
s的闭合间隔内计算总和。已经实现了尾递归方法(Int
)和非尾递归方法(sum1
)。
sum2
但是,打印输出不不会返回实际的package test
import scala.annotation.tailrec
object Currying extends App{
def sum1(f:Int=>Int)(a:Int, b:Int): (Int, Int) => Int = {
require(a <= b, "Received a=" + a + " and b=" + b)
@tailrec
def sum(a:Int, acc:Int) : Int = {
if(a > b) acc
else sum(a+1, acc + f(a))
}
sum
}
println("sum1(x=>x*x)(1, 4)=" + sum1(x=>x*x)(1, 4))
println("sum1(x=>x*x*x)(1, 4)=" + sum1(x=>x*x*x)(1, 4))
def sum2(f:Int=>Int)(a:Int, b:Int): Int => Int = {
def sum(a:Int) : Int = {
if(a > b) 0
else f(a) + sum(a+1)
}
sum
}
println("sum2(x=>x*x)(1, 4)=" + sum2(x=>x*x)(1, 4))
println("sum2(x=>x*x*x)(1, 4)=" + sum2(x=>x*x*x)(1, 4))
}
,但是看起来像是函数本身:
Int
很明显,我在做些愚蠢的事情,但我一生都无法解决。