Skip to content

Instantly share code, notes, and snippets.

@ThomasCrevoisier
Created March 21, 2017 13:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ThomasCrevoisier/ae3f7739e81da10969ca3ea0637303b8 to your computer and use it in GitHub Desktop.
Save ThomasCrevoisier/ae3f7739e81da10969ca3ea0637303b8 to your computer and use it in GitHub Desktop.
module Main where
import Control.Monad.State.Lazy
data AppState = AppState {
_appCount :: Int
, _appActions :: [String]
} deriving Show
data Action
= Increment
| Decrement
| Reset
| SetTo Int deriving (Show)
updateState :: Action -> AppState -> AppState
updateState action state = state { _appCount = updateCount action (_appCount state), _appActions = show action : _appActions state }
where
updateCount :: Action -> Int -> Int
updateCount Increment x = x + 1
updateCount Decrement x = x - 1
updateCount Reset _ = 0
updateCount (SetTo i) _ = i
initialState :: AppState
initialState = AppState 0 []
simpleStateExample :: (Int, AppState)
simpleStateExample = runState someStateComputation initialState
where
someStateComputation :: State AppState Int
someStateComputation = do
modify (updateState Increment)
modify (updateState Decrement)
modify (updateState (SetTo 2))
modify (updateState Reset)
gets _appCount
main :: IO ()
main = do
print simpleStateExample
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment