by uryga · 5y ago · 0 comments
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) 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 pure a >>= f ≡ f a m >>= pure ≡ mI’m sure most real-world Haskell programs are “incorrect” in some way.