Hacker News new | ask | show | jobs
by IndexPointer 1736 days ago
Yeah, it's very confusing.

Array is a monad. Then what's the function that takes an array and returns another? Is it map? That can't be because map takes two parameters, not one: the array and a function that it will apply to every element. Something is missing in the explanation.

And why is Option a monad? What's the associative function that takes two options and returns another Option?

1 comments

Leaving the confusing article aside.

Practically, the additional function that monads support is usually called bind and looks like: Array a -> (a -> Array b) -> Array b

This is different from map which is: Array a -> (a -> b) -> Array b

Notice how in map, your function returns a value that isn't lifted in the monad. The bottom one is a functor, the top one is a monad. Functors let you visit an array at every element. Monads let you visit an array and produce a new array each time and they internally decide how they will recombine those values.

This is a bit silly for Array, you just concatenate the outputs. But is more interesting for Option.

map for Option looks like: Option a -> (a -> b) -> Option b

It says "If there's anything in my Option, apply this function to it, otherwise there's still nothing there"

bind for Option looks like: Option a -> (a -> Option b) -> Option b

It says "If there's anything in my Option, run this computation. This computation can also return an option". In this sense, it lets you string together computations that each produce optional values. The whole computation will fail if any part fails. Something that is very useful!

Thanks for the explanation! The Option example makes perfect sense.