4 ms·
Pipable functions in C++14
- deleted 12y ago[deleted]
- smallduck 12y agoLook at the 3rd to last code block, especially; I claim it self-evident that C++ is irrevocably broken.
- pfultz2 12y agoHow is it self-evident?
- adamnemecek 12y agoThis is not what one would call 'sane C++'. I think it's more of an exercise than production code. If it is production code, may Knuth have mercy on whoever maintains that codebase.
- nhaehnle 12y agoExcept that nobody in their right mind would actually write code like this on a day-to-day basis. All languages allow the writing of insane nonsense. The question is how much nonsense is actually required in everyday work, and on that point I would argue that C++ is moving in the right direction since C++11.
- pestaa 12y agoWow. I think I'm a decent programmer, but that is some hardcore shit right there. Some of those syntax constructs are really hard to wrap my head around. In a lot of cases `x | f` is more readable than `f(x)` (especially when you want to chain several functions), but there's no way I can remember how to extend the language this way unless I'm a full-time C++ programmer. I don't feel the same in Haskell, for example. Also, function composition should be similar to this, anyone can shed some light how it would be implemented? (I mean `x | f . g` would look awesome.)
- pbsd 12y agoYou can't overload the `.` operator. However, something like this would work: `x | (f , g)`.
- deleted 12y ago[deleted]
- pcmonk 12y agoHow can any sane person think this is a reasonable way to program? While perhaps stated with slight hyperbole, this is actually a serious question. I don't see how, for example, these pipable functions give any additional real expressive power, and they seem incredibly hacky in how you have to build them. I simply don't understand why anyone would use this kind of thing. C makes sense; I can see an argument for C++03; this is madness.
- pfultz2 12y agoWell this can help when you have many nested functions that are chained together, for example, like this: auto r = select(where(numbers, [](int x) { return x > 2; }), [](int x) { return x * x; }); Because of nesting this can be hard to read(and even write). If we can make the function pipable, the above can be written like this: auto r = numbers | where([](int x) { return x > 2; }) | select([](int x) { return x * x; }); Which it is easier to see what this does. So this blogpost goes over how to implement an utility that will take care of the boilerplate involved in writing a function that can be pipable. It does take advantage of a lot of C++14 features to implement this such as such as vardiac templates, rvalue reference, generic lambdas, and auto type deduction, but those feature actually make it simpler. I have in the past implemented something similar for C++03 and the code looks awful with way too much noise. > this is madness. Why do you consider this madness? Maybe my mind has already been warped by C++.
- grundprinzip 12y agoI really like your above example. For people coming from Ruby on Rails or Python Django, such a notation makes it simple to understand what the code will do, even without knowing how to implement it. Thanks
- pcmonk 12y agoTo me, the first is much easier to read, but perhaps my mind has been warped by functional programming languages. At any rate, the thing that's strange about it is how verbose and hackish everything is. It's obvious the language wasn't designed to do anything like this, so the only way you can incorporate features like this is with unnecessarily obtuse and complex blocks of code.
- eps 12y agoI've been programming in C++ for close to 20 years now and the only description for what I feel when looking at this sort of thing is "morbid fascination". It's cool, but it's disappointing at the same time. The C++ I started with looked and felt significantly more logical and easier to grasp than what we have now and this is a very unfortunate way for a language to evolve.
- brooksbp 12y agoTaking a huge risk by saying this (I do not use C++ full-time), but every time I look at C++11 and C++14 I get the feeling that I should just stick with Haskell or <insert-popular-fp-lang-here>. It is insanely more natural to do stuff like this in Haskell. Defer to those with more experience in 'modern C++'.
- MaulingMonkey 12y agoI use C++ more than full time (gamedev -_-;;) out of necessity (consoles, existing codebase, C++ APIs...) If I could swing it, I'd absolutely code everything in C#. Okay, maybe that fails the "fp-lang" bit, but my reasons are basically the same ;). Unity's finally getting around to covering the "consoles" bases, although I really wish they weren't using old buggy compilers and writing similarly buggy APIs. Maybe MonoGame will port to Xbox One eventually...
- gkmoyn 12y agoSomehow I knew the top comment was gonna be "C++ is insane!!" How would you implement pipe functions in Javascript? And I mean literally using the pipe operator, and not just chained. You can't, so you don't. In Java? You can't, do you don't. In C++ you can. You probably won't. You probably shouldn't so others can maintain your code in the future. But still, you can do very advanced things. Thanks, pfultz2, for flexing C++'s muscles.
- pcmonk 12y agoJust because a language allows you to morph its syntax doesn't make it any more powerful. I'm not sure how this is considered an "advanced" thing. It's certainly a convoluted thing, but that's not at all the same.
- malisper 12y agoThere are three reasons why a program would look like this: 1. It is something simple implemented in a complicated way. 2. It is something complicated implemented in a simple way. 3. It is something complicated implemented in a complicated way. I believe this is an example of case 3, meaning even though it is something advanced, it should not take code that looks insane to express it.
- pfultz2 12y agoI disagree. It makes it very simple to make a pipable function, you just wrap the function object in pipable. There's nothing complicated about using it. Futhermore, doing it by hand is not as simple, but still not very complicated. This just helps alleviate the boilerplate in defining pipable functions.
- malisper 12y agoThere's nothing complicated about using it. I'm not talking about using the pipe operator, I'm talking about implementing it. The C++ version is ridiculously complicated. Let's compare your code with an analogous implementation in Common Lisp. (defun pipe (val &rest fns) (reduce (lambda (acc f) (funcall f acc)) fns :initial-value val)) Just this allows for some pretty similar code: (pipe 99 #'1+ #'sqrt #'1-) which evaluates to 9.0 It is possible to implement it in C++, but the implementation winds up being ridiculously complicated. I just implemented something very similar in Common Lisp and it wound up being incredibly simple. Why doesn't C++ allow for a definition nearly as nice as the Common Lisp one?
- kolev 12y agoThis is beautiful! Should be part of all languages. I love this in Jinja, but never thought that this should be native... until today!
- byuu 12y agoI'd really like it if they added D's uniform function call syntax to C++ (http://www.drdobbs.com/cpp/uniform-function-call-syntax/232700394 http://www.drdobbs.com/cpp/uniform-function-call-syntax/2327...). Then this code could be: auto r = numbers().where([](int x) { return x > 2; }).select([](int x) { return x * x; }); Without the need and potential ambiguity that arises from overloading the pipe operator, you'd just use simple free functions instead and it'd just work.
- paxcoder 12y agoPotentially ambiguous, but I assume worth it?
- pfultz2 12y agoIn practice, I've yet to see a problem.
- byuu 12y agoBy ambiguous, I mean that operator|'s precedence is very different than operator.'s (std::operator<< has similar issues); which could lead to surprises if you don't have the precedence tables memorized. operator. is at the optimal precedence for method chaining, and has well understood behavior, so I think it'd be preferred over hijacking things like the bitwise-or operator.
- paxcoder 12y agoHeh, didn't even notice that you mentioned ambiguity too. I was refering to the D's version with the dot operator: A programmer needs to differentiate between function calls and method calls. I wonder which ambiguity @pfultz2 was referring to. But now that you mention it, an operator (such as pipe) with a lower precedence could actually be useful and spare having to jump back in code to open brackets.
- C-- 12y agoI feel they could have stopped with C++03. C++11 certainly introduced very few necessary features but this is just going too far. This is not solving any problems but in reality is causing new ones as introducing syntactical redundancies ultimately leads to everyone having their own preference, which in turn is a source for inconsistent and dirty code bases and bugs. They should have taken a hint from all of those coding standards coming from companies such as Google, which basically constrain the programmer to a small subset of the language features.
- kabdib 12y agoOne rule of thumb I use for code is: Can you step through it in a debugger, at the source level, and have insight into what is going on? Because with really, um, "clever" code, you'll probably need to. And so will your cow-orkers. And if the code doesn't work or has limitations -- quite likely with creeping "clever" machinations like this one -- you'll get Spoken To. (Yeah, this depends on how good your debugger is. Visual Studio and XCode are pretty decent).
- to3m 12y agoThis is the only metric worth paying attention to, in my experience. Whatever you do, your product will end up with defects, you'll need to get rid of them, and towards the end of the project there will always be a huge pile of them. (And, thanks to natural selection, only the hard ones are left. All the easy problems are long extinct.) So why not optimize for this stage? Even if you don't end up turning a time/effort profit overall - which is unlikely - you'll at least benefit from being under far less stress during what's always a fraught period. And for whatever reason, C++ debuggers and debug info formats don't seem to be doing a great job of keeping up with the language. Even basic stuff like nested function calls (as easily found with any smart pointer/iterator or array class...) tends not to work very well, to say nothing of single stepping in to std::function, or watching STL types, or using iterators or smart pointers in the watch window. So this necessarily means being a bit conservative about which features you use. (You might have to go through the shipping-a-product process a couple of times before you really internalize this. But once you've learned it, it really does stick.)
- 12y ago
- IsTom 12y agoThis is a standard construct in functional languages, probably why it's getting into C++14. This "|" is $ in Haskell with its arguments reversed. F# even has it in this particular order of arguments "|>" IIRC.
- cschwan 12y agoThe techniques he used are very similar to "Expression templates". If you are a C++ programmer and haven't heard of it, look it up. There are not many libraries actually making use of it, but Boost uBLAS is an example. I think expression templates give you a good idea what one can achieve with C++ (whether this is a good idea is another question). OT: That's also why I love the language - there are plenty of ways to solve a problem and C++, unlike other languages, does not force me to solve a problem "the right way".