In thinking in Scala (5) ---- High-Order Function *, we demonstrate how to pass a function as a parameter to another function.
In this article, we will demonstrate another important feature of functional programming: return a function. First, let's look at the following code:
Code piece 1:
def sum(f:Int=>Int):(Int,Int)=>Int={ def sumF(a:Int,b:Int):Int= if(a>b) 0 else f(a)+sumF(a+1,b) sumF }
In a bit, F: Int => int is a parameter received by the sum function, which is a function.
":" (INT, INT) => Int Is the return value of the sum function, because (INT, INT) => int represents an "anonymous function ",
That is, to call the sum function, the returned value is a function. This is applicable to programming languages such as C, C ++, and Java.
It is hard for programmers to understand.
Let's continue with the example. What will happen if we execute the following line of code?
sum(x=>x*x)(1,4)
30 is returned. Why is it 30? 30 = 1 ^ 2 + 2 ^ 2 + 3 ^ 2 + 4 ^ 2.
First, sum (x => X * X) is a function, and the sum (x => X * X) type is (INT, INT) => int, because sum (x => X * X) is a function,
So it can continue to receive parameters ).
Well, I may not have explained this clearly. It is too abstract.
Thinking in Scala (6) ---- High-Order Function ---- returns a function