2

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??

2 Answers 2

2

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 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for kind reply :) I understand now
1

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 .. = ...

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.