The way I understand monads: some data structure plus 2 functions, "return" and "join":
- "return": wraps something with the data structure. (no relation with the return keyword you are used to in most languages)
- "join": joins 2 layers of the _same_ data structures into one.
And that's it. It's just that simple what a monad is: in java it would be an interface with just these two methods.
Examples:
- "return" for List: takes a value and returns a List containing just that value.
- "return" for Maybe: takes a value and returns Maybe value.
- "join" for List: takes a List of Lists and returns a flattened List (2 outer layers joined).
- "join" for Maybe: takes Maybe Maybe value and returns Maybe value.
I think what makes these functional programming concepts hard to grasp most of the times is that communicating the boundaries of abstract concepts is hard in general, even if the concept itself is really simple, like a monad can be for a programmer.
As for why monads are useful, the explanations you can find online give a lot of examples. Just think of all the times you may have used flatmap for arrays: that's just map followed by the "join" for arrays, which is sometimes called flatten. The other operators you see used in haskell, like "bind" (>>=), can be derived from "join" and vice versa and are just conveniences to write code with less noise, like flatmap is.
Recap: monad is the name of the concept for things that have a "join" and a "return" functions defined. Basically "join" is the distilled concept of what a monad is.
(edit: formatting)
Then, try store your programs state by passing it as a function argument to every function so it stays available for the lifetime of the program (no mutable state? This is basically what happens)
After realizing what a pain this is and wishing for boilerplate, look at the State monad. This is what did it for me :)
I'm honestly not even sure what function composition is, or why you would compose two functions instead of just explicitly making a new function that calls the two original ones.
The second one makes more sense because of the rumored bug-freeness of side effect free apps, but it seems like for that too, you'd need to understand a lot more than just monads.
Or in javascript:
function f(x) { return x + 1 }
function g(x) { return x + 2 }
f(g(1)) === 4
In functional languages like Haskell function composition is made easy, because functions can be partially applied. Partial application means that given a function that takes two arguments, I can call it with one argument and it will return a function that takes one argument which returns the result. Whereas in languages like javascript it is difficult because functions can have different numbers of arguments and there's no way to partially apply them or flip their arguments, so it is difficult to chain functions together. And because javascript functions aren't pure, they may not have any result which can be composed with other functions. In a functional language, functions are more like the functions in math. In most non-functional languages, functions are more like a procedure of commands. For example, the javascript function logMe(x) { console.log(x) } doesn't return anything. So it can't be composed functionally, and is not like a "real" function.
When we want to "compose" two functions, there's f(x){return a(b(x))}.
It doesn't matter if the signatures are different, you don't need any nice logical idea of composition, you just explicitly build the new function that does what you want.
I would say that is a lot easier than real composition, because real composition requires you first learn to see and think in terms of patterns you would want to compose in the first place.
Also, function chaining doesn't use intermediate variables. Named variables are like free documentation. With composition you have to actually remember what you're doing. Making everything explicit makes it easier to comment what's happening.
Regular programming is to math as cooking is to chemistry. Functional brings the math back to programming. Math is useful but also hard.
In OOP, more often you're doing the equivalent of:
if crinkle(a(b(x,68), modes.FOO).bar.baz(9)): x = foo() else: x = wipe(7).bar()
And I think it's a lot nicer to just spell it out with meaningful variable names, instead of trying to compose it like an equation.
let batter = mix(water, flour)
let saltedBatter = add(salt, batter)
let risenSaltedBatter = letToRise(saltedBatter)
let bread = bake(batter)
on the other hand: let bread = bake(letToRise(add(salt, mix(water, flour)))
The first example leads to awkward names and useless variables. The second example feels cleaner to me. Interesting that you take cooking as an example: recipes usually don't name most of the intermediate steps, they describe the actions you take and the ingredients you use. Most recipes also use composition a lot. You start with your actions/functions (cut, cook, bake, dice, etc) and you do a recipe out of them. You don't create new "functions" (actions) specifically for each recipe.You have standard functions like bake and boil, and they don't tell you to use clean utensils or how to turn the stove on, because an cooking is basically just a few dozen standard functions, end condition rules, etc.
If you think of them as programs, the composition they use isn't the same as functional languages, because the individual steps are unstructured and there's no generalized abstract pattern defining what a RecipeStep is or what composing two of them means.
You wouldn't say add(flour(add(salt,empty))), you would say "add flour, salt, water, and yeast".
"add" can take either an ingredient or a list, and it's pretty encapsulated, since it dynamically selects a way to measure the ingredient based on what it is, what utensils you have, etc.
It could trigger dozens of unrelated code paths based on state, and probably includes error recovery.
Functional might be nice for implementing the internals of that add() function, but in OOP the idea seems to be that it's a pretty minor detail, since add() is only written once and rarely changed, but used millions and millions of times all over the world for a decade.
Usually when people talk about "the beauty of functional" I get the impression that they're not really doing a whole lot of "One really smart function that knows exactly what to do" level abstraction.
It seems like they'd literally be composing together their own variations of what "add" is, as needed from the raw findMeasuringStrategy and checkPantry functions instead.
That second example tells the reader that it is doing, which may or may not be what it was supposed to be doing.
As a maintainer, I prefer knowing that:
(add(salt, mix(water, flour))
is supposed to result in a salted batter, which the first code block tells me but the second one does not.For write-only code, sure, that's great.
It's irrelevant when I am tracking down a bug - the label 'saltedBatter' tells me what that intermediate result is supposed to be.
If, when debugging, I find that `add(salt, batter)` results in something else[1], using your convention it is literally impossible to tell that the value is supposed to be `saltedBatter`.
There is literally no way to tell if the intermediate values are correct. Maybe each caller in the composition chain can throw an Exception?
The point is, the variable names are helpful.
> but only the first and last step have a name because the intermediate steps are just that.
That describes the entire program :-)
In all seriousness though, it's because you intend to describe steps in the process that throwing away all labels for the intermediate steps makes sense.
You're describing verbs. We don't need to know the in-between verbs for a verb. When you call `driveTo()`, it is not necessary to know all the verbs involved in that action, it is enough to know that it will attempt a certain action.
Verbs answers the "what we are doing" questions.
Variable names answer the "Why we are doing it" questions - `saltedBatter = foo (bar(), baz);` tells the reader why foo is being called.
We don't even need to know the steps involved or even what the other variables (used as parameters) should be. Assigning the result of a function to a variable ensures that the maintainer knows if that variable ever holds the wrong value.
I think where a lot of this value (variable-names) is lost is in enterprise development - the names are never helpful, they're just a differently-cased version of the type. Like these gems I see daily:
SomeClass someClass = foo();
List<OtherClass> otherClassList = bar();
....
return baz(someClass, otherClassList);
So, yeah, I see your point if all you ever see is enterprise-grade naming conventions. OTOH, if those above two lines were written as: SomeClass needle = foo();
List<OtherClass> haystack = bar();
...
return baz(needle, haystack);
you, as the maintainer, know exactly what that last line is supposed to do, and if it isn't doing that, then you know it's a bug.Compare with this:
return (foo(), bar());
Or, if you wanted descriptive function names: return (calculateResult(), userSubmittedList());
Brevity is not a virtue in programming languages and/or programs. It's probably why Haskell is still not even a rounding error as far as popularity goes.[1] Maybe `doubleSaltedBatter`, in case an upstack caller used `saltedWater` in place of `water`, or perhaps `pepperedBatter` in case a caller switched out the salt for pepper.
Real world Haskell code isn't the codegolf you are implying.
In fact, I think real world Haskell devs overcorrect and make code too verbose.
Also, "brevity is not a virtue in programming languages" is something I disagree with.
Walls of verbose code are just so damn mentally taxing. Especially hen you finish reading and saybto yourself "all that code just to do X?".
So is working with an edifice of unprincipled ad-hoc abstractions, but many seem to prefer pushing that debt on tomorrow them or others.
I'm not clear why the next function in the pipeline would need to know about the error rather than the caller, but that happens with promise chains too
Exceptions usually aren't typechecked.
All I know is they contain values and you can pass them functions, and somehow by doing this you can write fully pure programs with supposedly fewer bugs, and Haskell programmers seem to not understand why this is hard.
I have an article i'm about to publish that will have a lot more real world examples... hopefully it can bridge the gap.
It'll also have exercises, which are honestly the most important part of understanding.
It explicitly tries to answer the question: "I’m a C# programmer with no “functional programming” background whatsoever. What is this “monad” thing I keep hearing about, and what use is it to me?"
What I did was I gave up and no longer click those articles.