Over at the Edx Haskell course, Erik Meijer repeatedly states that using the Maybe
type for failed computations is not something one should do; instead, one should use the empty list for that.
My understanding is that the Maybe
type is a good thing and that we should use it. However, it seems that a list can model everything a Maybe
can model and more... So why do we need the Maybe
type at all?
Get Programming with HaskellYou can't return an empty list, because an empty list is the same type as the elements of the list.
The maybe function takes a default value, a function, and a Maybe value. If the Maybe value is Nothing , the function returns the default value. Otherwise, it applies the function to the value inside the Just and returns the result.
The sequence (n:ns) is a shorthand for head - tail. Quite literally, the first value, the head, is called n and the remained are the other, potentially plural, n s, which is why it is called ns . Haskell has pattern matching.
However it seems that a list can model everything a Maybe can model and more
The "and more" is an excellent reason to use Maybe
. As a consumer of a list, you need to be able to handle zero, one or multiple values. As a consumer of a Maybe
, you only need to be able to handle zero or one values. So in cases where multiple values don't make sense, it is much better to use Maybe
so that you know statically that you won't get nonsensical values.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With