I’ve been learning Lisp recently (I’ll eventually post something about how and why) but, oddly enough, all this Lisping has got me thinking about C++.
So, without further ado, a higher-order function in C++:
#include <boost/lambda/lambda.hpp>
#include <boost/function.hpp>
#include <iostream>
using namespace std;
using namespace boost::lambda;
template< typename T >
boost::function foo( T n_ )
{
// Old code. Leaks memory.
//T *n = new T( n_ );
//return ( *n += _1 );
boost::shared_ptr pn( new T(n_) );
return ret< T& >( *constant(pn) ) += _1;
}
int main()
{
// start with one
boost::function accum = foo(1);
cout << accum(2) << endl;
cout << accum(10) << endl;
}
This blows my mind on so many levels, I don’t know where to start. The gist is that foo is a function which generates new functions (ok technically it generates functors, but if you squint, you can’t tell the difference).
Neat.
(Inspired by Paul Graham’s Revenge of the Nerds.)
Update: I originally declared n as a static local, but then I realized what this actually meant (all generated accumulators share n). The current code leaks, but at least it works for multiple accumulator functions. I’m still trying to figure out how to use a smart pointer to plug the leak.
Update: Thanks to Peter Dimov on boost-users, the code above now uses a boost::shared_ptr and is leak-free. For some reason, it won’t build with gcc 4.0.2.

# In the language of my scarlet mistress (Ruby)
def foo( initial )
return lambda { |n| n+=initial }
end
accum = foo(1)
puts “#{accum[2]}”
puts “#{accum[10]}”
Mark -
I don’t have to remind you about what society thinks of guys who lisp do I?
Bheesh - Ruby is bad-ass.
Ryan - Don’t be thilly, you thexy boy.
You need closures. I’m not quite enough of a template god to get this one right, but this works fine (though the .get()(args) syntax really sucks):
Very cool, Kevin. I hoped that an implicit conversion operator would get a nicer syntax to work, but I couldn’t figure it out…