[Haskell-beginners] Rewriting using State and/or Reader?

Paul Sargent psarge at gmail.com
Fri Nov 12 16:38:35 EST 2010


Hi,

My Haskell project has quite a lot of code in it which either:

a) Uses a set of common values which are stored in an "environment" data type.
b) Takes a set of values, and updates them repetitively.

Often the same function will do both.

Up to now I've tended to avoid monad based code (except List and Maybe), but I'm thinking that maybe I can simplify some of my code.

The code for case a) might look something like:

    data Env = Env {rateA    :: Double,
                    valueB   :: Double} deriving (Show)

    f :: Env -> Double -> Double -> Double
    f env a b = a * ra + b * g' b
        where ra = rateA env
              g' = g env

    g :: Env -> Double -> Double
    g env b = (valueB env) + b

Basically I'm threading the Env parameter through all the function calls that need it. Am I right in saying this sort of stuff is a good candidate for the Reader monad? What do I gain if I do it?

Similarly am I right in saying that this type of code is a good candidate for State (called repeatedly from some loop somewhere)?

    updateList :: Double -> [Item] -> [Item]
    updateList t xs = map (updateItemToTime t) xs

    updateItemToTime :: Double -> Item -> Item
    updateItemToTime = some function which does an incremental calculation for a time slice

(obviously the code is nonsense, I'm just trying to give a feel of the structures I'm using)

Then, if I did move the code to these monads, how well do the live together? ...and how about functions which use functions in multiple different state or reader monads?

Basically, I haven't seen the advantage of using the monadic way for this code, so what am I missing?

Thanks

Paul


More information about the Beginners mailing list