4. Common Monads

Created Sunday 24 August 2014

Overview

Reader Monad

EXAMPLE
getFirst :: Reader String String
getFirst = do
name <- ask
return (name ++ " woke up")
getSecond :: Reader String String
getSecond = do
name <- ask
return (name ++ " wrote some Haskell")
getStory :: Reader String String
getStory = do
first <- getFirst
second <- getSecond
return ("First, " ++ first ++
". Second, " ++ second ++ ".")
story = runReader getStory "Benson"

State Monad

newtype State s a = State (s -> (a, s))
EXAMPLE
harmonicStep :: State (Double, Double) Double
harmonicStep = do
(position, velocity) <- get
let acceleration = (-0,01 * position)
velocity' = velocity + acceleration
position' = position + velocity'
put (position', velocity')
return position

harmonic :: State (Double, Double) [Double]
harmonic = do
position <- harmonicStep
laterPositions <- harmonic
return (position : laterPositions)

GHCi> let positions = evalState harmonic (1, 0)
GHCi> take 8 positions
Result: [1.0,
0.99,
0.9701, ..... ]

ST Monad

EXAMPLE
sumST :: [Int] -> STRef s Int -> ST s ()
sumST [] accumRef = return ()
sumST (x : xs) accumRef = do
accum <- readSTRef accumRef
writeSTRef accumRef (x + accum)
sumST xs accumRef
ALTERNATIVE
sum' :: [Int] -> Int
sum' xs = runST $ do
accumRef <- newSTRef 0
sumST xs accumRef
readSTRef accumRef



Backlinks: