Skip to content

Instantly share code, notes, and snippets.

@metric-space
Last active January 22, 2017 14:42
Show Gist options
  • Select an option

  • Save metric-space/f9f002f7bb2822bc32c302f851c91c8a to your computer and use it in GitHub Desktop.

Select an option

Save metric-space/f9f002f7bb2822bc32c302f851c91c8a to your computer and use it in GitHub Desktop.
fooling around with the state monad
import System.Random
import Control.Monad.State
-- given a [Int] add random numbers to it
a :: [Int]
a = [3, 1, 6, 7, 9]
myFunc :: Int -> State StdGen Int
myFunc x = do
gen <- get
let (y, gen2) = randomR (100,200) gen
put gen2
return $ y + x
myFunc2 :: Int -> State StdGen (Maybe Int)
myFunc2 0 = return Nothing
myFunc2 x = do
gen <- get
let (y, gen2) = randomR (100,200) gen
put gen2
return $ Just $ y*x
myFunc3 :: Int -> State StdGen (Maybe Int)
myFunc3 1000 = return Nothing
myFunc3 x = do
gen <- get
let (y, gen2) = randomR (100,200) gen
put gen2
return $ Just $ y*x + 2
myConnector :: Maybe Int -> State StdGen (Maybe Int)
myConnector (Just 1000) = return Nothing
myConnector (Just x) = myFunc3 x
x :: State StdGen [Int]
x = mapM myFunc a
y :: [Int] -> State StdGen [Maybe Int]
y = mapM myFunc2
z :: [Maybe Int] -> State StdGen ([Maybe Int])
z = mapM myConnector
g = evalState (x >>= (z <=< y )) (mkStdGen 4567)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment