Reputation: 5114
I have a simple function like:
nth :: Integer -> Integer
And I try to print it's result as follows:
main = do
n <- getLine
result <- nth (read n :: Integer)
print result
The following error is generated:
Couldn't match expected type `IO t0' with actual type `Integer'
In the return type of a call of `nth'
In a stmt of a 'do' expression:
result <- nth (read n :: Integer)
Also tried with putStrLn
and a lot of other combinations with no luck.
I can't figure it out and I would need some help, being that I don't fully understand how stuff works around these IO
s.
Upvotes: 21
Views: 38730
Reputation: 704
The do
syntax unwraps something within a monad. Everything on the right hand side of the arrow must live within the IO monad, otherwise the types don't check. An IO Integer
would be fine in your program. do
is syntactic sugar for the more explicit function which would be written as follows:
Recall that (>>=) :: m a -> (a -> m b) -> m b
main = getLine >>= (\x ->
nth >>= (\y ->
print y))
But nth
is not a monadic value, so it doesn't make sense to apply the function (>>=)
, which requires something with the type IO a
.
Upvotes: 7
Reputation: 64750
nth
is a function, not an IO
action:
main = do
n <- getLine
let result = nth (read n :: Integer)
print result
Upvotes: 20