You must use the function writeFile to overwrite or appendFile to add to the end, described in Section 7.1 of the Haskell Report.
Correcting your example (and spelling out 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"
, the function show
, and the result of calc
. The above version describes 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 yes, "inject a value into a monadic type". To "return" a value as in a non-constitutional language, simply write the value you want to return:
calc = 1 + 1
+1 for pointing out that
return
has nothing to do with thereturn
of imperative languages. I just think it’s worth adding that what thereturn
in Haskell does is "put a certain value within a minimum Context", which are suchmonads
. Example: when you are dealing with Lists, the lowest default context is the empty list[]
, then areturn 1 :: [Int]
will return to you[1]
(its encapsulated value in the Context of an Int list). Yes, it’s the same thing you said @Rudy, but maybe it’s clearer to some people (I included).– tayllan