In my program, I generate a list of numbers:
data = [2,3,2,5,2,7,2,3,2,11 ... ]
Now I want to write this list of numbers as a single-line comma-separated string in a file. I know I can use writeFile
combined with Show
:
writeFile "data.txt" $ show $ data
However, this will also print the square brackets at the beginning and end. Now I could remove the first and last characters from the string Show data
by using reverse
, but this is inefficient. At some point, the program is already traversing the list in order to write the characters to the file, so how can I make sure it doesn't write the first and last characters without doing an unnecessary traversal?
Will this do the job most efficiently?
writeFile "data.txt" $ drop 1 $ takeWhile (\c -> c/= ']') $ show data