[Haskell-cafe] Simple but interesting (for me) problem

Tim Wawrzynczak inforichland at gmail.com
Wed Oct 21 14:00:29 EDT 2009

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?
> Michael
> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20091021/d50a0e67/attachment.html

More information about the Haskell-Cafe mailing list