Force single evaluation?

Malcolm Wallace Malcolm.Wallace at
Mon Dec 18 11:50:28 EST 2006

"Axel Jantsch" <axel at> wrote:

> I call a C function from a Haskell program. I am using unsafePerformIO
> to use it outside a monad. 
> Even though the C function does not have any side effect, I absolutely
> don't want to evaluate it more than once for performance reasons. But
> my impression is that it is evaluated several times.
> 1. Can I monitor somehow how often it is evaluated?

You could wrap it (in C) with another function that keeps a counter of
invocations in a static local variable.

    result_t  originalFn (arg1_t arg1, arg2_t arg2);
    result_t  wrappedFn  (arg1_t arg1, arg2_t arg2) {
      static int i = 0;
      fprintf(stderr,"originalFn called %d times\n",i);
      return originalFn(arg1,arg2);

> 2. Can I ensure that the function is evaluated only once?

How about stating in the type of the FFI decl that the C function is
pure (even if it is not)?  Then be sure to bind its result in only one
place.  That should guarantee it is called only once.

    foreign import ccall originalFn :: Arg1T -> Arg2T -> IO ResultT
    foreign import ccall originalFn :: Arg1T -> Arg2T -> ResultT


More information about the FFI mailing list