[Haskell-beginners] Getting a specified number of lines from stdin

KwangYul Seo kwangyul.seo at gmail.com
Mon Mar 7 12:03:12 UTC 2016


Hi,

Your code does not work because sequence function can't be lazy due to the
strictness of IO monad's >>= operation.

Here's a more verbose version:

readWhile :: (String -> Bool) -> IO [String]
readWhile p = do
  line <- getLine
  if p line
    then do
      lines <- readWhile p
      return $ line : lines
    else
      return []

ghci> readWhile (/="")
foo
bar

["foo","bar"]


On Sun, Mar 6, 2016 at 7:38 PM, Nicolaas du Preez <njdupreez at yahoo.com>
wrote:

> Good day All,
>
> Why does
>
>     liftM (take 5) $ sequence $ repeat getLine
>
> not stop at reading only 5 lines from stdin but keeps on reading more?
>
> What I’m really trying to achieve is to get input from the user until
> an empty line is read with the code below.  But this doesn’t work
> as I expected, similar to the above.
>
>     liftM (takeWhile (/= "")) $ sequence $ repeat getLine
>
>
> Regards,
> Nicolaas du Preez
>
> _______________________________________________
> Beginners mailing list
> Beginners at haskell.org
> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.haskell.org/pipermail/beginners/attachments/20160307/7183cab3/attachment.html>


More information about the Beginners mailing list