I need a global counter, starting from 0, 1, 2, 3, ..... I kind of understand that this "impure" code should be separately implemented... I am just starting to understand Monad, but have no idea how to implement this global counter using Monad? This could be very useful example for understanding if it is possible
相关问题
- Understanding do notation for simple Reader monad:
- Making Custom Instances of PersistBackend
- Haskell: What is the differrence between `Num [a]
- applying a list to an entered function to check fo
- Haskell split a list into two by a pivot value
相关文章
- Is it possible to write pattern-matched functions
- Haskell underscore vs. explicit variable
- Top-level expression evaluation at compile time
- Stuck in the State Monad
- foldr vs foldr1 usage in Haskell
- List of checkboxes with digestive-functors
- How does this list comprehension over the inits of
- Replacing => in place of -> in function type signa
What you can look into is state monad. This is a general purpose monad which can be used to manage state. In your case the counter is just a state that you want to maintain.
http://www.haskell.org/haskellwiki/State_Monad
You can implement this using a
State
monad, which stores the current value of your counter as the state. You can then useget
to get the current counter value, andmodify (+1)
to increment it.One useful variation of this is the
Supply
monad, where you can use an arbitrary sequence as your "counter", so to have a plain counter starting from zero, just use[0..]
as the supply.While State is fine, you don't need to inspect the counter while calculating, but just to increase it, so the Writer monad should be sufficient. See Learn you a Haskell for a (not too serious) introduction.
State monad gives you state but only inside the monad. It is not persistent across repeated invocations of the function.
If you want truly global, mutable state you might want to do something like:
Here 'makeCounter' creates a global, mutable variable that is keeps its state across invocations and destroys purity. For example, in the main function two identical calls to 'testCounter' gives different results.