Skip to content

Instantly share code, notes, and snippets.

@fizruk
Forked from bgamari/TH.hs
Last active December 28, 2015 04:19
Show Gist options
  • Save fizruk/7441605 to your computer and use it in GitHub Desktop.
Save fizruk/7441605 to your computer and use it in GitHub Desktop.
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE FlexibleContexts #-}
module Main where
import Control.Monad
import Control.Monad.Free
import Control.Monad.Free.TH
data Lang next
= Done
| Failure String
| Output String next
| Input (String -> next)
| Prompt String (String -> next)
| InputWithNo (Int -> String -> next)
| Fork next (Int -> next)
| AnyOf (Int -> Int -> Int -> next) (String -> next)
deriving (Functor)
makeFree ''Lang
test :: Free Lang ()
test = do
output "Hi!"
name <- prompt "What's your name?"
when (null name) $ failure "No name given!"
output $ "Nice to meet you, " ++ name ++ ")!"
done
runLang :: Free Lang () -> IO ()
runLang = iterM runF
where
runF Done = return ()
runF (Failure s) = putStrLn $ "Error: " ++ s
runF (Output s next) = putStrLn s >> next
runF (Input next) = getLine >>= next
runF (InputWithNo next) = getLine >>= next 23
runF (Prompt s next) = putStrLn s >> getLine >>= next
main :: IO ()
main = runLang test
@fizruk
Copy link
Author

fizruk commented Nov 13, 2013

For the code from Control.Monad.Free.TH look here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment