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

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.

主站蜘蛛池模板: 云浮市| 遵义市| 兴隆县| 屏南县| 沐川县| 稷山县| 和林格尔县| 湟源县| 石城县| 南召县| 红河县| 盐源县| 玉龙| 乡宁县| 定远县| 莲花县| 彭泽县| 霸州市| 谢通门县| 望都县| 教育| 新龙县| 阿瓦提县| 浑源县| 南昌市| 博客| 瓮安县| 勃利县| 宁蒗| 名山县| 睢宁县| 萨迦县| 伊金霍洛旗| 西畴县| 杭锦旗| 吴川市| 岚皋县| 台南市| 漳浦县| 南雄市| 永昌县|