atlantis
atlantis

Reputation: 3126

Writing an IO String to stdout in Haskell

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.

Upvotes: 15

Views: 11826

Answers (2)

Dan Burton
Dan Burton

Reputation: 53715

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

Upvotes: 6

Daniel Fischer
Daniel Fischer

Reputation: 183978

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 ()

Upvotes: 25

Related Questions