[Haskell-beginners] Picking apart getLine

David McBride toad3k at gmail.com
Tue Jan 7 17:15:02 UTC 2014


You have the idea.  The x is fetched with getChar, then it sits in
that context until the return is executed.

So the x is sitting there and getLine' is called.  It makes its own x
via getChar, then maybe getLine' is called again.  Each getLine' sits
there with its own version of x until finally the last getLine' get's
a \n, and then returns a [].  Then the whole thing unwinds by
prepending x to [], then x to [x], then another x to [x,x], until
there are no more x's to return, and you have the whole string.

Hopefully that paragraph makes sense.

On Tue, Jan 7, 2014 at 11:54 AM, Angus Comber <anguscomber at gmail.com> wrote:
> 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?
>
>
> _______________________________________________
> Beginners mailing list
> Beginners at haskell.org
> http://www.haskell.org/mailman/listinfo/beginners
>


More information about the Beginners mailing list