Skip to content

Instantly share code, notes, and snippets.

@iurii-kyrylenko
Last active January 12, 2019 11:43
Show Gist options
  • Save iurii-kyrylenko/1d7a6a50b7a1c1d2218e8cc8ba52ac35 to your computer and use it in GitHub Desktop.
Save iurii-kyrylenko/1d7a6a50b7a1c1d2218e8cc8ba52ac35 to your computer and use it in GitHub Desktop.
Haskell State Exercises
-- exercices for
-- https://en.wikibooks.org/wiki/Haskell/Understanding_monads/State
import Control.Monad
import Control.Monad.Trans.State
import System.Random
rollDie :: State StdGen Int
rollDie = state $ randomR (1,6)
t1 = evalState rollDie (mkStdGen 0)
rollNDice :: Int -> State StdGen [Int]
-- rollNDice n = sequence $ replicate n rollDie
rollNDice n = replicateM n rollDie
t2 = evalState (rollNDice 5) (mkStdGen 0)
t3 = evalState (fmap (42*) rollDie) (mkStdGen 0)
fmap2 :: (a -> b) -> State s a -> State s b
fmap2 = liftM
t4 = evalState (fmap2 (42*) rollDie) (mkStdGen 0)
fmap3 :: (a -> b) -> State s a -> State s b
fmap3 f m = state $ \s -> let (v, s1) = (runState m) s
in (f v, s1)
t5 = evalState (fmap2 (42*) rollDie) (mkStdGen 0)
import Control.Monad.Trans.State
push :: a -> State [a] ()
push x = state $ \s -> ((), x:s)
pop :: State [a] (Maybe a)
pop = state $ \ s ->
case s of
[] -> (Nothing, [])
(x:xs) -> (Just x, xs)
stack = do
push 42
push 43
push 44
x <- pop
y <- pop
z <- pop
t <- pop
return (x,y,z,t)
r = evalState stack []
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment