Created
January 7, 2012 19:18
-
-
Save Newky/1575700 to your computer and use it in GitHub Desktop.
State Haskell
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
data State s a = State (s -> (a, s)) | |
test :: Int -> State Int () -> State Int () -> State Int Bool | |
test n f g = (f `bindState` (\_ -> g) `bindState` (\_ -> State $ (\s -> ((s > n), s)))) | |
runState (State t) s = t s | |
returnState :: a -> State s a | |
returnState a = State $ (\s -> (a, s)) | |
bindState :: State s a -> (a -> State s b) -> State s b | |
bindState m k = State $ (\s -> let (a, s') = runState m s | |
in runState (k a) s') | |
get :: State s s | |
get = State $ (\s -> (s, s)) | |
set :: s -> State s () | |
set s = State $ (\_ -> ((), s)) | |
instance Monad (State s) where | |
return = returnState | |
(>>=) = bindState | |
testMonad :: Int -> State Int () -> State Int () -> State Int Bool | |
testMonad n f g = ( f >> g >> (State $ (\s -> ((s>n), s)))) | |
testMonad2 :: Int -> State Int () -> State Int () -> State Int Bool | |
testMonad2 n f g = do | |
f | |
g | |
State $ (\s-> ((s>n), s)) | |
f :: State Int () | |
f = State $ (\s -> case s of | |
1 -> ((), (s+1)) | |
2 -> ((), (s+2)) | |
_ -> ((), (s)) | |
) | |
g :: State Int () | |
g = State $ (\_ -> ((), 11)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment