2

I've been trying to set up a rather simple math parser, and it's been working fine. Only I can't figure out how to put in implied multiplication.

I've been using lark as an lalr(1) parser.

Here's most of the grammar:

?start: expression

?expression: sub

?sub: plus ("-" plus)*
?plus: times ("+" times)*
?times: divide ("*" divide)*
?divide: power ("/" power)?
?power: unary ("^" unary)*

?unary: positive
      | negative
      | atom

?atom: "(" expression ")"
     | numeric 
     | symbol

positive: "+" unary
negative: "-" unary

?numeric: FLOAT
        | INT

?symbol: WORD

%import common.WORD
%import common.INT
%import common.FLOAT
%import common.WS_INLINE
%ignore WS_INLINE

How would I go about adding in and implicit times operator?

Making the times "*" operator optional works fine, except that addition/subtraction doesn't work because it's interpreted as unary positive/negative instead. x - y is interpreted as x times -y, but it should be x sub y.

10
  • You're not including variables in your grammar, so the only possible case of implied multiplication is when you have (exp1)(exp2), right ? Commented May 9, 2020 at 5:00
  • @Niloct The symbols rule is for variables. Plus without parentheses too, I want 2 2 or 2 x y to count as multiplication. Commented May 9, 2020 at 5:03
  • Ah symbols, indeed. But 2 2 isn't clear to be a multiplication imho. Commented May 9, 2020 at 5:08
  • I agree, I think it's sorta confusing if there's no symbols there. But I'm trying to have somewhat similar syntax to Mathematica, so having it would be nice. Commented May 9, 2020 at 5:14
  • 1
    @weakit: That's not what terminal priority does, and even if it was, the reverse precedence would still be weird. + and - should have equal precedence, as should * and /. Commented May 9, 2020 at 5:30

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.