QuickSnip LogoA light blue logo with a thunderbolt in bracketsQuickSnip

State Monad

Managing mutable state using the State monad.

  • monads
  • state
  • state-management

Code

import Control.Monad.State

increment :: State Int Int
increment = do
    count <- get
    put (count + 1)
    return count

Usage

main :: IO ()
main = do
    let (res1, intermediateState) = runState increment 0
    print res1      -- Output: 0
    let (result, finalState) = runState increment intermediateState
    print result    -- Output: 1
    print finalState  -- Output: 2