[Haskell-cafe] allocation for "pure" FFI functions

Duncan Coutts duncan.coutts at googlemail.com
Fri Oct 15 04:07:22 EDT 2010

On Thu, 2010-10-14 at 17:45 +0000, Johannes Waldmann wrote:
> Hi. I wonder how to do the following properly.
> I have one (large) C  type, let's call it T,
> and I want to sell it as an abstract type in Haskell.
> I want to use C functions as if they were of type T -> T  
> (pure function, returns a modified copy of the input)
> and the question is, how to do the memory allocation for that,
> in particular, how to avoid  IO  showing up 
> in the (visible) types on the Haskell side:
> I don't want IO because I don't want to declare some artificial
> order of execution - instead I want lazy evaluation.
> E.g., I might have some Haskell record with a T component
> which may or may not be evaluated (accessed) at all.

It is exactly for this purpose that the Haskell FFI library includes
unsafePerformIO. This is basically *the* legitimate use case for it, so
you don't need to feel bad about it.

The FFI spec says:

        Sometimes an external entity is a pure function, except that it
        passes arguments and/or results via pointers. To permit the
        packaging of such entities as pure functions, Foreign provides
        the following primitive: 
        unsafePerformIO :: IO a -> a



More information about the Haskell-Cafe mailing list