[Haskell-cafe] Re: Top Level TWI's again was Re: [Haskell] Re: Parameterized Show

David Roundy droundy at abridgegame.org
Tue Nov 23 08:17:42 EST 2004

On Tue, Nov 23, 2004 at 01:51:24PM +0000, Keean Schupke wrote:
> David Roundy wrote:
> >There are plenty of non-IO reasons to use unsafePerformIO, for which it is
> >essential.  If you want to write haskell code that uses a pointer
> >(allocated possibly via an FFI C routine), it has to be in the IO monad.
> >If you know that this pointer doesn't access memory that'll be changed at
> >random (or by other routines), you can (and *should*) safely use
> >unsafePerformIO.
> >
> Does it? cant you just declare:
> import foreign ccall "somefn" somefn :: Ptr Double -> Ptr Double

Right, but if you want to access the contents of that pointer in haskell,
you have to use the IO monad.  True, in principle you could write a pointer
dereferencing function in C:

import foreign ccall "readarray" readarray :: Ptr Double -> Int -> Double

but that hardly seems like either an efficient or elegant way of getting
around the fact that haskell can't read pointers outside the IO monad.
Also, of course, this readarray function written in C is no safer than
using unsafePerformIO with peekArray.

In case you're wondering, peekArray needs to be in the IO monad because
there's no guarantee that the memory pointed to by the Ptr is constant--it
may even be a pointer to an mmapped file, in which case it could change
value independently of the program's execution.

> >Also, if you're interested in using weak pointers (for example, to do
> >memoization), you'll almost certainly need to use unsafePerformIO.  Again,
> >the result can, and should, be encapsulated, so the module that uses
> >unsafePerformIO exports only pure functions (unless of course, there are
> >any that actually perform IO).
> Don't know about this one, got a short example?

I have a long and complicated example...


This is complicated because it's doing antimemoization rather than
memoization, and being backwards it's a bit trickier.  But it *is* an
example of a module that exports only pure functions, and couldn't be
written without unsafePerformIO (and does no IO).
David Roundy

More information about the Haskell-Cafe mailing list