How to write a list to a file?

I'm trying to:

saveArr = do outh <- openFile "test.txt" WriteMode hPutStrLn outh [1,2,3] hClose outh 

but it does not work ... output:

There is no instance for (Num Char) arising from the literal `1 '

hPrint OK hPrint works with ints, but what about a floating-point number in an array? [1.0, 2.0, 3.0] ?

+4
source share
3 answers

hPutStrLn can print only lines. Maybe you want hPrint ?

 hPrint outh [1,2,3] 
+7
source

Arrays, lists, and strings exist only in the imagination of the programmer and as a member in some languages.

A file is a sequence of bytes, so when you want to write something, you have to encode this imaginary String / List / Array string into a sequence of bytes (via show or something from Storable , etc.).
In addition, the terminal is a sequence of bytes, which is an encoded representation of the actions necessary to show something to the user.

You have many coding methods. You can make a CSV representation of the array on foldr (\ab -> a (',' : b)) "\n" (map shows [1,2,3]) or you can print it show [1,2,3]

+2
source

output binary code for your type, and then write the data in binary form using "encodeFile" from the Data.Binary package. This is similar to writing data as a byte.

+1
source

Source: https://habr.com/ru/post/1310716/


All Articles