Question:
I wanted to write my program's output straight to a file. When I ran the code, it automatically generated a file with the outputs of this code instead of printing them to the screen.
A simple example:
func = do
writeFile "file.txt" show(calc)
calc = do return (1+1)
I don't even know if that's possible. I'm new to Haskell and I still don't know how to use files.
Answer:
You must use the function WriteFile to overwrite or appendfile to add at the end, as described in section 7.1 of the Haskell Report .
Fixing your example (and making the types explicit):
func :: IO ()
func = writeFile "file.txt" (show calc)
calc :: Integer
calc = 1 + 1
Explanation
By writing writeFile "file.txt" show(calc)
, you are calling writeFile
with 3 arguments: "file.txt"
, the show
function, and the result of calc
. The version above describes the correct behavior:
writeFile "file.txt" (show calc)
about calc
return
in Haskell has a different meaning than most languages. It doesn't mean to return the value as a result of the function, but rather, " injecting a value into a monadic type ". To "return" a value as in a conventional language, simply write the value you want to return:
calc = 1 + 1