6 ms·
> I get how Maybe types can be useful for parsing something or doing IO but once you get your Maybe value, wouldn't be the first action to unwrap it? If it is N
by bradrn 5y ago
> I get how Maybe types can be useful for parsing something or doing IO but once you get your Maybe value, wouldn't be the first action to unwrap it? If it is Nothing you can either provide a default value or just stop right there. I don't see the sense of dragging the Nothing further …
I agree that this technique works well — as long as you need to use only one Maybe at a time. As soon as you want to combine multiple computations, each of which returns a Maybe, this quickly becomes horrible and cumbersome:
case parseNumber str0 of
Nothing -> Left "parse error"
Just str1 ->
case parseChar '=' str1 of
Nothing -> Left "parse error"
Just str2 ->
case parseNumber str2 of
Nothing -> Left "parse error"
Just str3 -> …
Monads are, quite simply, a way of abstracting this repeated structure.
And of course, then you get some data structures which can’t be unwrapped at all. The standard example is Promises as seen in e.g. JavaScript, but there are others.
- jerf 5y ago"Monads are, quite simply, a way of abstracting this repeated structure." More precisely, the monad interface allows abstracting this particular repeated structure in much the same way an iterator allows abstracting the repeated process of "get the next thing", but monad does not exist for Maybe just as iterators do not exist for arrays. It's easy to make the mistake of focusing on the Maybe portion of that repeated code snippet, but the value of the monad interface in that code snippet is everything other than the Maybe portion, that pattern of descending into a computation over and over again with a closure, that fits into a number of data structures and an even larger number of data structures that can be coerced into fitting into that pattern without much effort. Moreover, Maybe is a bad way of understanding the monad interface and pattern because it does not fully use the monad interface. It doesn't take advantage of the way the Maybe value is passed through to thread any additional values through. While a valid example of a monad interface usage, it is also a degenerate one that makes for a difficult lens to understand the interface.
- Twisol 5y agoI'm a big fan of trees and promises as more complete representatives of monads. Trees give us free monads, where `join` grafts the child tree contained in a leaf onto the parent tree; and promises are a bit more viscerally monadic, as you really can't get at the value in a promise, since it probably isn't even there yet.
- bradrn 5y agoToo true. I used Maybe as an example only because it had already been mentioned in the parent comment, but I agree that it doesn’t get across how incredibly useful monads are.