[Haskell-cafe] IORef memory leak

Claus Reinke claus.reinke at talk21.com
Fri Jun 19 12:29:42 EDT 2009


>> It is not possible to write a modifyIORef that *doesn't* leak memory!
>>   
> Why? Or can one read about it somewhere?

Possibly, Don meant that 'modifyIORef' is defined in a way that 
does not allow to enforce evaluation of the result of the modification
function (a typical problem with fmap-style library functions):

    modifyIORef ref f = readIORef ref >>= writeIORef ref . f

No matter whether 'f' is strict or not, the 'writeIORef r' doesn't
evaluate its result, just stores the unevaluated application:

    > r<-newIORef 0
    > modifyIORef r (\x->trace "done" $ x+1)
    > modifyIORef r (\x->trace "done" $ x+1)
    > readIORef r
    done
    done
    2

If it had been defined like this instead

    mRef r ($) f = readIORef r >>= (writeIORef r $) . f

it would be possible to transform the strictness of 'writeIORef r'
to match that of 'f':

    > r<-newIORef 0
    > mRef r ($) (\x->trace "done" $ x+1)
    > mRef r ($) (\x->trace "done" $ x+1)
    > readIORef r
    done
    done
    2
    > r<-newIORef 0
    > mRef r ($!) (\x->trace "done" $ x+1)
    done
    > mRef r ($!) (\x->trace "done" $ x+1)
    done
    > readIORef r
    2

Claus




More information about the Haskell-Cafe mailing list