Skip to content

Instantly share code, notes, and snippets.

@blippy
Created October 14, 2015 12:20
Show Gist options
  • Save blippy/23ffd1d9aff473c14d5b to your computer and use it in GitHub Desktop.
Save blippy/23ffd1d9aff473c14d5b to your computer and use it in GitHub Desktop.
Re-implementation of Haskell's Maybe monad
-- Maybe Just Nothing
data Smurf a = Foo a | Bar deriving (Eq, Ord, Show)
-- fmap :: Functor f => (a -> b) -> f a -> f b
instance Functor Smurf where
fmap f (Foo x) = Foo (f x)
fmap f Bar = Bar
-- fmap (+ 2) (Foo 10) => Foo 12
-- fmap (+ 2) Bar => Bar
-- (<*>) :: Applicative f => f (a -> b) -> f a -> f b
instance Applicative Smurf where
pure = Foo
(Foo f) <*> (Foo x) = Foo (f x)
_ <*> _ = Bar
-- Foo (+ 2) <*> (Foo 4) => Foo 6
-- Foo (+2) <*> Bar => Bar
-- (>>=) :: Monad m => m a -> (a -> m b) -> m b
instance Monad Smurf where
return x = Foo x
Bar >>= _ = Bar
(Foo x) >>= f = f x
-- (Foo 2) >>= (\x -> Foo (x+1)) => Foo 3
-- Bonus:
-- (*) <$> (Foo 3) <*> (Foo 4) => Foo 12
fromFoo:: Smurf a -> a
fromFoo (Foo x) = x
fromFoo Bar = error "Beats me"
-- fromFoo (Foo 12) => 12
-- fromFoo Bar => *** Exception: Beats me
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment