[Haskell-beginners] Global variables
gale at sefer.org
Thu Jun 30 16:05:15 CEST 2011
ARJANEN Loïc Jean-David wrote:
>> For a pet project I need a global counter, giving how many times a
>> given function was called. What would you use for that purpose ?
Michael Xavier wrote:
> I tend to use Control.Monad.State for stateful stuff like this. It is found
> in the mtl package
I agree that this is a good approach.
If the only state you need is this, it might be easier just
to add the counter as an additional parameter to your function,
and return its incremented value as part of your return type.
For example, you can return a tuple (v, n) where v is the value
you were returning before and n is the updated counter.
If you also need other kinds of state, or if adding the counter
complicates the types throughout your program,
then the State monad is the way to go.
More information about the Beginners