scala实战学习-尾递归函数


$$
\Sigma\sideset{^b_a}f(x)
$$

object sumfunc{
    def sum(f: Int => Int)(a: Int)(b:Int): Int = {
        @annotation.tailrec
        def loop(n: Int,acc: Int): Int = {
            if(n > b){
                println(s"n=${n},acc=${acc}")
                acc     //当计算到b值,返回acc值
            }else{
                println(s"n=${n},acc=${acc}")
                loop(n + 1, acc + f(n))
            }
        }
        loop(a, 0)      //n从a开始,acc从0开始
    }
    sum(x => x)(1)(5)   //将f(X)、a、b传到sum函数中
                                                  //> n=1,acc=0
                                                  //| n=2,acc=1
                                                  //| n=3,acc=3
                                                  //| n=4,acc=6
                                                  //| n=5,acc=10
                                                  //| n=6,acc=15
                                                  //| res0: Int = 15
    sum(x => x * x)(1)(5)                         //> n=1,acc=0
                                                  //| n=2,acc=1
                                                  //| n=3,acc=5
                                                  //| n=4,acc=14
                                                  //| n=5,acc=30
                                                  //| n=6,acc=55
                                                  //| res1: Int = 55
    val sumSquare=sum(x => x*x)_                   //> sumSquare  : Int => (Int => Int) = <function1>
    sumSquare(1)(5)                                //> n=1,acc=0
                                                  //| n=2,acc=1
                                                  //| n=3,acc=5
                                                  //| n=4,acc=14
                                                  //| n=5,acc=30
                                                  //| n=6,acc=55
                                                  //| res3: Int = 55
posted @ 2018-11-29 20:26  枫子_dan  阅读(348)  评论(0编辑  收藏  举报