In the last three episodes (part 1, part 2, part 3) we set the stage for parsing.
First we showed that parsing is such a common and important task that Apple provides multiple solutions for parsing in both Swift and Foundation. Everything from initializers that will parse a string into a specific type, such as integers, doubles, UUIDs and URLs, to general purpose parsers like the Scanner
type, which allows us to incrementally parse various types off the beginning of strings, to regular expressions.
All of those parsers are handy and powerful, but they have some serious drawbacks, such as they are not really defined for code reusability or composability. So we took a step back, and provided a precise definition of what a parser is. It was literally a function that takes an in-out substring as input and returns an optional, first class value as output.
With that simple definition we had a succinct, efficient description of parsing, and we even made a few domain-specific parsers that did just a little bit of parsing, but did it well. Then we pieced those parsers together and made a pretty complicated parser yet the code was very descriptive and straightforward. It even fixed some subtle edges cases that a hand rolled parser had missed.
But even though we accomplished a lot in the last 3 episodes, it doesn’t even scrape the surface of what functional programming has to say about parsing. Today we’ll really start to dig into that topic by seeing precisely how one glues together parsers to form ever more complex parsers. Once we unlock a few of the basic shapes we will be able to create incredibly powerful parsers with very little work, and the sky will be the limit!