[Haskell-beginners] Picking apart getLine

Angus Comber anguscomber at gmail.com
Tue Jan 7 16:54:15 UTC 2014


Before looking at getLine, I can understand this:

getnumber :: IO Int
getnumber = do x <- getChar
               if isDigit x then
                     return (ord x - ord '0')
               else
                     return 0

OK, it is not a very useful function but at least I understand it.  return
is required so that the function returns an IO Int.

But I don't understand this:

getLine' :: IO String
getLine'        = do x <- getChar
                     if x == '\n' then
                       return []
                     else
                       do
                         xs <- getLine'
                         return (x:xs)


I can understand what will happen if a user enters a newline (only).
 return [] brings the empty list into the monadic world.

But what is happening if x is not a newline?

xs <- getLine' will recursively call getChar and retrieve another character
from the input stream.  But it will do this BEFORE the return (x:xs) - so
what is happening to all the head elements in the list - the x element?

It is difficult to picture in my mind how this is working.  I understand
recursion but this looks tricky.

Can someone help me work this out?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/beginners/attachments/20140107/b8c21697/attachment.html>


More information about the Beginners mailing list