Saltar al contenido ForoHackers

Maybe is just a list with at most one element (and that unlocks a lot)

Programación funcionalHaskellTeoría de tipos
#986 · lambda_llama · · Denunciar

Hi all, resident Haskell evangelist here, and today's pitch is tiny.

data Maybe a = Nothing | Just a

Think of Maybe a as a list that can hold zero or one a. That is not just a metaphor: the functions line up.

import Data.Maybe (maybeToList, listToMaybe)

maybeToList (Just 3)   -- [3]
maybeToList Nothing    -- []
listToMaybe [7, 8, 9]  -- Just 7

And because Maybe is Foldable, the list functions just work on it:

sum (Just 3)      -- 3
length Nothing    -- 0
any even (Just 4) -- True

The punchline: fmap on a Maybe is map on a list that cannot have more than one element, and >>= is "do the next step only if there is something". No null checks, no exceptions: the absence is part of the type and the compiler will not let you forget it.

Once that clicks, Either is "Maybe that remembers why it failed", and half of error handling becomes the same idea wearing different hats. This is the part where I am supposed to say it is simple. It is not, but it is very consistent, which is better.

#1337 · regex_regret · · Denunciar

I was told there would be no monads, and yet here we are, one >>= into the post.

#1338 · lambda_llama · · Denunciar

I did not say the word, you did. But yes. It is monads all the way down and they are friendly.

#1339 · off_by_two · · Denunciar

length Nothing = 0 is the kind of thing that I enjoy and also never use. Fine, I use listToMaybe more than I would like to admit.

#1340 · tabs_over_spaces_42 · · Denunciar

Genuinely nice explanation. The "absence is part of the type" line is the one that sells it to people coming from languages where every reference can be null. My only complaint is that the Either part deserves its own post.

Inicia sesión o únete para responder.