[Tutor] Higher-Order Function Examples
Steven D'Aprano
steve at pearwood.info
Mon Feb 14 23:38:32 CET 2011
Walter Prins wrote:
> 2011/2/14 Rafael Durán Castañeda <rafadurancastaneda at gmail.com>
>
>> Could we consider sorted as an high order function?
>>
>> sorted_list = sorted(list_strings, key = str.lower)
>>
>>
> No because sorted() returns a list as a result. A higher order function
> produces another function as a result, or takes one or more functions as a
> parameter.
By that definition, sorted *is* a higher-order function as it takes a
key function as a parameter.
Typically, though, most people would consider that in order to count as
a high order function, it must take another function as a main
parameter, and not as an optional extra.
E.g. sorted doesn't make the cut, because you can call
sorted(list_strings) without giving a key function. The key function is
an optional extra that merely modifies the action of sorted, rather than
an essential part of it.
On the other hand, once you really start to embrace the idea of
functions-as-data, the distinction becomes less important. There are
functions that take strings as arguments, and functions that take
numbers as argument, and functions that take strings AND numbers as
arguments... why should we single out functions that take functions as
special? If functions are tools, then there's no fundamental difference
between "ordinary tools" and "tools that make other tools". They're all
just tools.
The difference between "ordinary functions" and "higher-order functions"
is most important in languages that don't have higher-order functions.
--
Steven
More information about the Tutor
mailing list