Slashdot Mirror


Ask Slashdot: Do You Like Functional Programming? (slashdot.org)

An anonymous reader writes: Functional programming seems to be all the rage these days. Efforts are being made to highlight its use in Java, JavaScript, C# and elsewhere. Lots of claims are being made about it's virtues that seem relatively easy to prove or disprove such as "Its use will reduce your debugging time." Or "It will clarify your code." My co-workers are resorting to arm-wrestling matches over this style choice. Half of my co-workers have drunk the Kool-Aid and are evangelizing its benefits. The other half are unconvinced of its virtues over Object Oriented Design patterns, etc.

What is your take on functional programming and related technologies (i.e. lambdas and streams)? Is it our salvation? Is it merely another useful design pattern? Or is it a technological dead-end?

Python creator Guido van Rossum has said most programmers aren't used to functional languages, and when he answered Slashdot reader questions in 2013 said the only functional language he knew much about was Haskell, and "any language less popular than Haskell surely has very little practical value." He even added "I also don't think that the current crop of functional languages is ready for mainstream."

Leave your own opinions in the comments. Do you like functional programming?

20 of 418 comments (clear)

  1. It has its uses by RightwingNutjob · · Score: 5, Insightful

    but I'm skeptical about functional as the hammer for every nail. Generics and lambda expressions in C++ can make some niche problems disappear entirely by making the compiler do all the work for you, Scheme and Lisp and the like are useful for some very narrow and very academic use cases. As the go-to tool in the tool box? Not so much.

    1. Re:It has its uses by beelsebob · · Score: 5, Insightful

      There's two big things that have come out of the recent move towards more functional programming which are really important.

      1) People are understanding that reducing the amount of state that any particular bit of code carries reduces the complexity of working with it. Less state means more testability, more easy reasoning about the code, more clarity, more easy debugging, and fewer edge cases to consider. That's not to say that you should never has state, as pure functional programming would have you believe, but reducing state dependance pretty much helps make your code better universally.

      2) People are realising that inheritance is not the be-all and end-all of modelling code that the OOP world would have you believe. They're realising that inheritance is what screws up type systems, and makes them hard to work with. They're realising that deep inheritance hierarchies often lead to complex code which is tricky to understand exactly what code is going to execute when, and where you're going to jump to when you're reading it. Again - this isn't to say you should never use inheritance, but people are realising that composition can work equally well, or better, and that using it over inheritance has some substantial benefits.

      As to the bandwagon of "write javascript, it's a functional language, that makes it brilliant". Fuck off... That's just yet another of the latest fads towards pascal on trains; nodeHaskell; and reactMonkey. I'll happily sit here continuing to write ancient languages, but trying to apply some of the concepts from FP to make my code simpler and more readable.

    2. Re:It has its uses by Dutch+Gun · · Score: 5, Interesting

      Few "in the OOP world" (whatever that means) promotes inheritance as the end-all-be-all these days. I think that went out of style fifteen or twenty years ago. The notion of eschewing inheritance whenever possible has its own Wikipedia entry, and was described in detail in the famous "Design Patterns" gang of four book.

      That being said, there's a time when reality can intrude on "theoretically" clean designs or programming paradigms. Functional programming and unit testing are things you don't see widely used in the videogame development world, at least that I've seen. Not all paradigms and patterns apply to all types of problems. Ultimately, I think that's the most valuable thing I've learned over time. Use the tools and techniques most appropriate to the problem at hand you're trying to solve. Religious wars over programming techniques and methodologies are for pedantic fools.

      --
      Irony: Agile development has too much intertia to be abandoned now.
    3. Re:It has its uses by Z00L00K · · Score: 4, Insightful

      Strong typing with static declarations may seem to be cumbersome to many but the good thing with the strong static typing is that you get slapped already when compiling and not late during execution when an obscure obnoxious condition is fulfilled. Of course unit testing should capture even obscure obnoxious conditions but since not every test is updated when the code is updated then it's easy to miss.

      However sometimes lambdas are also useful - but they shall be used with care. There's no golden solution that can capture everything, instead different parts of an application shall be implemented in different ways to get the most effective solution. It will of course mean that developers have to know more than one programming language and paradigm.

      --
      If builders built buildings the way programmers wrote programs, then the first woodpecker would destroy civilization.
    4. Re:It has its uses by RightwingNutjob · · Score: 4, Insightful

      It ain't f'ing unnecessary. If it's a spaghetti or gotos it'll be a spaghetti of inheritances or a spaghetti of lambda's. At some point, the complexity of the task the program is executing requires complex code. Goto's can be done so that they're easy to understand. So can inheritance. So can lambda's. But you've got to be aware of the fact that some things are just plain hard to understand because they're hard, no matter how good of a communicator the programmer is.

    5. Re: It has its uses by Anonymous Coward · · Score: 5, Interesting

      Lambdas are simple and nice. It's just overhyped and people get confused because hype generates fanboi noise that hide the actual facts.

      One good use of Lambdas is to implement the GOF strategy pattern. You can do it without Lambdas, but it's really verbose and hard to read in Java due to the amount of interface and one time use classes and objects simply to define a processing strategy. Lambdas make it much more concise and simple.

      Its important for frameworks to allow others to specify processing "strategies". Some frameworks like Spring use such techniques very extensively. When you use a framework you want others to write less code and reduce boilerplate, so people who write frameworks find Lambdas awesome. When I write frameworks and engines I get irritated by the sheer amount of boiler plate to do strategy pattern and comment the code so that people can understand my code. Good code should be self readable and strategy pattern on Java isn't readable to less savvy programmers.

      For users of the frameworks it's just a few lines less code which they "cut and paste" anyway and many don't see why they have to spend time learning Lambdas so they can save a few lines here and there.

      I think Lambdas are a good feature to make coding in Java more elegant. Coding elegance has a long pay off and inflict short term pain to change which is why people who don't understand hate it. They hate it even more at the level of hype something with so little immediate value gets forced fed to them.

      I woul agree that if you have less than 5 years left in your coding career, Lambdas are a waste of time.... but hey think of the children!

    6. Re:It has its uses by silentcoder · · Score: 4, Interesting

      The value of a lambda is greatly reduced in a language like python (though it supports them) where functions are first-class objects - when you can store functions and pass them around as variables the benefits of named functions hugely improve and much of what a lambda does can be done more cleanly by using data structures.

      So, for example, by storing functions as values in a dict you can build complex structures of execution without using any conditional codes . A long cluster of nested if-statements can be reduced to a single dictionary accessor. This is one of the standard ways to the common python-challenge of implementing Conway's game of life without using any if statements.

      This, in fact, was what I found most annoying working in Ruby as opposed to python - the fact that functions are not first-class objects force you to use things like lambdas even where more elegant solutions may otherwise have been available.

      --
      Unicode killed the ASCII-art *
    7. Re:It has its uses by TheRaven64 · · Score: 4, Informative

      In C++14 in particular, lambdas with auto parameters dramatically reduce copy-and-paste coding. If you have a couple of lines of code that's repeated, it isn't worth factoring it out into a separate templated function (in particular, you'll often need to pass so many arguments that you'll end up with more code at the end), but pulling it into a lambda that binds everything by reference and has auto-typed parameters can reduce the amount of source code, while generating the same object code (the lambda will be inlined at all call sites).

      --
      I am TheRaven on Soylent News
    8. Re:It has its uses by Big+Hairy+Ian · · Score: 5, Funny

      Religious wars over programming techniques and methodologies are for pedantic fools.

      Us Pastafarians would disagree! We prefer to write Spaghetti Code :D

      --

      Build a Man a Fire, and He'll Be Warm for a Day. Set a Man on Fire, and He'll Be Warm for the Rest of His Life.

  2. Dysfunctional programming by FrankHaynes · · Score: 5, Funny

    seem to be the prevalent choice on the web these days.

    --
    slashdot: A failed experiment.
  3. "Like"? by eyenot · · Score: 5, Insightful

    I don't get what you mean by "like".

    Procedures are procedures, period.

    Sometimes it's helpful to have some procedure (or subroutine) store some value in some location before popping the stack.

    What I really don't get in this write-up is the insinuation that a focus on (purely) functional programming is a "recent trend". That implies that the majority of today's coders have no fucking idea how coding has progressed through the last few decades (which I've been there to see firsthand).

    That's the only interesting thing about this article.

    --
    "Stratigraphically the origin of agriculture and thermonuclear destruction will appear essentially simultaneous" -- Lee
    1. Re:"Like"? by lucm · · Score: 4, Insightful

      What I really don't get in this write-up is the insinuation that a focus on (purely) functional programming is a "recent trend".

      There is a new area where functional programming does shine, and it's large scale analytics. Sometimes when you think about solving a specific problem, you can go about it in a few different ways, but almost every time if your solution later needs to be parallelized (i.e. running on a Hadoop cluster) the functional programming way will be easier to adapt.

      For instance, let's imagine a situation where you have a small e-commerce website and the marketing team wants to know what are the most common sequences of pages visited by users. You could write a quick & dirty python script that parses the logs and creates a hash of every possible sequence, then you could use that to "rank" sequences by time, browser, location, etc. Or you can play the fancy card and use something like Petri nets in a map-reduce-ish kind of way. Both approaches work.

      But then your small website becomes a big success, and grows and grows and grows, and one day your script runs out of steam. So you figure, let's run that bitch on a big Hadoop cluster. Well guess what, a script that is map-reduce friendly will be a lot easier to adapt for that.

      I'm not saying every single situation warrants for this kind of thinking. But that qualifies as a kind of problem that is fairly new for mainstream programmers.

       

      --
      lucm, indeed.
  4. It depends on the use by nanolith · · Score: 5, Insightful

    Functional programming languages like Haskell, ML, and Gallina can be very beautiful. The problem is that they have a steep learning curve that has less to do with the syntax of the language and more to do with the semantics. If one is well versed in category theory or has spent a significant amount of time working with functor spaces, monoids, and monads, then it's much easier to understand a non-trivial application written in Haskell than the equivalent object hierarchy in an object-oriented language. The up-front cost is greater in terms of study and learning the semantics, but the end result is significantly more powerful.

    I love functional programming. I went from C++ to Haskell and C as my go-to languages for personal projects. However, in my professional work, I tend to factor long-term language popularity into my decisions. So, I'm more inclined to use languages like Java, C#, Go, Python, and Ruby when I'm paid to write software. I have to consider the total cost of ownership in my professional work, and part of that cost is finding people to maintain it years from now.

    I think that FP has an elegance that makes it a worthy model, and I hope that some day, FP becomes more popular than OOP. But, I'm old enough to understand that technical superiority rarely wins out to popularity. Popularity matters. This sort of calculus is one of the reasons why FP has not gained much traction despite all of the buzz.

    1. Re:It depends on the use by nanolith · · Score: 4, Interesting

      I don't disagree with your assessment. However, if your assessment is valid, then a functional language is still going to be quite foreign to someone who has only been taught object-oriented programming. I agree that we can go deep down the rabbit hole with OOP as well. The minimal interface that has been extracted from the science behind OOP and introduced to programmers in general is a mere shadow of the works of folks like Barbara Liskov.

      FP has yet to have this generational winnowing. It is still fresh and academic. We can build people up to understand this, or we can pull these concepts down to their most basic versions that are still useful. I suspect that both will have to happen before the industry can meet in the middle with FP. We are seeing this happen already as mainstream languages are adopting bits and pieces of functional concepts. I think it's more likely that we will see functional applications of OOP, such as in languages like Scala, than OOP superseded by FP. That's okay. There are already plenty of examples of non-mutable objects with copy-on-write semantics. We are seeing functions treated more and more like first-class objects. There are examples of the FP-as-style movement taking off.

      I believe that we should teach higher math in high school and even as a requirement for engineering or information systems disciplines. Currently, most universities top out bachelor degree seeking students specializing in these disciplines to calculus, differential equations, and linear algebra if they are lucky. It would be nice to see abstract algebra and some category theory taught as well. When I advise people genuinely interested in pursuing software development as a career, I strongly recommend that they minor in mathematics so they can have the opportunity to take these more advanced classes.

      That being said, there's nothing that prevents people from studying this for self-improvement. Learning either or both OOP and FP will fundamentally change the way that one organizes software. I'd love to see high school kids exposed to these concepts and the mathematics behind them. Then again, I'd also love to see high school kids taught how to build their own CPUs from 74-series logic ICs. Understanding the theory of computation at an intuitive level will do incalculable good for most of these kids through the rest of their careers. If I were to teach a class to high school level students, it would be along this line. I can guarantee that they will never look at a computer, embedded device, or "smart" device the same way again.

  5. What is functional programming? by corporate+zombie · · Score: 4, Interesting

    Wow. Really?

    Functional programming.

    1. Prefer non-mutable data. No more action at a distance bugs. Hand off a reference to your data structure and don't have to care. Replay any data transform at any point as a unique structure.
    2. Prefer a defined and well known API often involving transforms that take a function as an argument to provide the predicate (e.g., filter), transform (e.g., map), aggregation (e.g., foldLeft/Right), or whatever building block.
    3. Prefer data structures that you can reason about based on a well-known set of patterns. (Best quote ever: "You say `patterns' and everyone is warm and fuzzy. You say `monad' and every loses their f-ing minds.)

    Given (2) in a language you'll often see in a language that functions are first-class data.

    Functional programming is just (a set of) best-practices. It's scary when the big words are new. Once you use it a bit you'll wonder why when you say, "use a flatMap", folks freak out because all you've said is, "You are transforming the elements of some container into values that are themselves an instance of the same container but you want to flatten everything back from nested containers. [E.g., Container is C with element type A; thus C[A]. You've run a transform that will create C[C[A]] but want to end up with C[A] at the end]." Now you could say that second part but that's a lot of words. Because of points (2) and (3) above we just say, "use a flatMap" (or however you spell `bind` in your language of choice).

    Nothing to see here. Please move along. (And yes. I like functional programming. A lot.)

  6. Functional is useful when not pure by PhrostyMcByte · · Score: 4, Insightful

    The best functional programming to me, is the kind being integrated into various primarily procedural languages. I use it daily in C# at work, and find it invaluable in performing complex transformations on data. Python, C#, etc. have the best of both worlds -- the choice to use whatever is best for your situation.

    I'll expand further, maybe to start an interesting conversation because I'm sure someone will disagree: purely- or mostly-functional languages are the original hype-driven languages. A lot of people say they're amazing, but don't actually do anything useful with them. Sure, some are making great apps with them, but they're clearly the exception. At the end of the day most of the people I've talked to who preach about how awesome their favorite functional language is have only gone skin-deep. Their experience is limited to the academic or experimental, and has never gone into the practical.

    The few times I've tried to really master these languages, I've been left with no epiphanies. I've found it extremely useful for some problems, like data processing mentioned above. But for most everything else, it doesn't get me anything useful. On some level it is nice having the flow of immutability -- it "feels" right, like you've discovered something special. The same way adding an extra layer of abstraction on top of something might feel. But when I'd look back on it and ask myself what I gained from having it, there's really very little to be found. It is, mostly, a dogma.

  7. I couldn't get past "how do you write a game"? by Jeremi · · Score: 5, Interesting

    When I was learning about functional programming in college, I got about as far as learning about the avoidance of side effects, at which point I started asking myself, "how would one write a video game in an FP language if you're not supposed to e.g. update the player's on-screen position in response to a keystroke"? The answer I got was to either generate an entire new game-state for each update (which seemed unwieldy), or work around the problem using monads, which admittedly I never really understood. I went back to procedural programming since that looked like the more straightforward way to implement the kinds of programs I wanted to write.

    My question now is, do people ever actually write video games using functional programming? And if so, how would an FP-based arcade-style video game realistically handle things like updating the state of the player and the monsters at 60fps, as the game progresses?

    --


    I don't care if it's 90,000 hectares. That lake was not my doing.
  8. Functional Programming Considered Harmful by doom · · Score: 4, Funny

    I tried a websearch the other day on "functional programming considered harmful" and found remarkably few hits. If anyone is so inspired, there's an opportunity there to gain some fame while earning the emnity of the hordes of javascript kids and half of the Computer Science digirati.

    1. Re:Functional Programming Considered Harmful by dgatwood · · Score: 4, Interesting

      It needs to be done and done well. Very tempting. But alas, just like drug use, there's only so much any sane person can write about the subject, because anyone who knows functional programming well enough to fully explain why it is harmful is probably mentally damaged beyond the point of being able to understand why it is harmful. :-D

      The thing is, functional programming is a good paradigm for students to be exposed to in school. Briefly. It forces you to think about data flow through your program, and forces you to think about your software as a giant state machine and visualize how the states change as your software does work. It is not the only way to teach that concept, but it is a halfway decent way. And once you pick up those concepts, you'll start to understand why singletons are so useful (approximately the polar opposite of functional programming, but often the software equivalent of the data you'd be passing around in a functional world).

      So basically, there's a time and a place for everything, and it's called college. But just like with drugs, if you continue to do significant amounts of functional programming after that, don't be surprised if the rest of us ask what you're smoking. Functional programming as a real-world paradigm tends to be almost invariably a disaster, because it neither fits the way we think about problems (human thinking is almost entirely procedural) nor the way machines do work (computers are inherently procedural). It can provide useful extensions to procedural programming languages that serve specific purposes (e.g. closures), but calling functional programming useful for that reason is akin to calling a diesel-electric freight train a perfect commuter car that saves fuel because a Prius is also hybrid hydrocarbon-electric.

      About the only space where functional programming techniques might really make sense is when working in a massively multithreaded environment, e.g. creating really efficient implementations of certain massively parallelizable functions (such as FFTs). But for the most part, that functional programming is limited to creating components that are then utilized as small (but performance-critical) parts in what is otherwise on the whole still procedural (or OO) software.

      Outside of those very limited scopes, though, the theoretically ivory-tower-pure, zero-side-effect functional programming model is pure garbage. Real world systems don't just have side effects; they are side effects, whether you're talking about storing data on disk, sending it over a wire, drawing it on the screen, reading data from a keyboard, or whatever. The notion of treating all of those "side effects" as some giant state object that mutates as it gets passed around is fundamentally antithetical to real-world use of the data, because state must be stored to be useful. And the entire notion of passing around the complete state of real-world software is so far beyond infeasible that the concept is utterly laughable. Cell phones have a gigabyte of RAM, not a petabyte. There's simply no way to write something like MS Word in a pure functional language, because it would take all the computing resources on the planet to barely run a single instance of it.

      Using functional programming in most real-world environments, then, cannot possibly do anything but cause brain damage, because the whole functional paradigm is wrong for the problem space. It is like cutting the grass on a football field using only a single pair of nail clippers—theoretically possible, but completely infeasible. To that end, although I wouldn't say that functional programming is inherently considered harmful, it should be approached with approximately the same level of skepticism as goto statements, and for approximately the same reason. When used correctly, in a very limited way, it is a powerful tool to have in your toolbox that can seriously improve your software. When overused or misused, it is a black hole that consumes infinite amounts of programmer time while emitting very little.

      --

      Check out my sci-fi/humor trilogy at PatriotsBooks.

  9. Hard stuff is, in fact, hard by fyngyrz · · Score: 5, Interesting

    I would add to this that reducing the complexity by turning everything into separate functions tends to also increase what I call "opacity by non-locality."

    Not only are some things hard, some things benefit from having the logic right there in front of your face; not in a header, not in some function elsewhere, not in a library.

    Benefits in both comprehension, and so ease of construction, but also in execution time and smaller executables depending on just how smart the language is in constructing its own executables.

    --
    I've fallen off your lawn, and I can't get up.