Lambda-style anonymous functions for C++ in less than 500 lines of code

I prefer functional languages like Scheme, Scala or Haskell over C++ for most tasks. So, when I'm forced to program in C++, I write functional C++.

Fortunately, it's possible to add the most important ingredient in functional languages--lambda-style anonymous functions--to standard C++.

For example, the expression

lambda<int> (x) --> 3*x + 7

<int>

represents a function that multiplies by 3 and then adds 7. (Themeans that the anonymous function returns an integer.)

These anonymous functions are first-class; that is, they can be assigned to variables, passed as parameters or returned from functions; for instance:

f = lambda<int> (x,y) --> x + y ;

f(2,3) == 5

(lambda<int> (z) --> z*z)(9)

so that. Or, they can be applied directly, as in:which is just another way of saying 81.

These functions can also map over data structures; for example:

B = (lambda<int> (x) --> 3*x + 1).map(n,A)

B

B[i] == 3*A[i] + 1

produces a new arrayin which

Lambda terms can also capture free variables and perform Currying; for instance, given the function definition

Function2<int,int,int> h(int a, int b) { return lambda<int> (x,y) --> a*x + b*y ; }

h(3,4)(1,1)

the value ofis 7.

To pull this off, the implementation exploits templates, operator overloading and function pointers (but, remarkably, not a single macro) to construct a type-safe domain-specific embedded language (DSEL) for describing anonymous functions.