Here's an example in the IO monad: import Data.IORef import System.IO.Unsafe
counter = unsafePerformIO $ newIORef 0 next = do modifyIORef counter (+1) readIORef counter Naturally, this uses unsafePerformIO, which as you know, is not kosher... Cheers, - Tim On Wed, Oct 21, 2009 at 1:00 PM, Tim Wawrzynczak <inforichl...@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) > 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). > > Cheers, > - Tim > > > On Wed, Oct 21, 2009 at 12:34 PM, michael rice <nowg...@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@haskell.org >> http://www.haskell.org/mailman/listinfo/haskell-cafe >> >> >
_______________________________________________ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe