scala anonymous function/function with function parameter

(1) Anonymous function

var triple = (x:Double)=> 3*x

This is the same as if you used def

def triple(x:Double) = 3*x

But you don't need to name the function, you can directly pass it to another function

Array(3.14,1.42,2.0).map((x:Double)=> 3*x)


(2) Functions with function parameters

def valueAtOneQuarter(f:  (Double)=> Double) = f(0.25)

What is the type of valueAtOneQuarter? She is a function with a single parameter, as his type writes:

(parameter type) => result type

The result type is obviously double, and the parameter type has been given as (Double)=>Double in the function header, so the type of ValueAtOneQuarter is

((Double)->Double)=>Double

Since ValueAtOneQuearter is a function that accepts function parameters, it is called a higher-order function.

Higher-order functions can also produce another function, here is a simple example:

def mulBy(Factor:Double)=(x:Double)=>factor*x

For example, mulBy(3) returns the function (x:Double)=>3*x, the power of mul is that it can produce functions that can be multiplied by any amount:

val quintuple = mulBy(5)

quintuple(20)

The mulBy function has a parameter of type Double and returns a function of type (Double) => Double, therefore, its type should be:

(Double)=>((Double)=>Double)





Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326153811&siteId=291194637
Recommended