Then yesterday's article, and then demonstrate a slightly more complicated tail recursive tail recursion example: Calculate the nth Fibonacci number. Fibonacci number first, the second value is 0, 1, in order after the value is the preceding two number of the addition. For example: 0,1,1,2,3,5 ...
1def fib (n:int): Int = {2 @annotation. Tailrec3def go (Cnt:int, Prev:int, cur:int): Int =CNT Match {4 CaseMif(M < 0) = Sys.error ("Negative number not allowed!")5 Case0 =prev6 Casec = Go (cnt-1,cur, prev +cur)7 }8Go (n,0,1)9}//> Fib: (n:int) IntTenFIB (5)//> res52:int = 5
First, the tail recursion refers to the last statement of a recursive function that references itself independently. In the example above, go (Cnt-1,cur,prev + cur) is the last independent statement that does not add any operations. We can try to make an appointment:
1 fib (5)2 Go (5,0,1)3 Go (4,1,0+1) = Go (4,1,1) 4 Go (3, (0+1), 1+ (0+1)) = Go (3,1,2)5 Go (2,1+ (0+1), (0+1) + (1+ (0+1)) = Go (2,2,3 )6 Go (1, (0+1) + (1+ (0+1)), (1+ (0+1)) + (0+1) + (1+ (0+1))) = Go (1,3,5)7 Go (0,5,8) = 5
Is the answer we expected.
The function of Scala is worth mentioning. A function can be used as a standard object: it can be treated as an input parameter or a result value of another function. Functions that accept a function as an input parameter or return another function as a result are called higher order functions (high order function). The use of anonymous functions (anonymous function or LAMDA functions) or function literal in Scala programming is also common. Use the code sample in the book to illustrate:
1 def formatResult (name:string, n:int, f:int = Int) = {2 val msg = "The%s of%d is %d. " 3 Msg.format (n, f (n))4 }
Note that FormatResult is a high-order function because it accepts a function f as an input parameter. here int = int is a class declaration and is a type of function. See how higher-order functions and anonymous functions are used:
1def main (args:array[string]): Unit = {2println (FormatResult ("absolute value", 42, ABS))3println (FormatResult ("factorial", 7, factorial))4println (FormatResult ("Increment", 7, (x:int) = x + 1))5println (FormatResult ("Increment2", 7, (x) = x + 1))6println (FormatResult ("Increment3", 7, x = x + 1))7println (FormatResult ("Increment4", 7, _ + 1))8println (FormatResult ("Increment5", 7, X = = {Val r = x + 1; R}))9}
The input parameter F of the incoming function formatresult can be a normal function such as factorial,abs. The function text can also be used, as long as its type is int + = Int. The various representations of the above anonymous functions can refer to the Scala language tutorials.
Functional Programming (3)-recognize Scala and functional programming