Reputation: 25
I'm a haskell beginner and got stuck with IO action behavior.
main() :: IO()
retval = if something
then "foo"
else `return value of IO String action` i.e getLine
print retval
How can I make this code work??
Upvotes: 2
Views: 146
Reputation: 15954
Both branches of if
have to have the same type. Since "foo"
is String
, the else
part has to be a String
too (but not an IO String
).
You can do
retval = if something
then return "foo"
else getLine
in order to make all parts of the if
of type IO String
. Here, return
converts the string "foo"
to an IO
action which just returns "foo"
.
Then, you need to extract the String
back out of the IO String
because print
expects a string (i.e. you carry out the IO
action):
retval <- if something
then return "foo"
else getLine
Upvotes: 2
Reputation: 12060
Both the then
and else
value in an if
need to have the same type. You need to convert String
to IO String
.
The return
function will do this for you.
main:: IO()
main = do
retval <- if something
then return "foo"
else getLine
print retval
Note that because the this is of type IO a, you also need to assign the value of retVal using "<-", not let .. = ..
.
Upvotes: 1