Although I feel like a have a good understanding of Haskel IO and Monads, I am having a hard time understanding the following error message.
Consider the following simple function in Haskell
testf :: Show a => a -> String
testf x = show x
I tried implementing a variant that prints to the console by using an IO Monad
printtoscreen :: Show a => a -> IO()
printtoscreen x = putStrLn . show x
However, this yields the following error:
Couldn't match type ‘[Char]’ with ‘a0 -> String’ Expected type: a0 -> String Actual type: String
The correct version should omit explicitly stating the x
parameter
printtoscreen :: Show a => a -> IO()
printtoscreen = putStrLn . show
I understand why the last code snippet works, but I cannot make sense out of the error message of the second code snippet, considering that it will also return a string to putStrLn
So why should the x
parameter be omitted in the IO()
variant?
.
, the function composition operator, expects a function. show x
however is not a function; it's an evaluated value (of type [Char]
) by the time it's given to .
.
You'd have to use the function application operator instead:
printtoscreen x = putStrLn $ show x