10.8. Functional Higher-Order

  • Function can take other function as arguments

  • Function can return function

Functions in the functional programming style are treated as variables. This makes them first-class functions. These can be passed to other functions as parameters or returned from functions or stored in data structures. [1]

A higher-order function is a function that takes other functions as arguments and/or returns functions. First-class functions can be higher-order functions in functional programming languages. [1]

>>> def lower():
...     ...
>>>
>>>
>>> def higher():
...     return lower

10.8.1. Calling

>>> def lower():
...     return 'My name... José Jiménez'
>>>
>>> def higher():
...     return lower
>>>
>>>
>>> a = higher
>>> b = higher()
>>>
>>> a  
<function higher at 0x...>
>>>
>>> a()  
<function lower at 0x...>
>>>
>>> a()()
'My name... José Jiménez'
>>>
>>> b  
<function lower at 0x...>
>>>
>>> b()
'My name... José Jiménez'

10.8.2. Use Case - 0x01

>>> def apply(fn, data):
...     return fn(data)
>>>
>>> def square(x):
...     return x ** 2
>>>
>>>
>>> apply(square, 2)
4

10.8.3. References