Abhinav Singh
Abhinav Singh

Reputation: 241

Haskell write a list in file and read later

I am trying to write a list into a file and later on I want to read the file contents into the list as well.

So I have a list like this ["ABC","DEF"]

I have tried things like

hPrint fileHandle listName

This just prints into file "["ABC","DEF"]"

I have tried unlines but that is priniting like "ABC\nDEF\n"

Now in both the cases, I cant read back into proper list. The output file has quotes and because of which when I read, I get like this ["["ABC","DEF"]""] i.e a single string in list.

As I am not succeeding in this, I tried to write the list line by line, I tried to apply a map and the function to write the list k = map (\x -> hPrint fileSLC x) fieldsBefore, it is not doing anything, file is blank. I think if I write everything in separate line, I will be able to read like (lines src) later on.

I know whatever I am doing is wrong but I am writing the code on Haskell for second time only, last time I just a wrote a very a small file reading program. Moving from imperative to functional is not that easy. :(

Upvotes: 0

Views: 1032

Answers (2)

chi
chi

Reputation: 116139

Try using hPutStrLn and unlines instead of hPrint. The hPrint internally calls show which causes Strings to be quoted and escaped.

hPutStr fileHandle (unlines listName)

Alternatively, use a mapM or a forM. A verbose example is:

forM_ listName $ \string ->
   hPutStrLn string

This can be simplified ("eta-contracted", in lambda-calculus terminology) to

forM_ listName hPutStrLn

Upvotes: 3

Code-Apprentice
Code-Apprentice

Reputation: 83517

As you have seen, when you read from a file, you get a String. In order to convert this String into a list, you will need to parse it.

For k = map (\x -> hPrint fileSLC x) fieldsBefore to work, you need to use mapM or mapM_ instead of map.

Upvotes: 0

Related Questions