Hi Roland,

> However my question is: How to do a little bit more complex IO:
> Assume I have a file called 'filenames.txt' that contains a
> list of filenames eg:
>   file1.txt
>   file2.txt
>   file3.txt
> 
> I now want to write a simple program, that prints out the first
> line of every file mentioned in 'filenames.txt'.

here we are ...

> module Main
> where

> printFirstLineOf      :: FilePath -> IO ()
> printFirstLineOf filePath
>                       =  do contents <- readFile filePath
>                             putStrLn ((lines contents ++ ["<empty>"])!!0)

> main                  :: IO ()
> main                  =  do contents <- readFile "filenames.txt"
>                             mapM_ printFirstLineOf (lines contents)

The function `printFirstLineOf' prints the first line of the given file
(no error handling). If the file is empty its prints `<empty>'.  The
predefined function `mapM_ f x' applies `f' to every element in `x' and
sequences the `IO' actions.

Ralf

P.S.: Your code does not work since `processSingleFile' does
`IO' but the type pretends it's a pure function.

> processSingleFile :: String -> String
> processSingleFile s =
>   do
>     inh <- openFile s ReadMode
>         cont <- hGetContents inh
>         return (head (lines cont))


Reply via email to