Created
August 3, 2012 19:01
-
-
Save joker1007/3250455 to your computer and use it in GitHub Desktop.
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
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