Skip to content

Instantly share code, notes, and snippets.

@ebresafegaga
Created November 17, 2020 02:53
Show Gist options
  • Save ebresafegaga/da96e8bd60890fa615cbb885fe39da7b to your computer and use it in GitHub Desktop.
Save ebresafegaga/da96e8bd60890fa615cbb885fe39da7b to your computer and use it in GitHub Desktop.
Monads for free!
module Free where
data Term f a = Pure a
| Impure (f (Term f a))
instance Functor f => Functor (Term f) where
fmap f (Pure a) = Pure (f a)
fmap f (Impure g) = Impure (fmap (fmap f) g)
instance Functor f => Applicative (Term f) where
pure = Pure
ff <*> Pure a = fmap (\f -> f a) ff
Pure f <*> Impure g = Impure (fmap (fmap f) g)
Impure ff <*> g = Impure (fmap (<*>g) ff)
instance Functor f => Monad (Term f) where
return = pure
Pure a >>= f = f a
Impure fa >>= f = Impure (fmap (>>=f) fa)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment