Saturday, 5 January 2008

Haskell: Read the content of a file into a list of string

module Main (main) where

import IO
import System.Environment

main :: IO ()
main = do { x <- getArgs           
; hdl <- openFile (x !! 0) ReadMode           
; y <- readSources hdl []           
; print y }  
readSources :: Handle -> [String] -> IO [String]
readSources hdl s = do { t <- hIsEOF hdl                        
; if t then return s else do { x <- hGetLine hdl; readSources hdl (s ++ [x]) } }

2 comments:

Don Stewart said...

A much simpler way, using 'lines', (also more idiomatic, since there's less IO code).


import IO
import System.Environment

main = do
[f] <- getArgs
print . lines =<< readFile f

You'll need to get the rig

Wei said...

Wow! Sorry, only noticed this now. Thanks!