Understanding the State Monad

Looking at you will learn about the Haskell definition State Monad:

instance Monad (State s) where  
    return x = State $ \s -> (x,s)  
    (State h) >>= f = State $ \s -> let (a, newState) = h s  
                                        (State g) = f a  
                                    in  g newState  

I do not understand the types h sand g newStatein the lower right-hand side.

Could you explain their types and what happens?

+4
source share
3 answers

State s a is the designation of the function --- "state transformer function"

s -> (a, s)

, s , , a. " ". , , - .

upd :: Int -> (Int, Int)
upd s = let s' = s + 1 in (s', s')

a s .


, , , . - upd.

, " ". :

compose :: (s -> (a, s))         -- the initial state transformer
        -> (a -> (s -> (b, s)))  -- a new state transformer, built using the "result"
                                 -- of the previous one
        -> (s -> (b, s))         -- the result state transformer

, , , . :

compose f f' = \s -> let (a, s')  = f s
                         (b, s'') = f' a s'
                     in  (b, s'')

, s -typed, [s, s', s''] " ", , , .

compose , , upd

twoUnique :: Int -> ((Int, Int), Int)
twoUnique = compose upd (\a s -> let (a', s') = upd s in ((a, a'), s'))

State. , , compose , .

(>>=) :: State s a     -> (a -> State s b   ) -> State s b
(>>=) :: (s -> (a, s)) -> (a -> (s -> (b, s)) -> (s -> (b, s))

. "" "" State --- State runState

State    :: (s -> (a, s)) -> State s a
runState :: State s a     -> (s -> (a, s))

compose (>>=)

compose f f'       =         \s -> let (a, s')  = f s
                                       (b, s'') =           f' a  s'
                                   in  (b, s'')

(>>=) (State f) f' = State $ \s -> let (a, s')  = f s
                                       (b, s'') = runState (f' a) s'
                                   in  (b, s'')
+7

State , . , , ,

newtype State s a = State { runState :: s -> (a,s) }

a State s -> (a,s). , - . Haskell, : s , a , a (, Int, ).

. , (>>=)

Monad m => m a -> (a -> m b) -> m b

, , f a -> m b. m State s, f a -> State s b. ,

(State h) >>= f = State $ \s -> let (a, newState) = h s  
                                    (State g) = f a  
                                in  g newState

f a -> State s b, State g State s b (.. g :: s -> (b,s)), h s -> (a,s), newState :: s, , g newState, (b, s).

- , State, .

+2

State LYAH:

newtype State s a = State { runState :: s -> (a,s) }

, State , a . , h , h s a newState.

Hoogle , (>>=)

(>>=) :: Monad m => m a -> (a -> m b) -> m b

f a State s b. , f a, State. , h, g - , ( newState) (a,newState2).

, , (>>=): . A State , , . , State " \s -> let (a, newState) = h s, . ( , ) , . , newState, .

+1

All Articles