Last active
July 16, 2017 16:03
-
-
Save OsQu/150ce09fc364ba599a63e3716eab821d to your computer and use it in GitHub Desktop.
FreeMonad + Interpreter
This file contains 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
module DSL | |
( get | |
, set | |
, end | |
, DSL(..) | |
) where | |
import Control.Monad.Free | |
data DSL next = Get String (String -> next) | |
| Set String String next | |
| End | |
instance Functor DSL where | |
fmap f (Get name k) = Get name (f . k) | |
fmap f (Set name value next) = Set name value (f next) | |
fmap _ End = End | |
get :: String -> Free DSL String | |
get key = liftF (Get key id) | |
set :: String -> String -> Free DSL () | |
set key value = liftF (Set key value ()) | |
end :: Free DSL a | |
end = liftF (End) |
This file contains 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
module IOInterpreter where | |
import Control.Monad.Free | |
import DSL | |
runIO :: Free DSL a -> IO () | |
runIO (Free (Get name k)) = do | |
putStrLn ("Get " ++ name) | |
let result = "something" | |
runIO $ k result | |
runIO (Free (Set key name next)) = do | |
putStrLn ("Set " ++ key ++ " " ++ name) | |
runIO next | |
runIO (Free End) = putStrLn "End" | |
runIO (Pure _) = return () |
This file contains 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
module Main where | |
import Control.Monad.Free | |
import DSL | |
import IOInterpreter | |
fn :: Free DSL a | |
fn = do foo <- get "foo" | |
set "foo" foo | |
end | |
main :: IO () | |
main = do | |
runIO fn | |
return () |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment