Skip to content

Instantly share code, notes, and snippets.

@btipling
Created August 7, 2017 01:30
Show Gist options
  • Save btipling/90786a396b155380d980f1539da39b54 to your computer and use it in GitHub Desktop.
Save btipling/90786a396b155380d980f1539da39b54 to your computer and use it in GitHub Desktop.
Figuring out state monads!
(Just 3,[9,1])
(Nothing,[])
module Main where
import Control.Monad.State
type StackVal = Maybe Int
type Stack = [Int]
popThings :: State Stack StackVal
popThings = do
state (\s -> (Just 0, s))
push 9
push 3
pop
pop
pop
pop
pushThings :: State Stack StackVal
pushThings = do
state (\s -> (Just 0, s))
push 9
push 3
pop
push :: Int -> State Stack StackVal
push n = state $ (\s -> (Nothing, n:s))
popState :: Stack -> (StackVal, Stack)
popState [] = (Nothing, [])
popState (x:xs) = (Just x, xs)
pop :: State Stack StackVal
pop = state $ popState
startState = [1]
main = do
putStrLn $ show $ runState pushThings startState
putStrLn $ show $ runState popThings startState
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment