[Haskell-cafe] Simple but interesting (for me) problem
Tim Wawrzynczak
inforichland at gmail.com
Wed Oct 21 14:23:40 EDT 2009
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 <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)
> 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 <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/96bb0e19/attachment.html
More information about the Haskell-Cafe
mailing list