In D
D provides several ways to declare function objects: Lisp/Python-style via closures or C#-style via delegates, respectively:
bool find(T)(T haystack, bool delegate(T) needle_test) { foreach (straw; haystack) { if (needle_test(straw)) return true; } return false; } void main { int haystack = ; int needle = 123; bool needleTest(int n) { return n == needle; } assert( find(haystack, &needleTest) ); }The difference between a delegate and a closure in D is automatically and conservatively determined by the compiler. D also supports function literals, that allow a lambda-style definition:
void main { int haystack = ; int needle = 123; assert( find(haystack, (int n) { return n == needle; }) ); }To allow the compiler to inline the code (see above), function objects can also be specified C++-style via operator overloading:
bool find(T, F)(T haystack, F needle_test) { foreach (straw; haystack) { if (needle_test(straw)) return true; } return false; } void main { int haystack = ; int needle = 123; class NeedleTest { int needle; this(int n) { needle = n; } bool opCall(int n) { return n == needle; } } assert( find(haystack, new NeedleTest(needle)) ); }Read more about this topic: Function Object