Reading in the contents of a variable number of files

Previous Topic Next Topic
 
classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

Reading in the contents of a variable number of files

Tim Perry-2
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....

Thanks,
Tim
Reply | Threaded
Open this post in threaded view
|

Reading in the contents of a variable number of files

Daniel Fischer-4
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).

Is

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