The prefix
function is an example of a “parser combinator”: it’s a function that produces brand new parsers out of thin air given a little configuration. This prefix
parser combinator unlocks some extra power because we can scan off as many characters as we want off the beginning of a string, based on a predicate, and then do something later with it.
Although this is the first time we’ve called something a “parser combinator,” it’s not the first parser combinator that we’ve seen: map
, zip
, and flatMap
are all parser combinators, because they’re functions that take parsers as input and produce parsers as output. Even the literal
parser is a parser combinator because it takes some configuration up front (a literal string to parse) and returns a brand new parser that uses that configuration.
We’re beginning to see how parser combinators can enter our code and clean up things in the process: they allow us to solve more and more precise parsing problems by moving the lower-level, trickier parsing logic to these combinators. And then we can use them to build more specific kinds of parsers.
And this prefix
combinator was handy enough to clean up the oneOrMoreSpaces
and zeroOrMoreSpaces
parsers, but it’ll definitely help us build plenty more parsers in the future. In fact, that kind of prefix
checking is being done in a bunch of the parsers we’ve already defined.