Huy's Notes
Parser Combinator

Parser Combinator

#parser #compiler

Parser combinator is the method that use the principles of functional programming to compose the primitive parsers into larger ones.

To demo how is the composing works, let's build a parser that accepts either a digit or a letter.

We can start by building primitive parsers for digits and letter:

// primitive parser
const digit = (c) => !isNaN(+c) && +c >= 0 && +c <= 9;
const letter = (c) => c.match(/[a-zA-Z]/) !== null;

The combinator we need to use is an OR logic:

// combinator
const or = (left, right) => c => left(c) || right(c);

Finally, combine them together:

// combined parser
const isDigitOrLetter = or(digit, letter);

It's important to note that, the above example is not the way a parser actually works, as it's lack of the mechanism to handle error, and the way to traversal to next chunk of input.

For a more detailed example, check: Parser Combinator Demo on Gist.

Referred in


If you think this note resonated, be it positive or negative, please feel free to send me an email and we can talk.