Created
June 8, 2012 15:54
-
-
Save MgaMPKAy/2896343 to your computer and use it in GitHub Desktop.
State Monad example
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
module RPN where | |
import Control.Monad | |
import Control.Monad.State | |
type Stack = [Int] | |
type StackState = State Stack | |
push :: Int -> StackState () | |
push n = modify (n:) | |
pop :: StackState Int | |
pop = do | |
stack <- get | |
modify (drop 1) | |
return $ head stack | |
add :: StackState () | |
add = do | |
stack <- get | |
when (length stack < 2) (error "Add need two oprand") | |
let s = sum $ take 2 stack | |
modify (\stack -> s : drop 2 stack) | |
begin :: StackState () | |
begin = do | |
modify (\s -> []) | |
end :: StackState Int | |
end = do | |
stack <- get | |
return $ head stack | |
evalRPN :: StackState a -> (a, Stack) | |
evalRPN exp = runState exp [] | |
test = do | |
begin | |
push 1 | |
pop | |
push 2 | |
push 3 | |
push 4 | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment