官术网_书友最值得收藏!

Higher-order functions

The last concept that is important to know when starting with functional programming is higher-order functions. A higher-order function is a function that accepts a function as an input parameter and/or returns a function as an output parameter. There are different reasons to use higher-order functions:

  • By taking functions as input, higher-order functions allow you to implement generic behavior on different types of actions. This allows you to factorize some code.
  • Returning a function as an output allows you to capture the values of input arguments, thanks to closures, and return a function that operates on a fixed set of parameters.

Both of these situations are covered in the example of the Closures section:

def act_on(what):
def exec(f):
f(what)

return exec

The exec function is a higher-order function that is an example of the first case. It takes a function as an input and calls it. The example is really trivial, but should any code be added in the exec function, it would add some behavior available to any function being passed as an input.

The second case is exactly what act_on does. The exec function that is returned by act_on embeds the value of what that was provided as an input. This is a very common way to save some context information and use it later.

主站蜘蛛池模板: 寻乌县| 区。| 铁岭县| 易门县| 广平县| 巩留县| 隆林| 迁西县| 福海县| 郑州市| 桐城市| 巴彦县| 军事| 汉寿县| 汉川市| 泰州市| 阜平县| 青川县| 和龙市| 罗城| 东港市| 嘉黎县| 老河口市| 渭源县| 宜州市| 兰州市| 商都县| 富阳市| 三原县| 高邑县| 海城市| 盘山县| 西吉县| 西华县| 丽水市| 明水县| 长春市| 杭锦旗| 彰化县| 平安县| 石首市|