[Haskell-cafe] IO Monad operation madness

Rob Hoelz hoelz at wisc.edu
Thu May 17 19:01:07 EDT 2007


Isaac Dupree <isaacdupree at charter.net> wrote:

> > linkedListToHaskellStringList :: LinkedList -> IO [String]
> > linkedListToHaskellStringList listPtr =
> >     let convertList' ptr =
> convertList' :: LinkedList -> [IO String], I infer?

Correct.
> >         if listIsNull ptr
> >             then
> >                 []
> >             else
> are you doing IO here or not? You need a 'do' if you are (else this
> is a syntax error), but IO /= [], so what is the function returning?
My mistake; I left off the 'do.'  My original code does have it, though.

I figure since the null case returns [] (which should be a valid [IO
String], and str is an IO String, it should work.  In fact, if I take
out the next <- ... line and substitute ptr for next, it compiles.  But
that's not exactly desirable behavior...=P

> >                 let str = peekCString =<< (linked_list_getdata ptr)
> >                 next <- linked_list_next ptr
> >                 str : (convertList' next)
> >     in
> >         sequence $ convertList' listPtr
> > 
> > listIsNull :: LinkedList -> Bool
> > listIsNull (LinkedList ptr) = ptr == nullPtr
> 
> I'd recommend recursion without the 'sequence', I think, so you can do
> IO along the way - traversing the LinkedList - and then 'return' the
> list made from (:).  (and throw in unsafeInterleaveIO if you're
> feeling sadistical and want parts of the traversal to be performed at
> unspecified later dates)

The problem I have with that is that I'd have to do something like this:

str <- peekCString =<< (linked_list_getdata ptr)
next <- linked_list_next ptr
rest <- linkedListToHaskellStringList next
return (str : rest)

I don't like this because it's not really tail recursive.  I've been
told tail recursion is overrated, but since I don't really know how
long the C linked lists are going to be (could be 10 elements, could be
100), I don't think avoiding a stack overflow is overrated.

Thanks,
Rob


More information about the Haskell-Cafe mailing list