-
-
Save fizruk/7441605 to your computer and use it in GitHub Desktop.
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 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For the code from
Control.Monad.Free.TH
look here.