The main function complains about returning a monad without IO

import Debug.Trace

main = do
  trace "Main function parses, and returns - " "0"
  return ()

      

This throws an error like,

app.hs:3:1:
    Couldn't match expected type β€˜IO t0’ with actual type β€˜[()]’
    In the expression: main
    When checking the type of the IO action β€˜main’

      

If I am not mistaken, the module should work without returning. But with or without a return function, it doesn't work.

+3


source to share


2 answers


trace

is not an IO action! Its type:

trace :: String -> a -> a

      

so that the compiler will tell you what you define main

to be in the Monad of the list! So he complains that you define it as [()]

when it should be IO ()

.

Try using traceIO

(or just putStrLn

). Keep in mind that trace

- this is a debug function: it prints things unsafely and breaks out of the IO monad, which should never be done by a real working program.



(In general, you can avoid confusion by writing the type signatures yourself: always write your function main

as

main :: IO ()
main = do
  ...

      

and then the error you get is less confusing since GHC won't call the weird type.)

+11


source


Since your string trace

returns a list (string "0", which is of type [Char]

), you are actually calling the list monad, not the IO monad. The function return

for the list monad makes a singleton list from its argument: in this case [()]

.



Change the second argument to trace

be an IO action instead of a list.

+8


source







All Articles