Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between getLine and readLn

Tags:

io

haskell

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?

like image 543
Stanko Avatar asked Dec 24 '14 10:12

Stanko


1 Answers

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.

like image 51
Don Stewart Avatar answered Sep 30 '22 17:09

Don Stewart