[Haskell-cafe] Simple but interesting (for me) problem
inforichland at gmail.com
Wed Oct 21 14:23:40 EDT 2009
Here's an example in the IO monad:
counter = unsafePerformIO $ newIORef 0
next = do
modifyIORef counter (+1)
Naturally, this uses unsafePerformIO, which as you know, is not kosher...
On Wed, Oct 21, 2009 at 1:00 PM, Tim Wawrzynczak <inforichland at gmail.com>wrote:
> I'm guessing the function looks something like this? (this is common lisp
> not scheme)
> (let ((counter 0))
> (defun next ()
> (incf counter)
> So the first time you call (next), it returns 1, then 2, etc.
> The function (next) is a closure over the variable 'counter' and acts by
> incrementing the variable counter, which is only visible in the scope of the
> let-block. As you know in Haskell there is no mutable state (outside of
> certain monads), so a function like must take place in a monad which allows
> this, such as IO or ST. You would probably have to allocate an IORef or
> STRef which is local to the next function (effectively creating a closure
> over it).
> - Tim
> On Wed, Oct 21, 2009 at 12:34 PM, michael rice <nowgate at yahoo.com> wrote:
>> There's a thread on the plt-scheme list about creating a function of NO
>> arguments named NEXT that just returns the number of times it's been called,
>> a piece of cake in Scheme, but how would one do this in Haskell? Would the
>> best approach be to use a State monad?
>> Haskell-Cafe mailing list
>> Haskell-Cafe at haskell.org
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Haskell-Cafe