Creating files in Haskell

Asked

Viewed 650 times

4

I wanted to record the output of my program straight into a file. When I executed the code, I automatically generated a file with the outputs of this code instead of printing them on the screen.

A simple example:

func =  do
writeFile "file.txt" show(calc)
calc = do return (1+1)

I don’t even know if this is possible. I’m a beginner in Haskell and still don’t know how to use files.

2 answers

4


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 the return of imperative languages. I just think it’s worth adding that what the return in Haskell does is "put a certain value within a minimum Context", which are such monads. Example: when you are dealing with Lists, the lowest default context is the empty list [], then a return 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).

0

import System.IO

main :: IO ()
main = do 

       dado <- getLine
       outh <- openFile "saida.txt" WriteMode

       hPutStr outh (map toUpper dado)

       hClose outh

Browser other questions tagged

You are not signed in. Login or sign up in order to post.