Blog

This is my blog.

Frustration with dys-functional C++

[linkstandalone]

C++ is the only language I know that punishes you for trying to program in a functional style. Really, it does.

Just have a look at std::transform, which is the C++ version of map. If you try to map a function over, say, a std::vector<int>, you get this:

std::vector<int> foo{ 1, 2, 3 };
std::vector<int> result(3);
std::transform(foo.begin(), foo.end(), result.begin(), [](auto &x) { return x + 42 ; });

First of, this isn't really functional. std::transform is modifying the state of the result-vector instead of returning anything useful. Secondly, the syntax is a nightmare. Compare with this bit of C# that does the same thing:

var foo = new List<int>{ 1, 2, 3 };
var result = foo.Select(x => x + 42).ToList();

That is not only much more readable (apart from the fact that C# also chose the wrong name for map, but also shorter. Plus, Select is an actual function that doesn't modify state, but just gives an output that depends on its input.

Of course, a still better (and more readable) choice is Lisp, e.g. in Scheme this would translate to:

(define foo (list 1 2 3))
(define result (map (lambda (x) (+ x 42)) foo))

It is obvious that map is the map algorithm, the lambda is called lambda, which is a bit verbose but quite readable, and all in all it's concise.

Go back
Mon, 12 Jul 2021 11:53:47 +0000