16 ms·
C++17: I See a Monad in Your Future
- angersock 13y agoWhy are all the Haskell and functional folks trying to screw up C++? 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.
- saurik 13y agoWhy do you feel that this is "screwing up C++"?! I think you need to motivate that a lot better, especially given that this author provided logical reasons for his issues with the design of std::future. :(
- danabramov 13y agoYou mean like they screwed C#? Or Harmony?
- mpweiher 13y agoyep
- jamesaguilar 13y agoCan you explain what about this article makes you think Haskell people are screwing up C++?
- kpmah 13y agoThey're actually trying to fix C++. :)
- _random_ 13y agoIt's easier to start from scratch.
- Iftheshoefits 13y agoOne doesn't fix perfection.
- freyrs3 13y agoSimon Peyton Jones has always said that the secret goal of Haskell is not to get you to write Haskell but change the way you think about programming. Seems like we've failed to avoid success again.
- deleted 13y ago[deleted]
- wereHamster 13y agoWhat exactly are your objections? 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.
- AnimalMuppet 13y agoYou know, if C++ used the concepts and just put sane (non-abstract-algebra) names on them, that might be really useful. I might get Haskell a lot better if the C++ committee does this well.
- freyrs3 13y agoYeah, moving away from the abstract algebra names definitely improves clarity because ``template <typename HasABinaryAssociativeOperationAndIdentity>`` is a much better choice than Monoid.
- Pacabel 13y agoYour examples are either at the extreme of literalness, or at the extreme of abstractness. The most useful name is probably somewhere in the middle. It may not necessarily consist of everyday words, but it probably relates very obviously and clearly to the C++ functionality. "Monoid" is a very detached term. It doesn't obviously relate to the C++ construct or concept the way that terms like "typedef", "template", "stream" and so on do for other constructs/concepts.
- chongli 13y agoIt may not necessarily consist of everyday words, but it probably relates very obviously and clearly to the C++ functionality. Such as? "Monoid" is a very detached term. It doesn't obviously relate to the C++ construct or concept the way that terms like "typedef", "template", "stream" and so on do for other constructs/concepts. Well of course! Monoid is far more general than those other concepts. It's also a far better name, being unambiguous. Those other names are reused all over the place in different contexts and their meanings subtly shift between their uses. Monoid is not so overloaded; once you learn it, you know what it means every time you encounter it.
- chongli 13y agoSome, not all! I'm a Haskell folk and I've no interest in changing C++. I'd rather just use Haskell and teach others about it! Isn't that novel? 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++.
- AnimalMuppet 13y agoEven if you feel that way, remember part of the philosophy of C++: You don't pay for what you don't use. 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.
- Dewie 13y agoWhy are people trying to ruin the beauty of functional programming by grafting it on like a ninth leg to C++?
- sanderjd 13y agoWhat do you think about a language like Rust that is trying to bring some of these ideas into a C++-like language from the get-go, without the necessity of interacting with code written more than two decades (or one decade, or one year, or sometimes even one month) ago? 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.
- angersock 13y agoSo, I don't know Rust, so I'm not going to try and voice an opinion that would be unsubstantiated. 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.
- chas 13y agoIn my experience, C++ is really a double-edged sword in this regard. 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.
- yngccc 13y agoThe article discusses a proposal to add new functionally to part of the standard library, which just happen to mimic a monadic interface. I fail to see how it even affect the language.
- Iftheshoefits 13y agoYou don't have to use C++XX features you don't like. One of the more beautiful things about C and C++ that I like is that I can go as "bare bones" as I want and still have an incredibly powerful (not to mention performant) language to program in. You didn't (and still don't) have to use STL (any version). You also don't have to use the lambda function syntax or range operator, move operators or rvalue references, or basically any other thing that is "new" to the C++XX standard(s). In fact, if you eschew these things your code is likely to be more portable and longer lived, although it may require more time to develop, and include more re-implementation of boilerplate. 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.
- coldtea 13y ago>Why are all the Haskell and functional folks trying to screw up C++? 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.
- BartoszMilewski 13y agoActually, Haskell people do influence C++ rather heavily. The ideas behind many of the functional aspects of C++ can be traced back to Microsoft Research in Cambridge, UK, where Simon Peyton-Jones works and whose collaborators/students went on to design F#, which very strongly influenced C#, with major contributions from Erik Meijer, a Haskeller extraordinaire and the inventor of LINQ and Reactive. Microsoft PPL library, which is the driving force behind most recent concurrency extensions to C++ has been created by functional programmers. The truth is that C++ cannot survive in the multicore world without an injection of functional programming.
- bitL 13y agoI find it quite funny. Monads were considered a hack to functional programming to add some imperative features like, you know, IO and similar funky stuff for which there was no math theory. Now seeing them grafted to a language that is considered the golden measure of all imperative languages is kinda LOL.
- eru 13y agoThat's somewhat backward. Monads come from Category theory. 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.
- bitL 13y agoSure, monads come from category theory. IO and interactivity doesn't. 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.
- Dewie 13y agoImperative languages seem like state monads. But a monad doesn't need to be a state monad. If you want something different than a state monad, it might not be any more simple to implement that in an imperative language than a declarative one.
- comex 13y ago> 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? 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.
- eli_gottlieb 13y agoPlease no. I liked C. Watching it die the death by a thousand cuts that is C++ featuritis is painful.
- jessaustin 13y agoEh, C++ was always a bit of a lost cause with respect to "featuritis", wasn't it? It's not like you can't still use C.
- Symmetry 13y agoYou can still use C! C++ has always been the sum of all the programming language features Bjarne had heard of and liked, so this is simply C++ continuing in it's traditions.
- dmunoz 13y agoSince the two main comments in this thread are unnecessary negative, I will point out the ongoing discussion in /r/cpp: http://www.reddit.com/r/cpp/comments/1z1b1q/c17_i_see_a_monad_in_your_future/ http://www.reddit.com/r/cpp/comments/1z1b1q/c17_i_see_a_mona... The author of the post is also participating there.
- dmm 13y agoEveryone in the c-preprocessor subreddit is surprisingly open minded about new c++ features.
- pbsd 13y agoI honestly don't understand the outrage here. This is about standard library functionality, not new language features. As far as standard libraries go, C++'s is actually pretty small and could use some additions.
- Suro 13y agoIt's sad to see so much trolling on this language but I suppose we all had to maintain old C++ programs that became spagetti codes and dependancy hells. 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.
- jerf 13y agoI guess the Katamari Dama-C++ is finally big enough to start picking up the functional programming languages. Will the ball never stop growing?
- stormbrew 13y ago... Start? C++ has been picking up functional programming paradigms pretty much since its standardization and the inclusion of the STL in that standard. C++'s evolution has been inexorably in this direction for a long long time.
- jerf 13y agoNot features, languages. We must be nearing the end of the game... C++ may be picking up whole countries soon.
- angersock 13y agoWon't do countries, because its Unicode support is garbage.
- bad_user 13y agoC++ has been an awful language for FP. First of all, you can't do FP without lambda expressions. It's just way too painful to do it without lambdas. Fortunately C++0x took care of that. 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.
- nly 13y agoWhat I would like is a way select() over a set of futures.
- sanderjd 13y agoHow would that be different than the `when_any` function the author described?
- MBCook 13y agoI believe the difference is that you wouldn't have to then iterate over all the futures to see which one fired, it would just return one of them. Boilerplate prevention, I think.
- sanderjd 13y agoThanks, somehow I forgot about the author's complaint about the API of `when_all` between the time I read it and the time I wrote my comment.
- deleted 13y ago[deleted]
- deleted 13y ago[deleted]
- npsimons 13y agoI'm of two minds about this: being moderately competent in C++ (my bread and butter language), and a dabbler and True Believer in Better Languages (ala the blub paradox), I think it might be nice and neat to have more high level features in C++ (yay lambdas in C++11x!). 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.
- danabramov 13y agoIt's not about a language feature, is it?
- jbeja 13y agoI wonder what programming language is not a mess?
- steveklabnik 13y agoI'll just state the obvious: Scheme. ;)
- eru 13y agoAnd Unlambda. Joking aside, Haskell is pretty pleasant to program in most of the time.
- letzjuc 13y agoforcing strict evaluation feels like a mess, template haskell feels like a mess, debugging space leaks feels like a mess, not to mention that the haskell learning curve is very high Haskell is pretty good at a lot of things, so don't misunderstand me, Haskell it's really good! But, at the same time, it still has lots of room for improvement. I guess perfection doesn't exist.
- Locke1689 13y agoMinor nit, but I believe that his description of the async pattern in future is not only monadic, but also comonadic.
- eru 13y agoYes, but only if you turn a blind eye to `get' being a partial function (ie it might fail or diverge).
- theophrastus 13y agoi prefer "holoambiadic". in all relative seriousness, would anyone care to put forward a concise definition of "monad" (for programmers, not math-category-theorists)?
- spion 13y agoFunctor is something that has a map function. 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
- 13y ago
- sixbrx 13y agoFrom skimming the article I can't tell if C++ will have anything akin to type classes, which is how Monad is expressed in Haskell? Is that what "Concepts" will bring and which enables Monad to be expressed as well?
- Sharlin 13y agoThe concept (lower case c) of monads cannot be represented in C++, but you can certainly write monads in it like in just about any language. You just can't make the compiler verify that what you have is actually a monad. As you suspect, Concepts (capital C) should make it possible to type-check monads in C++ like in Haskell).
- dllthomas 13y agoYou can't make the compiler check monad laws in Haskell, either. It would seem to me you should be able to write a Monad template class, though I admittedly haven't tried. 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).
- ajtulloch 13y agoYou can use templated template parameters in C++ - http://stackoverflow.com/questions/213761/what-are-some-uses-of-template-template-parameters-in-c http://stackoverflow.com/questions/213761/what-are-some-uses...
- dllthomas 13y agoAh, so you can! Here's the list monad. I'm not sure the type unification on templates is sophisticated enough to get all of the niceness of Haskell monads (I wasn't able to get bind to work generically, for instance, and I'm not sure what would happen with another instance of pure differentiated only by return type...) and certainly there's no do-notation), but clearly the functionality can be expressed. Still fun. It prints the results of expressions prefixed by their (loose) Haskell equivalents. Applicative included for good measure. #include <iostream> #include <list> #include <functional> using namespace std; // fmap :: (a -> b) -> f a -> f b template <template<typename> class F, typename A, typename B> F<B> fmap(function<B (A)>, const F<A> &); // pure :: a -> f a template <template<typename> class F, typename A> F<A> pure(A); // appl :: f (a -> b) -> f a -> f b template <template<typename> class F, typename A, typename B> F<B> appl(F< function<B (A)> >, F<A>); // join :: m (m a) -> m a template <template<typename> class M, typename A> M<A> join(M< M<A> >); // mbind :: m a -> (a -> m b) -> m b template <template<typename> class M, typename A, typename B> M<A> mbind(M<A> &x, function<M<B> (A)> f); template <typename A, typename B> list<B> fmap(function<B (A)> f, list<A> xs) { list<B> ys; for(auto x : xs) { ys.push_back(f(x)); } return ys; } template <typename A> list<A> pure(A x) { return { x }; } template <typename A, typename B> list<B> appl(list< function<B (A)> > fs, list<A> xs) { list<B> ys; for(auto f : fs) for(auto x : xs) ys.push_back(f(x)); return ys; } template <typename A> list<A> join(list< list<A> > xss) { list<A> ys; for(auto xs : xss) for(auto x : xs) ys.push_back(x); return ys; } template <typename A, typename B> list<A> mbind(const list<A> &x, function<list<B> (A)> f) { return join(fmap(f, x)); } template <typename A> ostream &operator<<(ostream &out, const list<A> &xs) { int i = 0; cout << "["; for(auto x : xs) { out << (i++ ? ", " : " ") << x; } cout << " ]"; } int main() { list<int> xs = {1,2,3}; function<double (int)> halve = [] (int x) -> double { return 0.5 * x; }; function<double (int)> quarter = [] (int x) -> double { return 0.25 * x; }; function<list<int> (int)> repeatOnce = [] (int x) -> list<int> { list<int> ys = { x, x }; return ys; }; function<list<int> (int)> repeatIfEven = [&] (int x) { if(x % 2) return pure(x); return repeatOnce(x); }; list< function<double (int)> > fs = { halve, quarter }; cout << "return 7 = " << pure(7) << endl; cout << "xs = " << xs << endl; cout << "fmap halve xs = " << fmap(halve, xs) << endl; cout << "fmap repeatOnce xs = " << fmap(repeatOnce, xs) << endl; cout << "fs <*> xs = " << appl(fs, xs) << endl; cout << "xs >>= repeatOnce = " << mbind(xs, repeatOnce) << endl; cout << "xs >>= repeatOnce >>= repeatOnce = " << mbind(mbind(xs, repeatOnce), repeatOnce) << endl; cout << "xs >>= repeatIfEven = " << mbind(xs, repeatIfEven) << endl; return 0; }
- malkia 13y agoI for one welcome our muddy::future!
- clinq 13y agoThis is a great example of how theory enthusiasts ignore practical world. Think about similar ironic claim by a C++11 guy: Haskell, I see a lambda in your future!
- kenferry 13y agoI appreciate this article's clear explanation of the topics! I've yet to really get my head around monads et al., but I could follow this article through from beginning to end. Thanks!
- im3w1l 13y ago>Combining functions using next, unwrap (or, equivalently, bind), and make_ready_future is equivalent to specifying data dependencies between computations and letting the runtime explore opportunities for parallelism between independent computations. He wants a jit for cpp?