Search code examples
parsinghaskellparser-combinators

What are the reasons for using parser combinators?


I'm looking at the following approach to using parser combinators in Haskell. The author gives the following example of Parser Combinators:

windSpeed :: String -> Maybe Int
windSpeed windInfo =
    parseMaybe windSpeedParser windInfo

windSpeedParser :: ReadP Int
windSpeedParser = do
    direction <- numbers 3
    speed <- numbers 2 <|> numbers 3
    unit <- string "KT" <|> string "MPS"
    return speed

The author gives the following reasons for this approach:

  • easy to read (I agree with this)
  • similar format to the specification ie the parser itself is basically a description of what it parses (I agree with this)

I can't help but feel I'm missing some of the reasons for choosing parser combinators. Some benefit of either using Haskell, compile-time guarantees, elimination of runtime errors. Or some subsequent benefit when you starting parsing DSLs and using free monads.

My question is: What are the reasons for using parser combinators?


Solution

  • I see several benefits of using parser combinators:

    • Parser combinators are a generalization of hand-written top-down parsers. In the case that you hand-write a parser, use parser combinators to abstract away common patterns.
    • Unlike parser generators, parser combinators are potentially dynamic, allowing for decisions during runtime. This aspect may be useful if the language's grammar may be redefined based on the input.
    • Parsers are first-class objects.