Skip to content

Instantly share code, notes, and snippets.

@takeouchida
Created November 11, 2012 13:51
Show Gist options
  • Save takeouchida/4054946 to your computer and use it in GitHub Desktop.
Save takeouchida/4054946 to your computer and use it in GitHub Desktop.
A free monad example: converting a kind of functor instance to monad
module Main where
import Control.Monad.Free
data Option a = Some a | None
deriving Show
instance Functor Option where
fmap f (Some a) = Some (f a)
fmap f None = None
type OptionM = Free Option
some :: a -> OptionM a
some = return
none :: OptionM a
none = liftF None
twiceIfEven :: Int -> OptionM Int
twiceIfEven n
| even n = some (2 * n)
| otherwise = none
main :: IO ()
main = do
print $ map (\i -> some i >>= twiceIfEven) [0..9]
print $ none >>= twiceIfEven
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment