Skip to content

Comment on Exotic List Monadsparent

Comments

Propagating "Nothing" is not inherent to the Maybe data type, it's just a convenient behavior to have.

nitpick about this particular example: is there another lawful implementation of Monad for Maybe? i can't think of any, apart from the trivial

  pure _  = Nothing
  _ >>= _ = Nothing
(eyeballing the lawfulness, but it'll all be `Nothing` so all the equalities should hold, trivially :D)

The trivial implementation isn't law abiding. This law doesn't hold (written in Kleisli form for simplicity)

    pure >=> f == f  (left identity)
There are no other monads for Maybe. First, any definition of pure must be Just as Nothing doesn't work because of left identity and parametricity prevents any other funny business. Now, by law we know
    pure a >>= f == f a
Thus, we must define
    Just a >>= f = f a
So the only variable is what (Nothing >>= f) does. For (f: A -> B) we must end up with a Maybe B. We don't have one to start and we can produce Maybe values only via Nothing and Just. So, either >>= is the standard definition or we have to do
    Nothing >>= f = Just (_: B)     -- we can achieve a B only via use of f, so
    Nothing >>= f = Just (f (_: A)) -- now we are stuck, there are no values of A
Thus, we must define
    pure a = Just a
    
    Just a >>= f  = f a
    Nothing >>= f = Nothing

yeah, and as others pointed out it fails right-identity as well. had a brain fart recapping the laws, though i think i got associativity right at least!

I don't think that holds for left identity:

    pure a >>= f ≡ f a

Exactly, and the right identity is also violated:

    m >>= pure ≡ m

ahh right! serves me right, i should've spent more than 10 secs checking

Everyone experiences this in Haskell, where you make some statement online and then someone tells you some way in which it’s incorrect.

I’m sure most real-world Haskell programs are “incorrect” in some way.

AboutSource Built by g1lg1l

Hackerly is an independent reader for Hacker News, built on the public HN API. Not affiliated with Y Combinator.