Reputation: 3973
I wrote this code that loops through the lines of a file handle and does an arbitrary action with it. I don't think it should need to be recursive - can I make it into a fold action?
Thanks!
processHandle :: Handle -> (String->IO ()) -> IO ()
processHandle h fn = do
eof <- hIsEOF h
if eof then
return ()
else do
myLine <- hGetLine h
fn myLine
processHandle h fn
Upvotes: 1
Views: 229
Reputation: 120751
Manually working with handles is very eschewed in Haskell. It doesn't play well together with a functional programming style.
For a simple input processor like this, it's probably the best to just read the entire file as one (lazy) string, and process the lines of that:
processHandle h fn = mapM_ fn . lines =<< hgetContents h
Of course this can also be written as a fold, just look up the definition of mapM_
.
Now, this lazy-IO approach doesn't work as well for many serious applications. If this isn't one huge file, then you may be good if you just read the file strictly with the Data.Text
equivalent. Else, if you really need to read lines interleaved with the processing steps, better look into conduit.
Upvotes: 6