Skip to content

Instantly share code, notes, and snippets.

@joker1007
Created August 3, 2012 19:01
Show Gist options
  • Save joker1007/3250455 to your computer and use it in GitHub Desktop.
Save joker1007/3250455 to your computer and use it in GitHub Desktop.
module MyState where
data MyState s a = MyState {runMyState :: (s -> (a, s))}
instance Monad (MyState s) where
return a = MyState $ \s -> (a, s)
(>>=) m f = MyState $ \s -> let (a, s') = runMyState m s
in runMyState (f a) s'
get :: MyState a a
get = MyState $ \s -> (s, s)
put :: a -> MyState a ()
put s = MyState $ \_ -> ((), s)
type Stack a = MyState [a] a
stack :: Int -> MyState [Int] Int
stack a = do as <- get
put (a:as)
return a
pop :: MyState [Int] Int
pop = do (a:as) <- get
put as
return a
hoge :: MyState [Int] Int
hoge = do stack 5
stack 10
a <- stack 15
return a
fuga :: MyState [Int] Int
fuga = do n <- pop
n' <- pop
return (n + n')
moge :: Int -> (Int, [Int])
moge n = let (_, as) = runMyState hoge [n]
in runMyState fuga as
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment