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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.128.226.121