I get no runtime errors when I run the following code:
printReverse :: IO ()
printReverse = do
line <- getLine
when (not $ null line) $
do putStrLn $ reverse line
printReverse
return ()
But when I run the same code except that I replaced getLine
with readLn :: IO String
, I get a parse error.
Code:
printReverse :: IO ()
printReverse = do
line <- readLn :: IO String
when (not $ null line) $
do putStrLn $ reverse line
printReverse
return ()
Error:
*** Exception: user error (Prelude.readIO: no parse)
What's the difference here between getLine and readLn?
Look at the types.
readLn :: Read a => IO a
and
getLine :: IO String
readLn
parses the input according to the 'Read' format of the result type. This is the same format as show
.
So you're attempting to read
a Haskell String value, in show
format from input, which is confusing, unless the string is already in double-qyoted haskell format.
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