Parser combinators must be one of the best things to come out of functional programming. They let you define intuitive parsers right in the code, without any need for pre-processors.
Like this:
letparser=function1<^>parser1<*>parser2<|>parser3
where function1 and parser3 return the same type.
parser will pass the input to parser1 followed by parser2, pass their results to function1 and return its result. If that fails it will pass the original input to parser3 and return its result.
FootlessParser is a simple and pretty naive implementation of a parser combinator in Swift. It enables infinite lookahead, non-ambiguous parsing with error reporting.
Footlessparser is using operators for map ( <^> ), flatmap/bind ( »- ) and apply ( <*> ). Luckily the Runes framework has already defined these, and implemented them for optionals and arrays.
Each parse returns a Result, which has either a tuple containing the output and the remaining unparsed part of the input, or an error description if parsing fails. The Result enum is in the Llamakit framework, later replaced by antitypical/Result.
Create a new project in Xcode, and select OS X framework if it is for both iOS and OS X. The iOS framework target can be added later, besides OS X frameworks are more practical for unit testing. No simulators needed.
where parser will pass the input to parser1 followed by parser2, pass their results to function1 and return its result. If that fails it will pass the original input to parser3 and return its result.
Before Swift my only contact with functional programming was a couple of half-hearted attempts at reading Erlang, all of them resulting in me running away screaming, clutching my aching head. But learning functional concepts in Swift proved far easier, probably because the syntax is closer to what I was used to. So I read Functional Programming in Swift and everything was well and good until one of the last chapters, “Parser Combinators”, and the headache was back. Luckily I managed to stay quiet and in place this time. I downloaded the code for the chapter, turned it into a framework and hacked away until I had implemented a CSV parser, but I still didn’t really understand it.