Polyglot CheatSheet - Higher Order Functions
Last Updated: 2022-04-03
Higher order function: a function that either takes a function as parameter, or returns a function after its execution.
First-class functions are the functions that are treated as values. It means, those functions can be assigned to a variable and can be passed around as an argument.
C++
Since C++11, we can use std::function
as an argument or the returned result.
Java
Before Java 8, use anonymous inner classes; after Java 8, we can pass the function as an argument:
Collections.sort(list, (String a, String b) -> {
return a.compareTo(b);
});
Python
Use decorators:
@foo
def bar():
pass
It's equivelent to:
def bar():
pass
# Pass bar() to foo() as an argument
bar = foo(bar)