Skip to content

Instantly share code, notes, and snippets.

@nathanic
Created March 11, 2013 13:37
Show Gist options
  • Save nathanic/5134282 to your computer and use it in GitHub Desktop.
Save nathanic/5134282 to your computer and use it in GitHub Desktop.
Educational Reimplementation of the Maybe Monad
-- | 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