[Haskell-beginners] Reading in the contents of a variable number of files

Daniel Fischer daniel.is.fischer at web.de
Tue Mar 16 17:28:55 EDT 2010

Am Dienstag 16 März 2010 22:10:46 schrieb Tim Perry:
> I need to read in and then combine a variable number of files. I am
> trying to figure out how to get the contents of all the files into an
> array.
> let fileContentsArray = getData ["dataFile1.txt",
> "dataFile2.txt"]
> getData :: [String] -> [String]
> getData [] = []
> getData (f:files) = do
>                        fileData
> <- readFile f
>                        fileData : (getData files)
> I figured I could use readFile to open the files. But, I need to use
> <- to get the data out of the IO Action and into a value. I thought I
> could write a function like the following, but I'm getting no-where. I
> suspect I'm missing something basic about IO in Haskell. Can anybody
> point me to a good resource....

If you're in IO, you can't get out (well, you can, but you shouldn't unless 
you really know what you do, the first six letters of unsafePerformIO 
really mean what they say).


do some stuff
   more stuff
   fileContentsList <- mapM readFile ["dataFile1.txt","dataFile2.txt"]
   print $ use fileContentsList other things

with an IO-free use function an option?

> Thanks,
> Tim

More information about the Beginners mailing list