Confusion over the passage of the state monad in Haskell

Haskell State uses a monad to retrieve and store state. And in the next two examples, both pass the state monad using >>, and a closed check (using the inline and abbreviations) confirms that the state has really been transferred to the next step.

But this does not seem very intuitive. Does this mean when I want to transfer the state monad, I just need >>(or a >>=lambda expression \s -> a, where sit is not free in a)? Can someone give an intuitive explanation for this fact without bothering to reduce the function?

-- the first example
tick :: State Int Int 
tick = get >>= \n ->
   put (n+1) >>
   return n

-- the second example
type GameValue = Int 
type GameState = (Bool, Int)

playGame' :: String -> State GameState GameValue 
playGame' []      = get >>= \(on, score) -> return score
playGame' (x: xs) = get >>= \(on, score) ->
    case x of
        'a' | on -> put (on, score+1)
        'b' | on -> put (on, score-1)
        'c'      -> put (not on, score)
        _        -> put (on, score) 
    >> playGame xs 

Thank you so much!

+4
1

, s -> (a, s). , , "" , s ( , a).

f :: a -> State s b
g :: b -> State s c

>=>

f >=> g

>>=

\a -> f a >>= g

a -> State s c

, - - s, a, c. , a, c s. , . ( ) , , . , , >>= hackage), , , ).

m >>= k  = StateT $ \ s -> do
    ~(a, s') <- runStateT m s
    runStateT (k a) s'

StateT runStateT, m s -> (a, s), k a -> (s -> (b, s)), s -> (b, s). , s, b k, a, a? m s, s' m, (k a) ( s -> (b, s)). s m, s' k, s''.

, , , - . , , , State -actions, do -notation bind (>>=) /.

>>= >> , , .

a >> b

a >>= \_ -> b

a, ( ) ( ) b.


tick :: State Int Int 
tick = get >>= \n ->
    put (n+1) >>
    return n

do -notation

tick = do
    n <- get
    put (n + 1)
    return n

, , , .

  • get current (get :: s -> (s, s) ), <- , , , ( get).

  • put :: s -> (s -> ((), s)), put :: s -> s -> ((), s), , ( ) , (), ( <- , >> >>=). - put n + 1 .

  • return , .

, tick s, s+1 s .

, >> , (), put. .

+5

Source: https://habr.com/ru/post/1670496/


All Articles