25.10.2015 Views

Write You a Haskell Stephen Diehl

1kEcQTb

1kEcQTb

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

evalStack :: Stack a -> IO [Int]<br />

evalStack m = exec<strong>Write</strong>rT (evalStateT (unStack m) 0)<br />

StateT<br />

e state monad allows functions within a stateful monadic context to access and modify shared state.<br />

put :: s -> State s () -- set the state value<br />

get :: State s s -- get the state<br />

gets :: (s -> a) -> State s a -- apply a function over the state, and return the result<br />

modify :: (s -> s) -> State s () -- set the state, using a modifier function<br />

Evaluation functions often follow the naming convention of using the prefixes run, eval, and exec:<br />

execState :: State s a -> s -> s<br />

-- yield the state<br />

evalState :: State s a -> s -> a<br />

-- yield the return value<br />

runState :: State s a -> s -> (a, s) -- yield the state and return value<br />

For example:<br />

import Control.Monad.State<br />

test :: State Int Int<br />

test = do<br />

put 3<br />

modify (+1)<br />

get<br />

main :: IO ()<br />

main = print $ execState test 0<br />

ReaderT<br />

e Reader monad allows a fixed value to be passed around inside the monadic context.<br />

ask :: Reader r r -- get the value<br />

asks :: (r -> a) -> Reader r a -- apply a function to the value, and return the res<br />

local :: (r -> r) -> Reader r a -> Reader r a -- run a monadic action, with the value modified by<br />

For example:<br />

import Control.Monad.Reader<br />

data MyContext = MyContext<br />

{ foo :: String<br />

26

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!