Learning #5: Functors and Lambdas, Putting the Fun in Function
A couple days ago I tried to implement a Haskell Functor in C++. It went ok and I got something that was kinda sorta functory-haskellish. However it wasn’t great and I had a list of at least five things that needed to be improved before it was satisfactory.
Looking back at it today, I do not believe it can really be done well and I do not believe following my laundry list of improvements will get it to where I hope it will be. Thus, I called that a failure and moved on.
Speaking of functors however, there is actually a functor in C++.
Actual Functor in C++
In C++, a functor is an object of a class that overrides the
() operator, allowing it to encapsulate some logic and data, think closure. Pretty nifty and very imperative (with state and what not).
Note: not showing an example here because I prefer lambdas.
There is More
It actually turns out there are four types of functions, besides normal methods on classes and regular functions and such.
- Function Pointers: C-style pointers to functions that can be passed around
- Functors, or Function Objects: see above
- STL functions: according to my second reference “the Standard Template Library (STL) provides three types of template function objects: Generator, unary and binary functions.” Do not know a whole lot about this, will need to explore it further.
- Lambdas (Yes, Thank You!): pretty cool feature allowing for anonymous functions and a utility for capturing, or enclosing, local variables
C++ lambdas are pretty cool and in fact my CS461 project group implemented a version of them in our Bantam Java compiler. You can pass them around, invoke them immediately, return them from other functions, etc. You cannot quite go fully functional in C++, but this gets you a little bit closer.
not true tho ^^ functional programming is great!
Basic Lambda syntax is as so:
where many of these parts are optional. See here for more details.