Earlier quoted context omitted.
> Barely typed languages like C made rigorously typed languages like C++ and Java seem appealing. The boilerplatiness of those languages made duck typing seem appealing. Eh, I consider Java to be barely typed too. If you have a variable of type Foo, the type system doesn't even guarantee that you have a Foo in there (it might be null). The whole point of a type system, in my mind, is to guarantee that I have that Foo…
I know dozens of people who tried understanding Promises and all of them succeeded. I know dozens of people who tried to understand monads (including myself) and maybe 3 of them succeeded (I do not consider myself one of them).
Mathematicians and Haskelites tend to explain things by giving their definition. (Imaging a Haskelite explaining how to write "hello world" in C: First you need a "main" function. A function is a process or a relation that associates each element x of a set X, the domain of the function, to a single element y of another set Y (possibly the same set), the codomain of the function. etc etc )
But most other programmers prefer to understand things by understanding the problem they solve. It is quite obvious what problems Promises solve, but in the context of JavaScript, monads does not solve any real world problem. That makes them hard to grasp for a programmer, even though the concept is simple.
Monads are a particular pattern for method chaining or function composition.
Here is an example of some JavaScript code which use regular method chaining:
[1,2,3].map(a => a + 1).filter(b => b != 3)
This code results in the array [2,4].Similar code following the monad pattern would look like this:
[1,2,3].flatMap(a => [a + 1]).flatMap(b => b != 3 ? [b] : [])
And the result is the same. But obviously the monadic version is more convoluted and harder to read. But if there was some syntactic sugar which covered the boilerplate, then the monadic version might be bearable!The "power" of the monadic pattern is that the operations can be chained or nested in a more flexible way. For example here the operations are nested, but the result is the same:
[1,2,3].flatMap(a => [a + 1].flatMap(b => b != 3 ? [b] : []))
This does have some nice properties, since operations can be chained or nested together to composites which have the same type as a single operation. The question is if the benefit outweighs the cost in code complexity.The monad pattern is purely concerned about how operations are chained together structurally, it is not about what they does or what types are involved. In this example the type is Array, but it could be any parameterized type.
Monads can be used anywhere a sequence of operations is stringed together. (But that doesn't mean you would want to.)