Created
May 4, 2017 07:05
-
-
Save Porges/f77329aa1a311fdd2e45edb7270b0f22 to your computer and use it in GitHub Desktop.
Example of free monad usage in Haskell
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{-# 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