11 ms·
Functional programming in C++ (2012)
- posharma 6y agoI wonder if there’s a modern c++ version of this somewhere.
- keyle 6y agoThat post is on multiple websites and I think it's one of the best written one by Carmack because it hits home directly (it applies to software as well as games). I think it gets posted once a year on HN. No regret though I don't mind an echo chamber of good thoughts.
- andi999 6y agoBasically he says you can't really do that in c++, because of performance (which is crucial otherwise why u use c++; last part is my addition)
- nielsbot 6y agoIs that what he says? I thought he said “As functional as makes sense, but not more.” I haven’t read this post in a while, but it’s definitely a worthwhile read.
- Jtsummers 6y agoYour interpretation is correct. He describes things that you shouldn't try to imitate in C++ (like appending an element to a vector by creating a copy and then appending to that). But also describes other situations where having a pure (or near-pure) functional version can be greatly beneficial. Like a method on vectors (math sense) that return a normalized version, or adding string methods which return a copy rather than mutate in place (think: upcased versus upcase).
- andi999 6y agoYes, that's what he also says, but this works best for very simple parameters. If things get interesting and you have bigger data structures there is (too much) performance penalty. I am a bit cherry picking here, but let me just cite "Actual functional languages are implemented in ways that make this not as disastrous as it sounds, but if you do this with typical C++ containers you will die."
- Jtsummers 6y agoHe's specifically referring to one thing that shouldn't be done in a functional style in C++, not saying "you can't really do that" as you originally post. The rest of the article is advocating a move towards pure-r functions in C++ (at least in addition to impure, mutating functions).
- andi999 6y agoMaybe I come from a different direction, lots of data. If you do any functional programming on these you are creating new lists/vectors (the type) left and right. To me this is the gist of functional programming. So when I started the article, I was wondering how would you do that in c++, well his answer is you shouldn't. So when you are saying it is just one thing for me it is like a car without an engine (also only missing one thing). (the other thing about functional programming is the widespread use of recursion, but this is not even mentioned in the article)
- neuromanser 6y agoI can't tell if your reading comprehension is completely shot, or if you're willfully misrepresenting the drift of the article.
- jimbob45 6y ago“The lack of any language support in C++ for maintaining purity is not ideal.” I get that C++ is already bloated and bolted on to C as is but I would have preferred to see changes like these instead of sugary bloat like “auto”. Adding a “pure” keyword allows testability not otherwise attainable without modifying the compiler. Adding “auto” is just a me-too to the “var” of C# and Java. Basically, I’m trying to say that C++ needs to have its standards committee fired.
- voldacar 6y agoD has a "pure" keyword and it works quite nicely. Agreed about the standards committee lol
- moonchild 6y agoD's pure doesn't work very well at all. Because there's no ecosystem of pure functions, a single impure function in the transitive closure of your dependencies can ruin your day. (Unless you depend on no code written by other people.) Compare with haskell, where effects are enumerated and purity is the default: most functions are pure.
- mhh__ 6y agoIdiomatic D code tends to use a lot of templates so this is true but much more prevalent if you write C-with-pure than (say) the code I tend to write (an incomplete C preprocessor+binding generator at compile time is the most D-ish thing I've done yet)
- voldacar 6y ago> Unless you depend on no code written by other people. Yeah that is me. I can certainly see how a program that uses a lot of libraries would have issues with pure though. Not sure what the solution to that would be other than going full haskell mode, which isn't what people who use C++/D would want anyways
- thechao 6y agoThe stds committee is similar to a regulatory capture situation: all the people who really cared gave the fuck up.
- seanalltogether 6y ago> A large fraction of the flaws in software development are due to programmers not fully understanding all the possible states their code may execute in. I think about this quote often in my day to day programming. Object oriented programming is so full of stateful objects and it's easy for programmers to add listeners to all sorts of events. Even on the cloud side now you have all these micro services and trigger functions and small changes can have cascading consequences.
- mumblemumble 6y agoThis has really been hitting me lately, as I try to understand a legacy program whose original authors are long gone. But not in a way that implicates OOP. The code is written in a functional language, and, while it's not one like Haskell whose compiler enforces any rules about referential transparency, I have yet to encounter a single mutable variable. However, it is constantly poking at a database, and different modules communicate with each other asynchronously over a message queue. And those two things are making it just impossible to reason about program state at a macro scale. To me, it really speaks to how functional programming is not the panacea it's often made out to be. I'd honestly prefer if it were just some crusty old Java monolith where all the objects are stateful, and have setters for every field, and all that good^H^H^H^H stuff. Because, while that kind of statefulness may not be well-isolated, it is navigable. I can splat-B and cmd-F7 my way into a decent understanding of how the application's state is getting twiddled. With this, I'm having to grep the code and manually sift through the lexical search hits to find what I need to know.
- Twisol 6y ago> I have yet to encounter a single mutable variable. > However, it is constantly poking at a database, and different modules communicate with each other asynchronously over a message queue. I think you found your mutable variables... No, I agree, functional programming on its own is not a panacea. Every program has state, even functional programs. FP promotes modeling state implicitly, by representing it in the program text itself (or more precisely, the "continuation" of the program). The evaluator of the program is responsible for managing that state, rather than the program author themself(^). The problem is that, since the state is implicit, it becomes hard for multiple modules of the program to collaborate over that state. There are ways around this -- for instance, have each module supply descriptions of the changes they want to apply, and have a central authority manage the actual state -- but you ultimately end up with some way to "address" the state, either explicitly or by reference to an entity that owns it. In either case, you have the "address" of some thing that may change over time, and so you've got yourself a mutable cell. All this to say that FP is indeed not a panacea -- every system needs to have a clear data model. Not only the structure of the data needs to be understood, but also the ways and means in which it is allowed to evolve over time. (Something something Linus Torvalds and Fred Brooks something flowcharts vs. tables something data vs. code.) It sounds like the system you're grappling with has a very loose data model -- I'm not surprised it isn't navigable. But the core idea I at least take away from FP -- that explicit state should be avoided -- is still vitally valuable, even if you approach it differently in different environments and for different problems. "Out of the Tar Pit" is a wonderful exegesis of the idea. [1] (^) Does singular "they" become "themself" or "themselves"?... [1] https://github.com/papers-we-love/papers-we-love/blob/master/design/out-of-the-tar-pit.pdf https://github.com/papers-we-love/papers-we-love/blob/master...
- bikeshaving 6y ago> A pure function only looks at the parameters passed in to it, and all it does is return one or more computed values based on the parameters. It has no logical side effects. This is an abstraction of course; every function has side effects at the CPU level, and most at the heap level, but the abstraction is still valuable. Rereading this for the umpteenth time, this is the paragraph which sticks out to me this time around, and a point which I think most people miss, specifically the latter part about “pure” functions consuming CPU and memory. The reality is that there is no such thing as a “pure” function, insofar as execution of that function costs something. Certain functional programmers corrupted this idea to somehow mean pure functions are free; that these functions can be executed one to infinity times and the result is the same. For instance, this idea taken to an extreme has resulted in the current situation with React.js, where most React applications pathologically over-execute the “pure” rendering functions which we use to define components, resulting in degraded performance, increased GC pressure, and a lack of understanding of how our code executes. Just because you can call a pure function many times doesn’t mean you should.
- Jtsummers 6y ago> Certain functional programmers corrupted this idea to somehow mean pure functions are free; that these functions can be executed one to infinity times and the result is the same. I'd be very curious to read someone claiming anything of this sort. One benefit (with respect to the CPU) of pure functions is that they can be cached because you know you'll get the same result for each call (of course, this impacts memory), which you can't guarantee with impure functions. But that's a tradeoff of memory for time. I've never seen anyone claim there's no cost to a pure function.
- bikeshaving 6y agoWhen we say “pure functions are free” out loud, of course it seems categorically false, and I don’t think anyone has ever credibly argued for this claim. And yet I think it is an implicit assumption of a lot of functional programming development, specifically that which attempts to build “referentially transparent” systems on top of an imperative, impure systems and languages, rather than starting with a new language from scratch. My example of React.js is the pinnacle of this, all features like hooks, contexts, and concurrent mode only make sense when they estimate the cost of re-executing pure functions to be free, or at least negligible, and yet real-world experience indicates this is definitely not the case. > One benefit (with respect to the CPU) of pure functions is that they can be cached because you know you'll get the same result for each call (of course, this impacts memory), which you can't guarantee with impure functions. But that's a tradeoff of memory for time. In my personal experience, I’ve become pretty skeptical of trading memory for execution time. Especially in garbage-collected languages, what you save in execution time you lose in GC pauses, so the end result is you get neither.
- CodeGlitch 6y agoSo the big win with functional programming is easier testibility and fewer hazards when trying to multi-thread your code. With test-driven development is it not the case that you are forced down the path of making your C++ code testable anyway? With multi-threading, there are numerous strategies to achieve this within C++ without blowing your foot off. Takes dicipline I know. Basically what I'm saying is, if functional programming is so great, why did LISP et al not take over the world? (Not a LISP hater, just curious).
- mhh__ 6y agoLISP and programming in a functional manner is comparing apples and oranges, surely?
- ashton314 6y agoJust some speculation, but one reason why C and friends took off better in enterprise domains is that they were on systems that people needed (C with Unix) or were more aggressively marketed. (Java) functional programming languages tended to not be as fast for single threaded programs compared to their imperative and object oriented counterparts. Now that we have stopped seeing such large gains in single thread and performance, most of our scaling comes from being able to scale horizontally. Functional programming languages are making a resurgence: the rise of Rust, Elixir, Scala, etc. is in response to this. I’m sure pg has plenty to say on the topic.
- lalaithion 6y agoDidn't LISP take over the world? Sure, not syntactically, but lambdas, complex expressions, garbage collection?
- seer 6y agoThis is indeed a very interesting question! I’ve also asked myself that time and time again, along the path of slowly discovering what this FP thing is all about over the course of my career. It does look wonderful, it does save you a lot of effort in some cases, where “some” is a vast swathes of computational problems. And its so damn elegant. A lot of examples are thrown around were a bunch of lambda calculus can result in 10-20 fold reduction in source code size. So where’s the catch?There has to be something wrong right? Well recently I stumbled upon a clojure conf talk that tried to tackle precisely this question. https://youtu.be/QyJZzq0v7Z4 https://youtu.be/QyJZzq0v7Z4 The short of it is that its more of a historical inertia and chance than any specific hidden gotcha. Fascinating talk.
- abhinav22 6y agoI honestly don’t get the rage with functional programming. I find the hardest parts is GUI and user interactions, this is a place where storing state is natural. Perhaps more on the server side functional programming is useful. Can somebody meaningfully explain to me why there is such a swell of interest in this field? Is it just all the ML and data scientists buzzing about an approach that is naturally suited to them or is there broader implications? I wouldn’t have guessed that everybody on HN was working on optimizing multi threaded applications or any of the other valid reasons to consider FP more generally.
- keurrr 6y agoTalking about GUI and data science... So ironic. Look at the author and when this was written.
- axguscbklp 6y agoHas Carmack coded anything interesting since he got into functional programming?
- kuiro5 6y agoHe rewrote Wolfenstein 3D in Haskell: https://www.youtube.com/watch?t=127&v=1PhArSujR_A&feature=youtu.be https://www.youtube.com/watch?t=127&v=1PhArSujR_A&feature=yo....
- gfxgirl 6y agoI watched this > year old video about C++ 2020 and feel like I totally changed my outlook on C++ to from kind of negative to fairly positive. https://www.youtube.com/watch?v=u_ij0YNkFUs https://www.youtube.com/watch?v=u_ij0YNkFUs
- huhtenberg 6y agoSo watched the talk just now. I've been using C++ as my main language since the early 90s and it pains me to see what it has become. I thought that I might've been missing something all along. Unfortunately, I wasn't. The talk all but confirmed my lingering assumption that C++ is intentionally designed to be an over-engineered language with no particular regard to the elegance of its construction. Worse yet, Bjarne did it all of his own free will rather than being forced into that by "the committee" (which would've been a weak, but acceptable excuse). If C++ were created just today, out of thin air and in its current form, there is no way in hell it would've seen any adoption. C++ is basically a long running bait-n-switch scheme. Come try a better C and then see it evolve into the Homer's car, which you have no choice but to use because it's now - surprise - an industry standard. So, yeah, there you go /rant.
- einpoklum 6y agoProgramming, and functional programming in particular, has changed a _lot_ in C++ since 2012: * Important libraries have been developed (e.g. Niebler's ranges) * The community has gotten used to C++11 constructs and getting the most out of them * The language itself has evolved, with 3 new standard revisions in 2014, 2017 and 2020; the latter change is actually pretty significant and we're only starting to observe its effect. So, even before reading this piece, you must realize it is quite outdated.