Created
August 7, 2017 01:30
-
-
Save btipling/90786a396b155380d980f1539da39b54 to your computer and use it in GitHub Desktop.
Figuring out state monads!
This file contains 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
(Just 3,[9,1]) | |
(Nothing,[]) |
This file contains 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
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