r/functionalprogramming • u/homological_owl • Aug 26 '24
Question Actual benefits of FP
Hi! My question is supposed to be basic and a bit naive as well as simple.
What are actual benefits of functional programming? And especially of pure functional programming languages.
Someone might say "no side effects". But is that actually an issue? In haskell we have monads to "emulate" side effects, because we need them, not to mention state monads, which are just of imperative style.
Others might mention "immutability," which can indeed be useful, but it’s often better to control it more carefully. Haskell has lenses to model a simple imperative design of "updating state by field." But why do we need that? Isn’t it better to use a language with both variables and constants rather than one with just constants?
Etc.
There are lots of things someone could say me back. Maybe you will. I would really like to discuss it.
37
u/SupportDangerous8207 Aug 26 '24 edited Aug 26 '24
If I can take a crack at it
The largest benefit I have seen personally in my work life is this
I think it’s largely about abstracting control flow away from you
In imperative code it is explicit that the code runs instruction by instruction
In functional code it is left to the exact implementation of your map/ monad / reduce to figure out the details
This means for example you can have lazy evaluation of things like maps to save memory. Python uses this a lot. This also means you can just replace ur regular map with a parallel map which is very useful for multithreading in languages like Java because a parallel map and a normal map are equivalent whereas there is no parallel for loops sure you can parellelise a loop or replace it with an iterator but it is not a drop in replacement like a parallel map is.
Monads are also good for this as again you can lazily evaluate them and again there is nothing stopping you from using them for multithreading or async stuff because at the time that the monad is unwrapped/ executed you know all of the functions that will be composed and can execute them using whatever model you like. In fact I have seen some code like this where one uses a monad to “queue” some operations and they execute async in the background whenever there is time. I have also seen monads that execute their functions in multiple separate threads because they were big and expensive calls and so on and so on. Again you can easily build this in imperative languages but a monad is a drop in replacement where you can swap simple control flow with more complex control flow without burdening the developer using it.
The combination of strong type safety that is generally preferred in fp + abstracting away as much control flow as possible from the programmer just lets you do neat stuff with said control flow as long as you don’t break those strong promises
I guess what I’m trying to say is
Imperative languages already encourage you to not be overly specific in the interfaces and variables you require
I really like that fp goes one step further and encourages you to also be as non specific in which exact control flow you require
Oh also for a lot of common stuff fp syntax is simply more concise than for example oop
Like currying vs constructing some object to hold your function and its internal variables
13
u/Inconstant_Moo Aug 27 '24
It has only one design pattern: The Pipeline. We take some data, we push it through a pure function, we get a result out which we can then feed into another pure function ...
This is a very pleasant way to work. Bugs tend to be shallow and easy to find. And then it opens up possibilities for the rest of the language. In terms of power, if you know that all your functions are pure functions then they can all safely be passed to appropriate higher-order functions, and the whole language and its libraries can be built around that fact. Then there are lots of possibilities for tooling: refactoring some of your code out to a separate function is really easy when your functions are referentially transparent. Unit testing is easy when there's no state to mock. Live-coding and REPL-oriented development, similarly.
(The ease of using FP is often obscured by the fact that people use it to do difficult things. Haskell is frankly scary but as I don't need any of its powers I can stay a safe distance away from it and whatever the heck this is. Similarly Lisp, while at least comprehensible, is unfriendly and confusing, especially if you use macros, but if you don't need macros then you could use something other than Lisp. And so FP has historically often been associated with languages or language families which are intrinsically hard for reasons other than being FP.)
12
u/a3th3rus Aug 26 '24 edited Aug 26 '24
Same thing can be said about static typing. Why do we need static typing? Because it can mitigate a whole kind of error (type mismatch) even if we are dumb. Why do we need universal immutability? Because it does not allow another kind of error (accessing corrupted data) to exist.
After years of coding in Java, Ruby, and Elixir, I found that Elixir code is the easiest to read and to reason about, even if that piece of code is written by someone I don't know, thanks to immutability. In Elixir, when you look at the implementation of a function, you know that each and every piece of data it creates never changes, even if it gets passed around many times. Because of that, I don't need to dig deeper into other functions' implementation to understand the current function.
8
u/Delta-9- Aug 27 '24
Probably the one benefit that everyone can agree on is this: it teaches you a new way to approach problems and design solutions, which makes you a better programmer.
As for the direct benefits of the style, honestly... FP languages are as diverse as IP and OOP languages, so I think it's not really easy to nail down "this is why FP good" even by looking at common features. Take immutability, for example: it's not really required by FP, there's nothing to stop an FP language from having mutable data structures, immutability just makes functional patterns easier to understand and implement. I can't remember the name right now, but there's at least one FP language where collection types pretend to be immutable for the programmer but silently mutate under the hood when doing so is safe and there's a provable performance benefit.
It would be easier to talk about the benefits of specific languages or features, particularly with the understanding that some features (like immutability) are not unique to FP. You can get many of the purported benefits of FP in languages like Python or JS just by using FP patterns in what are, ostensibly, OOP languages.
But enough beating around the bush, what are features common to FP languages that are beneficial to have?
|,|>,<<, or something else that means "feed left hand output into right hand input."4
u/recursion_is_love Aug 27 '24 edited Aug 27 '24
When you have solid theory on something, apply it to a task will be more easy (to model and test) and with higher confident that it do what it should do.
We have acquired lots of knowledge on functional programming from it started (lambda calculus, type theory, denotational semantic ...) for a very long time.
That is, this is from my point of view of an engineer, we use math and logic because we know how to analyze and adapt the known theory to solve the problem.
If you only focus on capability to computing (Turing complete), any computation method will just work fine. But how easy can you model such process to make it extensible?
4
u/catbrane Aug 27 '24
I had an interesting experience back in the 80s, modifying a fairly large Miranda (the language Haskell is most based on) program (a screen editor, c. 10,000 lines of code), written by someone else, to use monadic IO.
I was expecting it to take a while. A 10k line C program isn't too hard to understand, but 10k lines of Haskell is a lot, and getting a good enough understanding to be able to make a large change seemed intimidating.
In the event, it was just a couple of days. Purity made it very simple to split the code into separate pieces, and I just needed a little monadic glue to join them up again. It was very striking.
You can certainly overuse monads, and a program written with monads everywhere wouldn't be very different from the same program in an imperative language. But you can overuse almost any language feature! If you only use them where they are really necessary, your programs are still going to be far easier to maintain than more traditional imperative code.
4
u/Serpent7776 Aug 27 '24
One thing that no-one mentioned yet is composability. If I have a function
foperating on some typet, I can trivially apply that function to a list ofts usingmap f. This generalizes further withfmap f. Imperative programming didn't traditionally have this, because it focused on statements heavily. I'd need to write for loop and invoke the function directly. This difference blurs nowadays though, because FP aspects likemapcreeped into imperative languages.2
u/sagittarius_ack Aug 26 '24
In pure functional programming larger computations (functions) are expressed in terms of smaller computations (functions), in such a way that you only need to care about the inputs and outputs of the computations (functions). You don't need to worry about any kind of (hidden) side-effects that a computation (function) might perform. In other words, a computation (function) is fully characterized by the way inputs are mapped to outputs (or outputs are computed from inputs).
The biggest benefit of this style (paradigm) of programming is that it is easier to reason about computation. Perhaps it is more accurate to say that in programming styles that allow mutation it is hard to reason about computation, precisely because it is hard to reason about state changes.
17
u/[deleted] Aug 26 '24
I feel its like guard rails. It prevents me from doing stupid stuff. I like when doing stupid stuff is not an option. The tradeoff is that its easy to make complicated stuff, so you need to watch out for that.
There's a lot of that that it's readability and aesthetic. Looking at my project feels like a satisfying thing to do. Revisiting old code is not as gruelling. Changing something in a class does not make me terrified that I might be unkowingly breaking something in a completely unrelated part of the system.
6
u/[deleted] Aug 26 '24
for me it has a lot more to do with beauty and readability than anything else
3
u/[deleted] Aug 27 '24
FP is a broad and overloaded term. But in a nutshell FP code is USUALLY more safe, correct and should not cause / have less runtime issues. This has a huge caveat, and is assuming you actually use a typed language with a compiler, like ocaml.
That said benefits are also gained when doing FP in a dynamic language like javascript.
3
u/[deleted] Aug 27 '24
I was asking myself like you before.
Now I have found the answer.
3
u/Organic-Permission55 Aug 27 '24
Personally it is very useful for me for building parsers. Could probably also be done in other languages. But in FP languages using pattern matching "it just feels right" and actually makes code more readable.
2
u/stellar-wave-picnic Aug 27 '24 edited Aug 27 '24
most important thing for me is summed up in two words: referential transparency. I feel anxious when working without it.
2
u/reteo Aug 27 '24 edited Aug 27 '24
I 'm still working on learning more of functional programming, but I do recognize the benefits of two of the core rules to functional programming that I make use of as much as possible.
Using Pure Functions
The pure function is the idea that the parameters are the only input a function gets, and the return value is the only output available. There are no modifications of variables outside that function (which is what no side effects means). This means that a function will either work correctly, or it will not, and the only thing you need to do to test this is put in the expected inputs, and look at the return value to make sure it's correct.
This can have an incredible benefit in terms of debugging problems. After all, if a function did not perform a process correctly, it's obvious, because its return value is the only place the wrong answer will be seen. If a function can modify an external variable, and it's not the only one, then you will have to spend a lot of time trying to find out which function was responsible for making the higher-scope variable change the wrong way. If the only output is the return value, then it's easy to find out which function got it wrong. In the same vein, if the function does not look for data outside of itself, then there's no risk that a change somewhere else will cause the function to produce the wrong output. Again, anything causing the function to fail will be internal to the function itself.
Using Immutable Variables
In the same vein, most of the time, variables and structures are either going to be throwaway (a stepping stone in a longer chain of assignments) or constant. If they're going to be this way, it helps to keep them immutable, or unable to be changed after being created and assigned.
For variables, this can ensure that it's not possible to accidentally change the wrong variable, since it won't allow changes after its assignment. This can cut down on logic errors that can result from changing a variable that shouldn't be changed.
For data structures, this can have a more significant advantage, because there is no need for inserting, deleting, or internally sorting data, all you need is to assign the data and search it, which reduces the complexity of the compiled code or the runtime of the interpreted code. This won't matter much with smaller structures, but the benefits scale with the size of the structure.
2
u/dustingetz Aug 26 '24
FP is what makes this possible: https://github.com/hyperfiddle/electric
1
u/NumbaBenumba Sep 04 '24 edited Sep 04 '24
Disclaimer: in production I've done mostly Scala, so some of this lingo might be Scala-biased some things might have different names in Haskell. However, from my hobby-level exposure to Haskell, I've found there's a lot of equivalence.
IME, the biggest benefits I've seen are referential transparency and error handling. Thanks to referential transparency, you can pretty much move chunks of code around and things will just work. Go refactor to your heart's content. The hard "I wanna justify this to the leadership people" benefit is faster iteration.
I also gotta say a lot of the constructs offered by monadic systems just make stuff like retrying on an error a lot easier than it'd be in an imperative language, especially if there's concurrency involved... The amount of code it takes with imperative languages to accomplish the same is insane. Less code also helps with faster iteration.
edit: I can't believe I forgot my every day bread and butter - algebraic data types. I know it's not exclusive to FP languages, but to my understanding the concept originates from FP. The hard benefit of this is how much easier it makes making illegal states unrepresentable, which means fewer unexpected logic errors.
0
u/[deleted] Aug 27 '24
[deleted] — view deleted comment