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.
In Haskell it is also very easiest form of data type which can be used, easy to handle and create as well. String can be created by using double quotes (“”) inside this we can write our string or value that we want string type to be hold for us.
Haskell separates pure functions from computations where side effects must be considered by encoding those side effects as values of a particular type. Specifically, a value of type (IO a) is an action, which if executed would produce a value of type a .
If you have a String that you want to print to the screen, you should use putStrLn . If you have something other than a String that you want to print, you should use print . Look at the types! putStrLn :: String -> IO () and print :: Show a => a -> IO () .
If show is ok to print your elements, you can use putStr ( unlines $ map show [(1,"A"),(2,"B"),(3,"C"),(4,"D")]) but you can replace show by any funtion that'll take your custom type and return a string.
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 ()
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With