15

How do we print the output of a function that returns an IO String to the stdout? I am not able to use show or print.

2 Answers 2

25

If you want to print the result of the function foo :: Int -> IO String (for example), you can do

main = do
    str <- foo 12
    putStrLn str

or, without the do-notation,

main = foo 12 >>= putStrLn.

The do-notation is syntactic sugar for the second, which uses the fundamental (>>=) combinator, which has the type

(>>=) :: Monad m => m a -> (a -> m b) -> m b

IO is an instance of the Monad class, so you can use it here.

foo :: Int -> IO String
foo 12 :: IO String

putStrLn :: String -> IO ()

(foo 12) >>= putStrLn :: IO ()
Sign up to request clarification or add additional context in comments.

1 Comment

Generally, you could say ´printio = do oi <- io \n print io´
6

How do we print the output of a function that returns an IO String to the stdout?

Well let's see. Here's a function that returns an IO String:

dumbFunction :: a -> IO String
dumbFunction x = getLine

dumbFunction is a dumb function (but a function nonetheless!). It ignores its input, and then returns getLine, which has the type IO String.

So you tell me, how do you print getLine :: IO String? The answer is, you don't! This is what we call an "IO action". Note that an IO action is not a function, because it does not take input. (However, IO actions might acquire input from, well, IO operations such as reading stdin, as getLine does. But it is not considered a "function" because it does not accept any traditional input)

So instead of printing out the action itself, you probably want to run the action, and then print the result. This can be done as Daniel Fischer described (with <-, which can be thought of as the "run" operator).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.