[Haskell-beginners] Global variable question

Brent Yorgey byorgey at seas.upenn.edu
Wed Dec 30 20:59:52 EST 2009


On Wed, Dec 30, 2009 at 05:49:12PM -0800, Joe Van Dyk wrote:
> What's the appropriate way to write this in Haskell?
> 
> # Ruby code, ignore the thread-unsafety for now.
> class Ticker
>   @@tick = 0
>   def self.update!
>     @@tick += 1
>   end
>   def self.current
>     return @@tick
>    end
> end
> 
> Ticker.update! # 1
> Ticker.update! # 2
> Ticker.current  # 2

If you really want a global ticker, use the State monad:

  tick :: State Int ()
  tick = modify (+1)

  -- increment the counter twice then return its new value
  mainStuff :: State Int Int
  mainStuff = tick >> tick >> get

-Brent


More information about the Beginners mailing list