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?

70 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 beelsebob · · Score: 2

      The same problem they solve in any other language - they allow you to easily express a function that captures values from a dynamic scope.

    3. Re:It has its uses by thogard · · Score: 3, Insightful

      I see lambdas as the opposite end of the pendulum swing from the goto statement.

      They have their place but they both lead to lots of confusion with poor coders who are trying to maintain very old code.

    4. Re:It has its uses by plopez · · Score: 2

      *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*

      In the GoF book they flat out state that they prefer aggregation to inheritance. There is a reason you cannot do diamond inheritance in Java. Am I the only one who got the memo?

      --
      putting the 'B' in LGBTQ+
    5. 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.
    6. Re:It has its uses by jandrese · · Score: 3, Insightful

      There is certainly value in reducing the amount of state you are managing, but too often it seem like Functional programmers are willing to declare it gone when they've just swept it under the rug. Sure you don't have a variable now, but instead you have the logic tied up in your stack. This is especially true when the language does pattern matches on the parameters to determine which function to call. In the end you have to keep track of that iterator somehow, and I tend to think something like a for loop tends to be clearer than looking through the function headers to figure out how the loop is initialized and when it terminates.

      --

      I read the internet for the articles.
    7. Re:It has its uses by dcollins · · Score: 2

      "People are realising that inheritance is not the be-all and end-all... 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..."

      I'm pretty sure it was 1990 when one of my professors said, "We used to worry about spaghetti GOTOs; now we have to worry about spaghetti inheritance".

      --
      We know where leadership by an anti-intellectual "strongman" who scapegoats minorities and likes boisterous rallies goes
    8. 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.
    9. Re:It has its uses by Z00L00K · · Score: 2

      And spaghetti inheritance is especially prevalent in some solutions where there's an unnecessary amount of interfaces declared - so that everything is just declared and accessed through badly documented interface items so you can't figure out how to create new objects when you need them.

      Don't get me wrong - interface declarations are good too, but they have to be documented so others can understand how the objects they carry are constructed. The overall system design strategy is also something that has to be well thought out. Too much work put into abstracting away the physical world can create a system that's hard to maintain too. Layers upon layers hiding how stuff really works means that nobody will be able to understand it after a while.

      --
      If builders built buildings the way programmers wrote programs, then the first woodpecker would destroy civilization.
    10. 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.

    11. 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!

    12. Re: It has its uses by thsths · · Score: 2

      The beauty of Lambda expression is that it moves features that are classically considered key language elements into a library: if-then statements, loops, etc can all be library functions. And it makes typical library function like optimization algorithms or other analysis methods much easier to use. In numerical computing, Lambda expressions certainly have their place.

      Of course in GUI development, Lambda can also be very convenient. But you need to make sure that you keep concerns together, and that can be a challenge.

      Coming back to the original question of Java: Java was a good language, but a poor implementation. What really kept it back was the license: Java (like Flash) was always designed as a plug-in, running side by side with the browser, not an integrated part of the browser. The Javascript engine is much more powerful in terms of interaction with the browser (DOM and stuff), and that is the reason it succeeded.

    13. Re:It has its uses by DrXym · · Score: 2
      They're a relatively concise way of creating a reusable anonymous function and binding values to them and having the code inline and next to the functionality it's relevant to. This isn't a new concept since C has always allowed function pointers to be passed around (e.g. for qsort) and boost has had function bindings well before C++11. But now they're part of the language and therefore more useful.

      But like all things they should be used with due consideration. C++ doesn't help itself by having horrible syntax for iterating collections.

    14. 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 *
    15. Re:It has its uses by silentcoder · · Score: 3, Interesting

      I would argue that OO remains the best paradigm we have for constructing data presentation - especially when the data represents something that exists in the real world (or a reasonable facsimile as in GUI programming or video-game dev). Functional programming on the other hand - is often the best paradigm we have for data processing, especially big data processing. Use them each in their own domains and break these rules-of-thumb whenever it makes sense to.

      --
      Unicode killed the ASCII-art *
    16. Re:It has its uses by dcollins117 · · Score: 3, Insightful

      They have their place but they both lead to lots of confusion with poor coders who are trying to maintain very old code.

      If you're using poor coders to maintain very old code then perhaps the choice of programming style is not your biggest problem.

    17. 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
    18. Re:It has its uses by TheRaven64 · · Score: 3, Interesting

      This needs moderating up. Talk to an Ocaml programmer and a Haskell programmer about what makes a functional language and you'll see very different opinions and these two are languages that were actually designed as functional languages: the bits that end up in other languages are a tiny subset.

      Coming from the Haskell side, I see functional programming as programming without side effects and with monads. You can implement monadic constructs in other languages, but it rarely makes code cleaner. Just having higher-order functions doesn't make a language a functional language any more than having structs makes C an object-oriented language.

      If the question is 'do you think using higher-order functions simplifies the expression of some algorithms' then the answer is obviously 'yes': programmers have a lot of tools to choose from and most of them are useful at least some of the time.

      --
      I am TheRaven on Soylent News
    19. 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.

    20. Re:It has its uses by Moridineas · · Score: 2

      I remember back in school writing a (very rudimentary) MIPS emulator for a class assignment. Since most of the students had never used C before school (and were, in any case, more used to C++ references than pointers), apparently I was the only person in ~10 years that implemented the emulator using an array of function pointers (indexed on op codes). I thought it was a pretty cool innovation, then I read about jump tables.

      Still cool :-)

    21. Re:It has its uses by silentcoder · · Score: 2

      That's actually a very similar technique - and its a perfectly valid one, it's also a very FAST one since accessing an array element (or for that matter a dictionary value by key) is an atomic operation that only requires a single CPU instruction. Python making functions first-class object is, effectively, a very elegant way of bringing the capabilities of C's function-pointers into a high-level object oriented language, and a bit easier to work with since you're not (visibly) dealing with pointers since you can address the function by name.

      def test( str ):
          print("Hello %s" %str)

      test('John') #Calls the function - prints 'Hello John'
      mydict = {'X': test} # Address the function, stores it as a value in the dictionary, does not run it
      mydict[X]('Mike') #Prints 'Hello Mike'

      It is also possible to use a function as the KEY in a dictionary - though I've never seen anybody actually do that and I would be hard pressed to come up with any use-case for doing so.

      --
      Unicode killed the ASCII-art *
    22. Re:It has its uses by Wootery · · Score: 2

      very small chunks of performance-critical code, such as massively parallel bits down in the guts of raytracing engines. Now whether they actually use functional programming languages or not is another question.

      Looking at OpenCL/Vulkan/Direct3D/OpenMP/etc, the answer seems to be a clear no. The lots-of-'threads'-running-sequential-C-code model seems to work pretty well though, and programmers are essentially forced to think about state. You don't stand much of a chance messing about with globals in those environments (but I guess you could try it).

    23. Re:It has its uses by beelsebob · · Score: 2

      Games dev actually avoids OOP like the plague these days. Anything that runs on the GPU is purely functional, much of what runs on the CPU is purely functional, and data oriented rather than object oriented. Games devs care more about whether you can keep everything in cache, and crunch through it, rather than whether its modeled nicely.

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

      This was the subject of Brian W. Kernighan's paper: Why Pascal is Not My Favorite Programming Language, where he analyzes converting software tools to Pascal. His conclusion summarized the problems I was having in being forced to use ADA for DOD. Of course in the DOD's case, they deliberately closed the language, and that's why C passed it by.

            9) There is no escape.

      This last point is perhaps the most important. The language is inadequate but circumscribed, because there is no way to escape its limitations. There are no casts to disable the type-checking when necessary. There is no way to replace the defective run-time environment with a sensible one, unless one controls the compiler that defines the ``standard procedures.'' The language is closed.

      People who use Pascal for serious programming fall into a fatal trap.

      Because the language is so impotent, it must be extended. But each group extends Pascal in its own direction, to make it look like whatever language they really want. Extensions for separate compilation, Fortran-like COMMON, string data types, internal static variables, initialization, octal numbers, bit operators, etc., all add to the utility of the language for one group, but destroy its portability to others.

      I feel that it is a mistake to use Pascal for anything much beyond its original target. In its pure form, Pascal is a toy language, suitable for teaching but not for real programming.

      http://www.cs.virginia.edu/~evans/cs655/readings/bwk-on-pascal.html

    25. Re: It has its uses by Lije+Baley · · Score: 2

      Heresy! How dare you take the focus away from the almighty Tool? You are practically taking food right out of the mouths of authors and trainers! And don't forget the psychic damage to the gurus! Why won't you think of the gurus??

      --
      Strange things are afoot at the Circle-K.
    26. Re: It has its uses by lgw · · Score: 2

      I never had the need to circumwent the type system, and I used plenty of languages, where you simply can't circumvent it.

      Not sure what language you're using, but most have either void* or Object. The more refined version is "downcasting" a base type to a derived type. Any time you set the type of an object dynamically at runtime, you're bypassing strong type checking. And don't get me started on reflection.

      --
      Socialism: a lie told by totalitarians and believed by fools.
    27. Re:It has its uses by lgw · · Score: 2

      Explain to me, what problems do lambdas solve in C++?

      Lambda make for sane "list comprehension", that is, transforming a list in some simple way, or taking a simple action for each item in a list (or any other collection).

      C++ was years behind pretty much every other mainstream language but C in list operations. You should never need to code a for loop to do something simple to or with each item in a list.

      Also, more generally, lambdas are useful everywhere for defining function that are short, and only called from one place. As a sibling post points out, they are "function literals", and with other sorts of literals, code is more clear if your literals are simply in-line in your code, not defined elsewhere (when the value is only used once).

      Returning a lambda as the result of a function is where is gets dubious: usually at that point, it's going to be more clear and easier to debug to make a named class/interface that expresses the captured functionality, with a named method. More typing, but self-documenting. Any time a lambda is used from where you can't see the definition, it's a warning sign the code may be confusing.

      --
      Socialism: a lie told by totalitarians and believed by fools.
    28. Re:It has its uses by jellomizer · · Score: 2

      The computer scientist in me loves functional languages, the MBA in me doesn't.
      Functional languages makes very tight code. Which for the programmer and the computer scientist is great. Less coding, a solid routine with little effort.
      However it makes it difficult to maintain a program over a life time. As it is always near one feature away from a full rewrite, vs just slapping some if conditional in the code which while inelegant, is easy to code, easy to see the change, and easier to test.
       

      --
      If something is so important that you feel the need to post it on the internet... It probably isn't that important.
    29. Re:It has its uses by HiThere · · Score: 2

      Functional languages are a bit more difficult to think about, but that may be a combination of my inexperience and the implementations I've seen. OTOH, some problems do not deal with with lack of state. I'd really like to use Erlang, e.g., but I need mutable state. You can do it in Erlang, but you've got to fight the system to do it.

      Note: I don't need externally visible mutable state. That's clearly dangerous in a concurrent system. I need internally mutable state. In Erlang that means either storing things in a hash table, a database, or a block of uninterpreted bytes. All ways that are clumsy to handle (and, I presume, slow). That Erlang allows this indicates that it is seen as something that is concurrently safe. But the difficulty in doing this shows that the designers of Erlang didn't see this as anything important for their use cases.

      Now it's a good question whether or not you consider immutability a part of the definition of functional programming. Lisp allows mutable state, so does Scheme. So does Erlang. But they all discourage it and make it difficult to use. It's my contention that the definition should restrict itself to shared mutable state, but I'm not sure that this is the consensus.

      --

      I think we've pushed this "anyone can grow up to be president" thing too far.
    30. Re:It has its uses by JesseMcDonald · · Score: 2

      There's no real difference between a lambda and an object full of state, beyond the syntax. Lambdas capture arbitrary state.

      When functional programmers talk about state they're referring to mutable state. What you are describing is simply data. Capturing immutable data provided through function arguments does not violate referential transparency. You still get the same result for the same arguments.

      Plus, in real software, the results of some functions is often some measurement of some changing real-world thing.

      That isn't a function, not in the mathematical sense. In Haskell it would be referred to as an I/O action. In functional programming objects exist which describe "impure" actions, such as sampling a sensor or printing to the console; these objects can be manipulated by pure functions, e.g. combining two actions to make a larger action, or mapping a function over the result, but are only executed (logically speaking[1]) by an impure external interpreter in the language runtime. The program itself is pure, even the parts which evaluate to IO actions—barring abuse of specific constructs like unsafePerformIO. The runtime, inevitably, is not pure, since has the responsibility of interfacing between the pure program and the real world.

      [1] For performance reasons, of course, the compiler actually "inlines" the interpreter, generating impure object code similar to a traditional compiled imperative program. The external interpreter, like the C virtual machine model, is merely an aid for thinking about the code, not a concrete implementation.

      --
      "The state is that great fiction by which everyone tries to live at the expense of everyone else." - Bastiat
  2. Dysfunctional programming by FrankHaynes · · Score: 5, Funny

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

    --
    slashdot: A failed experiment.
  3. functional composition by motorsabbath · · Score: 2

    I like functional composition, it certainly has its uses (at least as middleware). I disagree with the notion that it makes code more readable though, in general. It only makes code more readable if you're familiar with it (functional programming).

    --
    The heat from below can burn your eyes out
    1. Re:functional composition by Pseudonym · · Score: 2

      It only makes code more readable if you're familiar with it (functional programming).

      Well that's a truism. Object-oriented programming is the same: it only makes code more readable if you're familiar with it.

      The main distinction between the two, however, is that object-oriented programming was invented, but functional programming was discovered.

      --
      sub f{($f)=@_;print"$f(q{$f});";}f(q{sub f{($f)=@_;print"$f(q{$f});";}f});
  4. Scala by Anonymous Coward · · Score: 3, Interesting

    I prefer to use functional programming where it makes sense (most of the time). One reason I like Scala is that it's not pure. You can always write a for loop if you need to. Haskell, is a bit less forgiving.

  5. As Bruce Lee said by Z80a · · Score: 2

    Use only that which works, and take it from any place you can find it.

  6. "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 gl4ss · · Score: 2

      That implies that the majority of today's coders have no fucking idea how coding has progressed through the last few decades

      ..and you were unaware of this? how in the hell?

      --
      world was created 5 seconds before this post as it is.
    2. 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.
    3. Re:"Like"? by swillden · · Score: 2

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

      Procedures are procedures, period.

      Indeed they are. And purely functional programming languages don't have procedures.

      The grafting of functional programming constructs onto imperative languages is interesting and useful, but every programmer should spend some time learning to program in a purely functional style, even if they then go back to imperative languages for their everyday work. It opens up a whole new way of thinking about code.

      --
      Note to ACs: I usually delete AC replies without reading them. If you want to talk to me, log in.
  7. It's not that I want to brag I'm old... by gwolf · · Score: 3, Insightful

    But it seems that I will.

    Around ten years ago, I started writing a column for a magazine. My first article was precisely a way to use functional programming for "real" code, using a multi-paradigm language (Ruby).

    I didn't jump on the Functional bandwagon first time I saw it; it took me around ten years to understand and embrace what it can do. So we are talking about 20 years of hype. At least.

    I am far from proficiently thinking functionally, although I have used it for many interesting things. It is a cool, and very different, way to work. It can make many things faster and simpler, but if you completely bite the bullet and make it your dominant paradigm, it will kill your productivity (with many other things that are not best served by that paradigm.

    It has a clear spot under your programmer belt. But it should not be The Only Way to approach a program - unless you are Truly One with the Tao.

  8. I do to an extent by reanjr · · Score: 2

    While I wouldn't want to program in a pure functional, no side effect language, a good mix of differing paradigms seems to me to be the way to go. Java and .NET went overboard on the OOP, and it leads to these poor abstractions in many cases (I.e. AbstractFooProcessor), which are much better approached with some FPd

    Pure functional code is super easy to reason about, though, especially asynchronous code. OOP has its role, but oftentimes you find yourself on loose footing, with its focus on always changing state. This can be addressed with good practices, which leads you down class hiearchy hell. Throwing some FP in the mix gives you (mostly) the best of both worlds.

  9. 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.

    2. Re:It depends on the use by vtcodger · · Score: 2, Funny

      "The world's most popular programming language (Excel) is functional"

      Is that intended to be an argument in FAVOR of FP?

      --
      You can't see ANYTHING from a car, You've got to get out of the goddamned contraption and walk...Edward Abbey
  10. Wrong question by gweihir · · Score: 3, Insightful

    The right question would be "Do you understand functional programming?". And when you see about 99% of all "coders" having no clue, then you could ask the rest why they invested the time.

    --
    Most ACs are not even worth the keystrokes to insult them. Be generically insulted by this and ignored otherwise.
    1. Re:Wrong question by bzipitidoo · · Score: 2

      A more basic question: "Do you understand recursion?" Lot of programmers really struggle with recursion, and avoid it like the plague. A common mistake is thinking that exiting the function means exactly that, rather than exiting only the current invocation of the function.

      --
      Intellectual Property is a monopolistic, selfish, and defective concept. It is "tyranny over the mind of man"
  11. Re:My answer by ewibble · · Score: 3, Interesting

    yes,

    OK a bit more detail, there are advantage to not having state, or at least making the system deal with it it lead to some really elegant code.

    Just like most languages it has it limits, mainly input and output.

    I have used haskell and I think it has some really good concepts but is plagued by people using being to terse and cryptic, 1 character names for types are not good yes you can work out what it is doing but you shouldn't have to, and the use of random definable operator like '' makes it unreadable without a reference manual for beginners. A part of good code is being clear, being cleaver isn't usually as important as being understandable. At least the uses I have seen generally been quite cryptic.

    If the haskel community want haskel to popular they should make an better effort to make it more understandable.

  12. 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.)

    1. Re:What is functional programming? by mikaere · · Score: 2

      I'm a C# and BI developer I was paid to learn Clojure (a LISP) for a cloud-based contact centre platform project. I really liked it, but it did take me a while to get my head around the different patterns

      If you have a problem that can be solved using functional programming (e.g. operating on sets of data) then it can be a good choice. For example, I reckon it would be extremely useful in a business intelligence transformation layer.

      --
      It's good luck to be superstitious
  13. Drink the "kOOl-aid" by michael.karl.coleman · · Score: 2

    Not sure whether that was an intended pun or not, but I'm using it...

  14. I like functional aspects not functional languages by brian.stinar · · Score: 3, Informative

    I got my master's degree with this guy, and I had to take a Haskell course, or seminar, every semester. I was, and still am, pretty terrible at Haskell.

    However, what I attempted to learn helped my Python out a lot. Map and filter are two of my favorites, and the other functional paradigms are occasionally useful to me as an actually working, productive, programmer. I'm happy I was exposed to those concepts, since they tend to come in handy. Yes, everything is Turing complete, and you can accomplish the same things without functional programming, or without high level language, or without computers, but that doesn't mean they are all equally useful to solving the problem at hand.

    I recommend everyone become familiar with functional concepts in some way, if only to make them more well rounded. I don't advocate writing your next web application in Haskell though...

  15. Re:I like functions... by mrchaotica · · Score: 3, Insightful

    Yes, it means your functions aren't allowed to have side effects (i.e., all parameters are passed by value and the only result is the value returned to the caller).

    Personally, I like it because it's a good way to manage complexity -- kind of like the encapsulation of object-oriented programming, except applied to the verbs instead of the nouns.

    --

    "[Regarding the 'cloud,'] ownership was what made America different than Russia." -- Woz

  16. 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.

  17. It is great, just don't make a religion out of it by jma05 · · Score: 3, Interesting

    All programming paradigms have useful abstractions to offer. Eventually, they will all come together. Object orientation is great, until one overdoes it in design pattern hell. Likewise with functional programming. There are great many ideas in academic programming languages that will be made more accessible and integrated into mainstream programming languages. Functional programming is a dead end only in the sense SmallTalk was a dead end. People may not use SmallTalk much today, but its ideas live on in nearly every language we use today. Functional programming is here to stay. It won't replace imperative and object-oriented programming, but will add to them.

    First and foremost, programming languages are for people, not computers. So if regular programmers who form the bulk of the workforce can't grok them, the languages need to be fixed, not people. Haskell is too hard for most. But it has many wonderful ideas that can be distilled into simpler forms and adopted and integrated elsewhere. Python got list comprehensions from it and perhaps the indentation.

    C# is absorbing some features and Java is doing that less elegantly. Scala is a good balance and has already established itself. But people still find the type system complicated. So there are attempts to bring forth a simpler Scala - Kotlin, Ceylon etc.

    We all agree that things like compact syntax, first order functions, lambdas, streams, type inference etc that functional languages pioneered, belong in every language. We still haven't sorted out how to make more advanced type systems, provability, strict programming without side effects etc more approachable. We should not need to have this much trouble explaining what a monad is or isn't. We'll get there, eventually.

  18. 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.
    1. Re:I couldn't get past "how do you write a game"? by phantomfive · · Score: 2

      I would do it by making a function something like, newGameStateScreen() which is a function of the old screen, and the current state (maybe even the old state). That part is fine enough.

      Then I would cheat and optimize it to actually update in place. Conceptually it would still be functional, but every useful functional program ever written mutates state.

      But if you have FP, then you have repeatability. Given a particular game state, combined with a given input, you can know what the next game state will be, every time. It's testable, provable, and helps you make sure that every possibility is covered.

      --
      "First they came for the slanderers and i said nothing."
    2. Re:I couldn't get past "how do you write a game"? by jbolden · · Score: 2

      Functional reactive programming came out of the functional community. Assume you had an array of all the inputs the end user entered for a game that already happened. Then the engine can create an array of all the corresponding outputs. That's your engine. Now wrap the construction of those two arrays in a stateful monad (IO).

      This book ( https://www.amazon.com/Haskell... ) is out of date but it will teach the ideas well. You'll create a video game and a music player.

      In general though, no video games don't generally get written in functional languages they are too messy and stateful. Video game engines though can easily be written in functional languages.

    3. Re:I couldn't get past "how do you write a game"? by Dutch+Gun · · Score: 3, Insightful

      As a professional videogame programmer, I can assure you that I haven't heard functional programming discussed much at work or among other peers in the industry. Videogames are giant, data-intense state machines, with lots and lots of state to track and manage. My feeling is that it's really not a great fit for functional programming. Traditional object-oriented programming is *heavily* used (C++ is the defacto industry standard language), because that's a reasonable and proven way to encapsulate complex, independently-operating entities into well-behaved packages of data + code.

      It's the same reason that the industry doesn't extensively use unit testing for engines and game code (not broadly at least), which may surprise some programmers in other fields. The reason is simple: many game engine tasks can't be boiled down into simple algorithmic data transformations that can be checked and verified by a simple function. For instance, how would one write a unit test to ensure audio is playing correctly, or a graphic shader is working as intended, or a physics engine "looks" correct in realtime interactions? It's not really practical. Thus, videogames tend to rely on integration tests using QA team members to spot anomalies.

      In short, not every programming paradigm can be effectively applied to every problem. That's not to say you *couldn't* write a game purely in a functional language, of course. I just don't think you'd be working to FP strengths.

      --
      Irony: Agile development has too much intertia to be abandoned now.
  19. 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.

  20. Re:Functional programming is trendy hipster garbag by brantondaveperson · · Score: 3, Insightful

    Programming is about translating what you want a computer to do into a set of instructions that the computer understands that mean the same thing.

    That is half of what programming is, at most. The other half is, at least, making that set of instructions easily understandable by another human being. Your code will be read thousands more times than it is written, and readability is far more important than your statement suggests.

  21. Makes you think of data design more by yes-but-no · · Score: 2

    In my experience FP style (in python), makes me spend lot more time in the design phase. The emphasis is on data/data-structure more than the code/algorithm/operations [the spotlight of imperative languages]. You start thinking more about how your data gets transformed from input to output. I felt this way of separating data representation from the code/operation lead to more robust code; also much faster implementation phase. FP surely changes the way you think at a higher plane of the problem at hand.

  22. In small doses by DrXym · · Score: 2
    Anonymous functions / closures / lambdas are fine for small snippets of code, e.g. iterating loops, firing timers, success / fail handlers etc. When you start nesting them or chaining them together with promises or similar constructs, then things can get really hairy.

    Try writing sets of asynchronous Jasmine tests that use promises, lodash iterators, success callbacks and other things of that nature arrays and madness swiftly follows.

  23. Re:My answer by Rockoon · · Score: 3, Interesting

    1 character names for types are not good

    Says who?

    All localized variables and types in my programs have 1-character names, and its for multiple good reasons including that because you can see that something is only 1 character at a glance, that therefore you know for sure that it doesnt have much if any outer scope with that very same glance.

    --
    "His name was James Damore."
  24. Poorly understood? by fyngyrz · · Score: 3, Interesting

    If you're using poor coders to maintain very old code then perhaps the choice of programming style is not your biggest problem.

    You may have misunderstood the previous poster's use of "poor coder."

    I read it as "unfortunate coder", not "incompetent coder."

    I could certainly be wrong. Perhaps clarification will be forthcoming.

    --
    I've fallen off your lawn, and I can't get up.
  25. Fluid type manipulation with unions by fyngyrz · · Score: 2

    Would you consider unions in c a "means to circumvent the type system" as compared to a language with strong up-front typing?

    Unions are certainly a very powerful, useful, and concise tool for manipulating data across type boundaries. If you don't have them, in trying to accomplish similar tasks as those unions make easy, in many languages you're going to be a lot more verbose, and likely a lot less efficient, than if you do.

    I am assuming competence. Strong typing is a safety net. The need for such a thing varies with one's skill set. The fewer the participants, the more likely it is that the skill sets can be arranged to be similar. With larger teams, the need for safety nets almost always increases.

    --
    I've fallen off your lawn, and I can't get up.
  26. 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.
  27. structs and fundamental OO by fyngyrz · · Score: 3, Interesting

    Just having higher-order functions doesn't make a language a functional language any more than having structs makes C an object-oriented language.

    Structs do, however, make the critical aspects of an object oriented approach practical in c. They can carry data, function pointers, etc., and they can be passed around.

    I've been writing my c code like that since the 1980's. There are significant benefits.

    --
    I've fallen off your lawn, and I can't get up.
  28. cars cons crap by fyngyrz · · Score: 2

    ((((((((((((I hate lisp too))))))))))

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