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

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.

主站蜘蛛池模板: 湘西| 寿光市| 宾川县| 建湖县| 兴山县| 万安县| 清流县| 高淳县| 旬阳县| 项城市| 溧阳市| 邓州市| 克东县| 临武县| 泰和县| 海晏县| 濉溪县| 西乡县| 鄢陵县| 博乐市| 伊吾县| 盐源县| 岫岩| 泰州市| 大石桥市| 盐边县| 长葛市| 卢湾区| 宜丰县| 阿巴嘎旗| 靖边县| 徐汇区| 阿城市| 湄潭县| 安丘市| 隆尧县| 龙山县| 保康县| 昭觉县| 太仆寺旗| 石台县|