Are there open source C++ libraries that are similar or equivalent to the excellent Functional Java library?
Specific features would include:
- map, fold/reduce, filter, etc on iterables or the like
- option type
- immutable data-structure implementations
(asked out of curiosity, having been away from C++ for some years)
Yes, some of these features have traditionally been thought to require garbage collection. But with modern C++ features and libraries, has anyone started passing managed pointers through the functional transformations or something?
UPDATE
To be clear, I’m wondering the there’s something similar to Functional Java, so that the following might be typical syntax:
// assumptions:
// * my_list is a standard library iterable of ints
// * f is a function of int that returns a std::string
// * p is a predicate of std::string returning bool
// * head_opt returns an option type
stream(my_list).map(f).filter(p).head_opt.get_or_else("None")
This is the idiom that Functional Java offers, and believe me it’s really easy to get accustomed to it…
As @jalf said, map and fold are already in the standard, hidden behind different names:
std::transform, found in header<algorithm>std::accumulate, found in header<numeric>Many more functional stuff can be found in Boost.Range, which is a pretty awesome library. Especially the range adaptors give a real functional feeling, as they create views over other ranges. With C++11, possible predicates are also easily created on-the-fly through lambdas.
Boost.Optional might be your “option type”, depending on what exactly you mean with that.
Immutability in C++ can be achieved by simply declaring your object
const. You can avoid copies using by-reference argument passing. Truth be told, this is of course no real equivalent to true functional immutability, since immutable containers in functional languages can be copied however your want and usually just share the internal representation. After all, copy-on-write is awesome if you never write.On your managed pointers, I got no idea what you mean by them. In C++, you usually don’t need pointers or dynamically allocated objects at all. Just create them “on the stack”:
Foo obj;.If you mean shared ownership, there’s
std::shared_ptr. There even is a nice range adaptor if you store such a pointer in a container:Your specific example
might be implemented like this (note that
std::vectoris the default container in C++):Compiled with Clang 3.1 Trunk, this results in the following output: