Created
March 11, 2013 13:37
-
-
Save nathanic/5134282 to your computer and use it in GitHub Desktop.
Educational Reimplementation of the Maybe Monad
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- | Re-implementing the Maybe monad from memory, to make sure I | |
-- understand it. | |
module MyMaybe where | |
import Prelude hiding (Maybe, Just, Nothing) | |
data MyMaybe a = MyNothing | MyJust a | |
deriving (Eq, Show) | |
instance Monad MyMaybe where | |
MyNothing >>= f = MyNothing· | |
MyJust v >>= f = f v | |
return x = MyJust x | |
instance Functor MyMaybe where | |
fmap f MyNothing = MyNothing | |
fmap f (MyJust x) = MyJust $ f x | |
{- | |
*MyMaybe> MyJust 5 >>= \x -> return $ x * 2 | |
MyJust 10 | |
it :: MyMaybe Integer | |
*MyMaybe> do { x <- MyJust 5; return $ x * 2 } | |
MyJust 10 | |
*MyMaybe> do { x <- MyNothing; return $ x * 2 } | |
MyNothing | |
*MyMaybe> (*2) `fmap` (MyJust 5) | |
MyJust 10 | |
-} | |
~ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment