C++ language, having undergone a long evolution, has acquired a number of features specific to the functional paradigm: functions became first-class objects that can be operated on, and template instrumentation suports compile-time computation on types. The mathematical basis of these two features are lambda calculus and category theory, respectively. Extendinng the language with these tools brought to implementation in C++ of various instruments knows from functional programming. Some of these implementations became a part of the standard library (std::function, std::bind), others reside in third-party libraries, in particular - in Boost collection of libraries (for example, fufnctional, hana).
An important place in the functional programming toolkit belongs to fold and unfold operations which are most obviously defined for lists and also can be quite naturally generalised onto other inductive and coinductive data structures. For example, calculating a sum of a list of numbers can be presented as folding the list against addition; building a list of prime factors for a given integer is an example of unfolding that integer. Generalisations of folds and unfolds are known as anamorphisms and catamorphisms. In addition, a composition of unfold (of some object into a collection) with subsequent fold (of that collection into a new object) finds its applications in functional programming.
It is demonstrated in this talk that folds, unfolds and compositions thereof can be easily implemented in C++.
Lead Developer, SolarWinds, Kyiv-Minsk, Ukraine-Belarus
Ph.D, 10 years of academic experience: lectures about programming for students, including Kiev National Taras Shevchenko University. 10+ years in software development (mainly in C++ and C#), focusing on data …