Force single evaluation?

Sven Panne sven.panne at aedion.de
Thu Dec 21 06:27:06 EST 2006


Am Mittwoch, 20. Dezember 2006 16:10 schrieb Axel Jantsch:
> [...] My simplified codes is as follows:
>
> f :: InparT -> IO CInt
> f inPar = do
>           inP <- malloc
>           poke inP inPar
>
>           r <- cfun inP
>
>           free inP
>           return r

This can be simplified to 'flip with cFun' (malloc/free pair => alloca, 
alloca/poke => with).

> [...] So even if I make cfun pure (which it is), the enclosing function f is
> not.

This depends on the viewpoint: Unless malloc fails, f will return the same 
value for the same argument, so it can be considered pure.

> Shall I pretend f is pure and wrap it into unsafePerformIO?

You can do this, but you still depend on the compiler/interpreter not doing 
any funny transformations which could duplicate an application of f. I don't 
think that this will be a problem in practice, but to be on the safe side you 
could memoize f or cFun and perhaps even a 1-element cache might be enough to 
avoid all this trickery.

Cheers,
   S.


More information about the FFI mailing list