How to write list to file?
I am trying:
import System.IO
saveArr = do
outh <- openFile "test.txt" WriteMode
hPutStrLn outh [1,2,3]
hClose outh
but it doesn't works... output:
No instance for (Num Char) arising from the literal `1'
EDIT开发者_StackOverflow中文版
OK hPrint
works with ints but what about float number in array? [1.0, 2.0, 3.0]
?
hPutStrLn
can only print strings. Perhaps you want hPrint
?
hPrint outh [1,2,3]
Arrays, Lists and Strings exists only in imagination of programmer and as a term in some languages.
File is a sequence of bytes, so when you want to write something to it you should encode that imaginary String/List/Array into sequence of bytes (by show
or by something from Storable
etc).
As well terminal is a sequence of bytes which is encoded representation of actions needed to show something to user.
You have many ways to encode. You can make CSV representation of array by foldr (\a b -> a (',' : b)) "\n" (map shows [1,2,3])
or you may want to print it show [1,2,3]
derive Binary for your type, then write the data in binnary form using 'encodeFile' from the Data.Binary package. This is similar to writing the data out as a bytestring.
精彩评论