[Haskell-cafe] A question about laziness and foreign resources (and libxml2)

Graham Fawcett graham.fawcett at gmail.com
Wed Apr 29 21:02:45 EDT 2009


Hi folks,

I'm having trouble reasoning about laziness and FFI resources. I've
written a little C wrapper function to augment Text.XML.LibXML; given
a Ptr Node, it will return the node's tag-name:

  foreign import ccall unsafe _getName :: Ptr Node -> IO CString

Given LibXML's 'withNode' function, I can write:

  withNode :: Node -> (Ptr Node -> IO a) -> IO a
  getName1 :: Node -> IO String
  getName1 n = withNode n $ \n' -> _getName n' >>= peekCString

But I'm tempted to write this instead:

  getName2 n = withNode n return >>= _getName >>= peekCString

In a strict language, I'd observe that the (Ptr Node) in getName2 was
escaping the lexical scope of the withNode call, and so getName2 would
be unsafe (since it might get GC'd upon leaving that scope). But in
Haskell, I can't reason out whether that's the case.

Is 'withNode n return' a risky proposition? Is lexical scope indeed
the right test here? If not, how might you reason about the safety of
this code?

Thanks,
Graham


More information about the Haskell-Cafe mailing list