153 points · by adamnemecek · 12y ago · 165 comments
http://www.reddit.com/r/cpp/comments/1z1b1q/c17_i_see_a_mona...
The author of the post is also participating there.
I'm currently working on a new project using C++11/14 and it's a pleasure to see more functional features that will allow to be more concise.
On the other hand, C++ is already a mess. It's not even a beautiful mess, but it is a very functioning mess. Adding more stuff to it just seems like heaping more things on top of a pile that's already falling over in pieces.
Granted, like most everything else in C++, it will probably be optional, and hey, if nothing else, having more (optional) features is very pragmatic.
Either because they are new, because nobody use them, or because they are LISP.
I really don't like how no lisper thinks it's a good idea to improve LISP, but it's this way.
Then C++ is a too low level language. Memory management is a bitch to deal with. FP is comfortable only in garbage collected languages, or otherwise you need a really, really well designed library and unfortunately STL ain't it, as STL has been plagued with memory leaks for years and still is. And many things in it are simply broken.
For me the test for FP is pretty simple - a language is FP-capable if there exists for that language a comfortable and reliable library for persistent/immutable collections/data-structures. And this is in fact not enough, but rather the bare minimum. You simply can't talk about functional programming without immutable/persistent data-structures.
Can such a library be designed for C++? It's much harder to do it than in say, a JVM language, or in Javascript, or in any garbage collected language, because of the memory management. Persistent data-structures rely on structural sharing for efficiency and in turn you rely on the garbage collector to take care of the junk when no longer needed. As an exercise, try to implement an immutable data-structure in C++, even a simple one like a linked-list and watch in horror the output of Valgrind as you're using it.
I do think it's possible though, with a little care towards designing it. I think the TFA explains quite well the value of good design and even takes memory management into consideration. If more people actually do FP in C++, maybe one day we'll have an awesome standard and an awesome library that we could use for our FP needs.
With that said, I really hope they won't leave std::future as is and I hope they do improve it. Adding a broken interface to the standard is not OK. If you can't design well an interface, then adding it to the standard does more harm then good. On the other hand the commute seems to be aware that std::future needs fixing, so that's good.
Thanks!
I think the main point to take away is that this is a case where a monad is the right abstraction and can be implemented very logically, but since C++ doesn't and cannot really speak about monads directly, there comes a lot of boilerplate and you lose a lot of "free" utility functions you'd get in a language that can talk about arbitrary monads.
Edited to add: Ah, it seems a template argument can't itself be a template, which would seem to rule it out (though I'm running on very little sleep, so I might very well be wrong).
this is valid C++14:
template<typename A, typename B>
auto add(A a, B b)
{
return a + b;
}One thing C++ templates can't express e.g. is polymorphic recursion. http://stackoverflow.com/questions/10321856/does-c11-support...
in all relative seriousness, would anyone care to put forward a concise definition of "monad" (for programmers, not math-category-theorists)?
A monad is any generic class that has a flatMap function and a factory function that together satisfy 3 laws (explained below)
flatMap is like map, except the function passed to flatMap must return a monad (of the same kind).
The factory can make a monad of a regular value (it wraps it)
For example, an array's flatMap function takes a function that takes an element and returns an array. You can return an empty array if you wish, or an array of two elements (of the same type). flatMap "flattens" the result - it returns an array of elements of that same type.
The factory function and flatMap must satisfy 3 laws: left identity, right identity and associativity. That is, flatMapping with the factory function should result with the same thing as what you started with; wrapping a value with a factory then flatMapping it should result with that same value being passed to the function you passed to flatMap; and it shouldn't matter whether multiple flatMap calls are chained, or nested.
Like design patterns in OO languages, it isn't immediately clear why its useful to give a name (or a type) to all generic classes that satisfy this "interface" called monad, but it turns out that the concept pops up everywhere, from arrays to futures to Maybe (to replace null values) to Either to Observable and so on.
Not sure if I managed to be correct, understandable, concise or neither :P
Foo<A>
and a function B f(A)
and apply it to get Foo<B>
Then monad gives us something called join, which lets us take: Foo<Foo<A>>
and turn it into Foo<A>
It's pretty obvious that a Vector of Vectors of A's can be turned into a Vector of A's by concatenating them into one Vector. Also optional (something I don't know much about, sorry) can be turned from Optional<Optional<A>> into Optional<A> if the outer actually contains an inner optional, and the inner optional contains an A.So with these two things, we can do things like:
Vector<B> f(A);
Vector<C> g(B)
Vector<A> foos = {a,b,c};
foos.fmap(f).join().fmap(g).join()
to get a Vector<C>. The result is basically considered all possible results of applying f to all the values in foos, and then applying g to all the values returned by all the calls to f. this is the non-deteminism monad, where each function f and g can produce multiple results (including none) for each input, and we can chain multiple non-deterministic computations to get all the non-deterministic results.Usually Mopnad is explained with return and bind, but I think it's a bit less obvious. But I'll give it a shot...
bind in Haskell is something that takes something of type
Foo<A>
and a function with type Foo<B> f(A)
and produces something of type Foo<B>
From above, we can rewrite the example with Vector<B> f(A)
Vector<C> g(B>
Vector<A> foos = {a,b,c};
foos.bind(f).bind(g);
and get the same result as before. I guess you could use slightly cleaner syntax (why the hell not overload >> for yet another bizarre use right? [leading to foos >> f >> g;])I hope that you can see that this is just a simple interface which can work for many types that look like Foo<a> (Vector, Set [assuming C++ has that?], Optional, even pointers to some extent; see the discussions of the introduction of "?." into C# which is exactly what the Maybe monad encodes). There are also plenty of other monads in the haskell universe which aren't as easy to show in C++ because a) I'm not sure C++'s type system is up to it and b) my C++ knowledge is not strong enough to demonstrate things like the State monad, and definitely the Cont[inuation] monad.
Anyway, bring it back to the topic of the article, it should be clear that something of type
Future<A>
can be composed with other functions w3hich produce more Futures: Future<B> f(A);
Future<C> g(B);
Future<A> async_A("thing");
asyc_A.bind(f).bind(g);
Which handles all the unwrap and passing of values "inside" the future to each consecutive function.I know this isn't a concise explanation, but it's because it's a very simple, but also very abstract idea, and its best introduced with example uses, then generalising it.
He wants a jit for cpp?
Boilerplate prevention, I think.
I'm sure that's not the actual state of things, but goddamned if that isn't what appears to be happening.
EDIT:
Before downvoting, consider the elaboration I've replied below with (and then you can at least downvote that too!).
EDIT2: HN wouldn't let me submit this, so is edit:
The basic issue is not that futures/promises/monads aren't awesome--I'm quite, quite sure that they are the future (harhar) for solving a lot of things. I use them extensively, for example, in Javascript. They're Good Things (tm).
It's not that template metaprogramming is bad, or not useful, or that Boost isn't our lord and savior for greenfield C++ code.
The problem is that this shit still has to interoperate with code written more than two decades ago.
C++ began life as a weird ball of OOP and templates slathered over C. It failed to fix some of the real, true, awful parts of C (pointers, for example), and those are still around.
Pray tell me, why do I want a language which has both atomic exchanges (sorta, kinda, depending on your compiler and environment) and monads and function mapping? Doesn't that strike anyone else as, oh, I don't know...ill-focused?
C++ is simply too large a language to recommend to a beginner, too difficult to actually make guarantees about (when you can at all!), and in general the whole rotten mess should be cut in half.
Into, perhaps, C, and Haskell.
Is it the naming convention? Functor, Monad, Applicative, bind, join, fmap etc? Yes, Haskell can be a bit confusing at first. But if you don't like them you can urge the standards committee to use different names.
Or is it the concepts themselves? That would be pretty sad. A Functor is a really basic concept. You probably use it every day, in one form or another. I'm pretty sure of that. Once you understand this basic concept, you can start building the others on top of that knowledge. It's all about building a common language and understanding of these basic concepts.
They're able to turn a lot of algorithms inside out; make the kernel a simple function of values where they used to be threaded through the code flow, and use things like bind to mix them back in. This makes algorithms testable and more composable, and raise the level of abstraction in the rest of your code so that you're operating more at the DSL level for your domain, whatever it is.
It's worth learning the concepts. Once you do, you'll be surprised that there's so little "there" there.
And their commonality and generality are exactly the reasons why they should have short yet precisely general names.
Personally, I don't think you'll ever reach perfection if you restrict yourself to adding features. Sometimes you've got to take them away and that's not really feasible with a mature language like C++.
I'm curious because you seem to have made two different points: 1) it doesn't make sense because adding new features to such an old and widely used language is hard, and 2) it doesn't make sense because of the kind of language C++ is. (1) isn't true for Rust, but (2) is.
As for your observed point 2 though: at some level, systems languages need to allow the twiddling of bits on and off, perhaps allow the direct interaction via assembly with the processor, have some notion of native word size, and perhaps also make simple common idioms in low-level programming (stacks, interrupts, and so forth).
It is very rare (in my experience, which may not be accurate) that these issues should be even visible at semantic layer concerned with mapping functions over data and other functions, with sorting sets, and sending messages. It's simply too polluted a headspace.
At its best, it provides tools for building cost-free abstractions that hide bit-twiddling and assembly hacks while providing an expressive set of building blocks for the semantic layers above them. In this case a programmer only thinks about one layer at a time, so the mapping and messaging can be tuned to their domain, but the implementation is abstracted.
At its worst, it provides the verbosity of Enterprise Java with the memory safety of C and it becomes very difficult to trace what the program is doing and how. I have found this is very strongly related to the widespread use of non-smart pointers. This lets the semantic domains smear into each other and tends to produce astonishingly brittle code.
All 10 of them? You do understand that these C++ proposals and additions have nothing to do with Haskell people, but come from seasoned C++ veterans, like Herb Sutter and such.
You don't like this? Fine. It's pretty easy - don't use futures, and it won't be in your face. You can ignore it completely and use the rest of C++ as you see fit.
Also it's amusing you opine that pointers are "awful" in the same post in which you rail against others' for "screw[ing] up C++". Pointers are one of the best things about the two languages in my opinion. I love the power and flexibility they provide.
Dunno, but I think part of the reason Rust is popular lately is that it combines safety and functional features with high performance by default and the ability to /theoretically/ easily drop down into lower-level code to eke more out.
I think C++ is an unnecessarily complex language for various reasons, but adding some basic functional methods to a STL class isn't the end of the world on that front and sounds fairly useful.
p.s. Java has atomic exchanges.
A while ago the FP people figured out that their `hacks' to do IO actually conform to the structure of a Monad. So they exploited the fact. Now the author sees that the `hack' to do futures in C++ also conforms to the structure of a Monad, and suggests exploiting that fact.
Yes, though futures were always like that when you look at Java for example. Java always suffered from the need to prepare complex design patterns to do simplest things as it was much less flexible than C++. Now C++ is getting there as well.
I personally would stick with some earlier C++ standard and use Haskell for my functional programming needs. Feels much more natural than trying to bend each language to support every thought process imaginable, and doing a poor job at that.