DEV Community

loading...

Discussion on: Pratt Parsing

Collapse
jrop profile image
Jonathan Apodaca Author • Edited

Good question! First, we define the BP of ")" to be a low number that will always be guaranteed to stop the current parse-run. For example:

bp(")") = 0

Next, we define the NUD of "(" to read the next expression, and then eat the closing ")":

nud("(") => {
  const e = expr(0);
  lexer.expect(")");
  return e;
}

For a fully working example, I have implemented this in my JavaScript calculator expression evaluator:

github.com/jrop/pratt-calculator/b...

Collapse
kryptocrash profile image
KryptoCrash

That's pretty nice! I actually got around with just setting a var pLayer to 0. Incrementing it for every open parenthese and decrementing it for every closing parenthese. Then just applied a bias of pLayer*3 to the operator precedence. Would this run in faster time?

Thread Thread
jrop profile image
Jonathan Apodaca Author

It's hard to say without running some performance benchmarks.

Forem Open with the Forem app