Skip to content

Instantly share code, notes, and snippets.

@kseo
Created February 12, 2016 05:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kseo/8854207e08f6dba35a62 to your computer and use it in GitHub Desktop.
Save kseo/8854207e08f6dba35a62 to your computer and use it in GitHub Desktop.
Monads are Trees with Grafting
-- http://blog.sigfpe.com/2010/01/monads-are-trees-with-grafting.html
import Control.Applicative
import Control.Monad
data Tree a = Fork (Tree a) (Tree a) | Leaf a | Nil deriving Show
tree1 = Fork (Fork (Leaf 2) Nil) (Fork (Leaf 2) (Leaf 3))
instance Functor Tree where
fmap = liftM
instance Applicative Tree where
pure = return
(<*>) = ap
instance Monad Tree where
return a = Leaf a
Nil >>= f = Nil
Leaf a >>= f = f a
Fork u v >>= f = Fork (u >>= f) (v >>= f)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment