Skip to content

Instantly share code, notes, and snippets.

@MgaMPKAy
Created June 8, 2012 15:54
Show Gist options
  • Save MgaMPKAy/2896343 to your computer and use it in GitHub Desktop.
Save MgaMPKAy/2896343 to your computer and use it in GitHub Desktop.
State Monad example
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