[Haskell-cafe] lazily traversing a foreign data structure

Derek Elkins derek.a.elkins at gmail.com
Thu Oct 25 13:04:34 EDT 2007


On Thu, 2007-10-25 at 11:30 -0400, Graham Fawcett wrote:
> Hi folks,
> 
> I'm writing a Gnu DBM module as an exercise for learning Haskell and
> its FFI. I'm wondering how I might write a function that returns the
> database keys as a lazy list. I've wrapped the two relevant foreign
> functions:
> 
>     firstKey :: Ptr Db -> IO (Maybe String)
>     nextKey  :: Ptr Db -> String -> IO (Maybe String)
> 
> NextKey takes a key, and returns the next one. Either function could
> return Nothing, since the db may have 0 or 1 keys.
> 
> Given these, is it possible to write a (simple) function
> 
>     allKeys :: Ptr Db -> IO [String]
> 
> that lazily fetches the keys? (Or, an idiomatic way of achieving the
> same end?)

Just use unsafeInterleaveIO in the obvious definition to read all the
keys.  That said, it's not called unsafeInterleaveIO for no reason.



More information about the Haskell-Cafe mailing list