Skip to content

Instantly share code, notes, and snippets.

@Porges
Created May 4, 2017 07:05
Show Gist options
  • Save Porges/f77329aa1a311fdd2e45edb7270b0f22 to your computer and use it in GitHub Desktop.
Save Porges/f77329aa1a311fdd2e45edb7270b0f22 to your computer and use it in GitHub Desktop.
Example of free monad usage in Haskell
{-# LANGUAGE DeriveFunctor #-}
module Main where
import Control.Monad
import Control.Monad.Free
data InteractionF f
= Get (String -> f)
| Put String f
deriving (Functor)
type Interaction = Free InteractionF
put :: String -> Interaction ()
put s = liftF (Put s ())
get :: Interaction String
get = liftF (Get id)
hello :: Interaction String
hello = do
put "What's your name?"
name <- get
put ("Hello, " ++ name)
pure name
interpret :: InteractionF (IO a) -> IO a
interpret (Get f) = getLine >>= f
interpret (Put s f) = putStrLn s >> f
main :: IO ()
main = void (iterM interpret hello)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment