liveBook · Manning

takeWhile

As explained in Learn Haskell by Example

takeWhile is an Attoparsec parser combinator that consumes consecutive input characters satisfying a predicate.

takeWhile is an Attoparsec combinator that reads consecutive input bytes or characters while a predicate remains true, returning the consumed input. The parser stops before the first character that fails the predicate. section 12.2.1

Use the variant that matches the input and predicate:

  • Data.Attoparsec.ByteString.takeWhile :: (Word8 -> Bool) -> Parser ByteString reads bytes. section 12.2.1
  • Data.Attoparsec.ByteString.Char8.takeWhile works with Char predicates, which is convenient for ASCII-oriented parsing. section 12.2.1
  • Unlike skipWhile, takeWhile preserves the matching input as a ByteString. section 12.2.1

Reading a PNM comment

A PNM comment begins with '%' and continues until a newline. Combine char with takeWhile to consume its body: comment :: Parser BS.ByteString; comment = C8.char '%' >> C8.takeWhile (/= '\n'). This parser consumes the percent sign and all non-newline characters, leaving the newline for subsequent parsing. section 12.2.2

Listing 12.21 A parser for comments
comment :: Parser BS.ByteString
comment = C8.char '%' >> C8.takeWhile (/= '\n')     #1

View the complete comment parser used for PNM header parsing. section 12.2.2

How Learn Haskell by Example covers it

How deep it goes
Defines the predicate-based API and demonstrates one parser, but does not develop its internals or broader edge-case behavior.
Examples
Uses a PNM comment parser that reads '%' followed by characters until a newline.
What it assumes
Assumes basic Haskell parser types and predicates while introducing takeWhile within an Attoparsec parsing task.
What you can do after
Build comment and similar delimiter-based parsers by combining takeWhile with Attoparsec character parsers.
How it connects
Connects takeWhile with Attoparsec, Parser, ByteString, Char8, predicates, char, skipWhile, and PNM parsing.

Also explained in

Compare how 2 books explain takeWhile →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Haskell by Example. The section links point to the parts of the book it draws on.