1

Would it be possible to write in a file without returning an IO() element in the function. For the moment, I am only able to write to a file by returning IO() in my function f.

f:: Type -> IO()
f sequent = do 
    --let result = ...
    let file = "tmp/log.txt"
    writeToFile file ("TIMES rule: " ++  (show result))


writeToFile :: FilePath -> String -> IO()
writeToFile file content = do 
    x <- SIO.readFile file
    writeFile file ("\n"++content)
    appendFile file x

Would it be possible to have something as follows instead,

f:: Type -> String
f sequent = do 
    --let result = ...
    let file = "tmp/log.txt"
    -- do without returning
    writeToFile file ("TIMES rule: " ++  (show result))
    -- return the result
    result
Polo
  • 89
  • 1
  • 8
  • 5
    No, the idea of `IO` is to encapsulate logic that has side-effects in an `IO` container. See for example https://stackoverflow.com/questions/12892814/how-to-convert-io-int-to-string-in-haskell `IO` is not the *result* of an `IO` action, you can think of it as a collection of steps to get a result. – Willem Van Onsem Dec 11 '21 at 21:33
  • 2
    In Haskell, any function that does IO must return an IO-related type. This is enforced by the type system, there's no way around it. – chi Dec 11 '21 at 21:42
  • Is there writeFile function not returning IO() in haskell ? – Polo Dec 12 '21 at 10:09
  • 1
    No, and there isn't supposed to be. – Matthias Berndt Dec 12 '21 at 11:41
  • Relevant: https://stackoverflow.com/a/46743512, https://wiki.haskell.org/Haskell_IO_for_Imperative_Programmers, https://wiki.haskell.org/Non-strict_semantics. – atravers Feb 19 '22 at 00:54
  • Related: https://stackoverflow.com/q/7154518, https://stackoverflow.com/q/41522491. – atravers Feb 19 '22 at 00:56

1 Answers1

4

This is intentional. The idea behind IO is that you can see from the type of the function whether it will perform side effects.

Matthias Berndt
  • 4,387
  • 1
  • 11
  • 25