Skip to content

Instantly share code, notes, and snippets.

@dtchepak
Created November 11, 2013 04:44
Show Gist options
  • Save dtchepak/7407995 to your computer and use it in GitHub Desktop.
Save dtchepak/7407995 to your computer and use it in GitHub Desktop.
{-# LANGUAGE DeriveFunctor #-}
import Control.Monad.Free
--data Free f a = Pure a | Free (f (Free f a))
--instance Functor f => Monad (Free f) where
-- return = Pure
-- (Pure a) >>= f = f a
-- (Free fr) >>= f = Free (fmap (>>= f) fr)
--
--liftF :: Functor f => f a -> Free f a
--liftF = Free . fmap Pure
--
data Terminal a =
WriteLine String a
| ReadLine (String -> a)
deriving (Functor)
writeLine :: String -> Free Terminal ()
writeLine s = liftF $ WriteLine s ()
readLine :: Free Terminal String
readLine = liftF $ ReadLine id
helloWorld :: Free Terminal ()
helloWorld = do
writeLine "Hi, what's your name?"
name <- readLine
writeLine $ "Hello " ++ name
interpretIO :: Free Terminal a -> IO a
interpretIO (Free (WriteLine s a)) = putStrLn s >> interpretIO a
interpretIO (Free (ReadLine f)) = getLine >>= interpretIO . f
interpretIO (Pure a) = return a
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment