Question :
I wanted to record the output of my program straight into a file.
When I ran the code, it automatically generated a file with the output of this code instead of printing it on the screen.
A simple example:
func = do
writeFile "file.txt" show(calc)
calc = do return (1+1)
I do not even know if this is possible. I’m a beginner in Haskell and I still do not know how to use files.
Answer :
You should use the writeFile function to overwrite or appendFile to add to the end, described in section 7.1 of the Haskell Report .
Correcting your example (and specifying the types):
func :: IO ()
func = writeFile "file.txt" (show calc)
calc :: Integer
calc = 1 + 1
Explanation
When writing writeFile "file.txt" show(calc)
, you are calling writeFile
with 3 arguments: "file.txt"
, show
, and calc
result. The above version describes the correct behavior:
writeFile "file.txt" (show calc)
About calc
return
in Haskell has a different meaning than most languages. It does not mean return the value as a result of the function, but rather, “ inject a value into a type monadic . To “return” a value as in a conven- tional language, simply type the value you want to return:
calc = 1 + 1