1. 程式人生 > >scala實戰學習-尾遞歸函數

scala實戰學習-尾遞歸函數

sig ati sid sigma 實戰 lse bject ann fun


$$
\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

scala實戰學習-尾遞歸函數