(no title)
spellcard199 | 4 years ago
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)
No comments yet.