Created
October 6, 2013 17:11
-
-
Save funrep/6856523 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
import Control.Monad.State (State, get, put, runState) | |
inc :: State Int () | |
inc = fmap (+ 1) get >>= put | |
-- get returns the state's int | |
-- fmap applies (+ 1) on that int | |
-- >>= applies the result to put which makes it the current state | |
reset :: State Int () | |
reset = put 0 | |
-- put makes 0 the current state | |
getCounter :: State Int Int | |
getCounter = get | |
-- get same as in inc, it get state | |
foobar :: Int | |
foobar = let | |
-- here we got a "private" interface within foobar | |
inc' = fmap (+ 1) get >>= put | |
reset' = put 0 | |
getCounter' = get | |
in (\(_, x) -> x) $ runState (do inc' -- here we got a sequence of actions | |
{- the above is a lambda -} reset' -- each replaces the current state | |
{- which simply extracts -} inc' | |
{- the result from the -} inc' | |
{- struct (tuple) that gets -} _ <- getCounter' -- here we bind the int to the var _ | |
{- returned -} inc') 0 -- this 0 is the default state | |
-- if you run foobar you will get 3 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment