Last active
July 13, 2017 18:50
-
-
Save vvv/4f10496438bdd003a972f7879a667144 to your computer and use it in GitHub Desktop.
Working through the Operational Monad Tutorial
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
{-# LANGUAGE GADTs #-} | |
module Program where | |
-- | |
-- The Operational Monad Tutorial: | |
-- http://apfelmus.nfshost.com/articles/operational-monad.html | |
-- | |
-- GADT | |
data Program instr a where | |
Then :: instr a -> (a -> Program instr b) -> Program instr b | |
Return :: a -> Program instr a | |
type StackProgram a = Program StackInstruction a | |
data StackInstruction a where | |
-- Swap :: StackInstruction () | |
Push :: Int -> StackInstruction () | |
Pop :: StackInstruction Int | |
type Stack a = [a] | |
interpret :: StackProgram a -> Stack Int -> a | |
interpret (Then (Push a) is) stack = interpret (is ()) (a:stack) | |
-- interpret (Push a `Then` is) stack = interpret (is ()) (a:stack) | |
interpret (Pop `Then` is) (b:stack) = interpret (is b ) stack | |
interpret (Return c) stack = c | |
-- interpret :: StackProgram -> Stack Int -> Stack Int | |
-- interpret (Push a : is) stack = interpret is (a : stack) | |
-- interpret (Pop : is) stack = interpret is (tail stack) | |
-- interpret [] stack = stack | |
-- example :: StackProgram | |
-- example = Push 5 : Push 42 : Pop : [] | |
-- example2 = do | |
-- a <- pop -- Pop `Then` \a -> | |
-- b <- pop -- Pop `Then` \b -> | |
-- push (a+b) -- Push (a+b) `Then` Return | |
example2 = Pop `Then` \a -> | |
Pop `Then` \b -> | |
Return (a+b) | |
-- Push (a+b) `Then` Return | |
-- Push (a+b) `Then` \_ -> Pop `Then` \c -> Return (c*10) | |
example3 = Pop `Then` \a -> Pop `Then` \b -> Return (a*b) | |
-- f :: String -> Int -> String | |
-- f s n = s ++ show n | |
-- prefixWithABC :: Int -> String | |
-- prefixWithABC = f "ABC" | |
-- f' :: String -> (Int -> String) | |
-- f' s = | |
-- where | |
-- g n = s ++ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment