Parser combinators
Parsers are everywhere. A Scala program text needs to be parsed first for it to run. We parse a JSON to get at the data structure. We then try to make sense of the text and pull out something useful from it.
Parsing may succeed or fail. For example, the text may not have what we are looking for. It may have something else equally interesting. At times, we'll want to retry different parsers on a piece of text, hoping that one of them might succeed.
A parser looking for a number in the string how do you do?
will fail as there is no number. However, a parser looking for greetings will succeed.
The idea behind Scala's Parser combinators is to compose more complex parsers from simpler ones. We compose parsers that can be tried one after another or one instead of another.
Here is a simple example of parsing a double from a string:
scala> :paste // 1 // Entering paste mode (ctrl-D to finish) import scala.util.parsing.combinator._ // 2 object ParseANumber extends RegexParsers...