fn: Scala View in C++11

Simpler functional programming in C++11

STL comes with an extensive set of tools for functional programming, ranging from std::remove_if() to std::transform() to std::accumulate(). For example, you can solve Euler Project’s Problem 1 in C++11, functional-style:

#include <algorithm>
#include <vector>
#include <numeric>

std::vector<int> v;
// You can replace this with std::generate, but let's forget
// about that in this example for brevity.
for (int i = 1; i < 1000; i++) {
v.push_back(i);
}
v.erase(std::remove_if(v.begin(), v.end(), [](int i) {
return i % 3 != 0 && i % 5 != 0;
}), v.end());

auto sum = std::accumulate(v.begin(), v.end(), 0,
[](int i, int n) { return i + n; });

To implement the same idea in Scala, one would write something like this:

(1 until 1000).filter(n => n % 3 == 0 || n % 5 == 0).sum

And something like this in Python:

sum([i for i in xrange(1, 1000) if i % 3 == 0 or i % 5 ==0])

C++11 indeed feels like a new language, but its functional programming API still looks old. There is too much to write for simplest things. That made me write a simple library for generic functional programming idioms in C++: fn. Let’s rewrite our C++ code in fn:

#include "fn/fn.h"
...
using fn::_;
auto sum = _(range(1, 1000))
.filter([](int i) { return i % 3 == 0 || i % 5 == 0; })
.sum();

Not bad, hah? But, it’s actually beyond simplicity. It’s based on Scala-style views to avoid multiple temporary collections, and “materialize” the views only when you do an aggregation (e.g., sum(), max(), etc.) or convert the results into a collection.

There is lots of missing features, but check it out and take it for a test-drive! It’s header only and works with clang and gcc: github.com/soheilhy/fn