As many people (humbly including me) has been trying some new, exciting (maybe) features of the new standard version of C++, a.k.a C++11
(or, C++0x
), I personally still find it very rewarding to explore cool things about the oldie C++98 (correct me if I was wrong!). In this post, we will look into some basic techniques/features related to functional programming in C++. Unless otherwise stated, C++, in this post, refers to the previous standard version of the language. I’m unfortunately not a hardcore fan of some functional programming languages, e.g., Haskell, but the ideas of functional programming are very appealing and profound.
0. Map and Reduce
People who are familiar with functional programming might look for something corresponding to the classic higher-order functions Map and Reduce in C++. One acceptable answer would be:
-
accumulate(start, stop, accumulator, binary_op): a general purpose function in <numeric>, that basically transforms a collection/sequence of elements into a single value. Simply put, it does Reduce.
-
transform(start, stop, result, unary_op) or transform(start1, stop1, start2, result, binary_op): a function in <algorithm> library, that applies specified operation and transform given sequence(s) to a new sequence. In other words, it does Map.
1. Function object - Functor
To be updated.
2. Adaptable Functions and <functional> library
To be updated.
3. Where to go from here?
As you can see, C++ does provide support for function programming through e.g., useful yet quite limited <functional> library. C++11
, however, seems to empower us with more features which can make functional programming a lot easier and funnier. Check out Bjarne Stroustrup’s page, or this article for more information on C++11. Enjoy!