Associativity of operators

41 views
Skip to first unread message

Paul Royik

unread,
Aug 12, 2024, 2:37:57 PM8/12/24
to sympy
Hello.

I'm trying to parse the ">>" symbol as implies operator.

I've managed to parse p>>q>>r as Implies(Implies(p,q), r) using sympy functions as a base (possibly, there is a built-in solution that I'm not aware of), but it appeares that Implies is a right-associative operator.

Are there some functions in Sympy that allow me to parse p>>q>>r as Implies(p, Implies(q,r))?

Thank you.

Aaron Meurer

unread,
Aug 12, 2024, 3:20:25 PM8/12/24
to sy...@googlegroups.com
There's no way to change the Python operator precedence, but you can
modify the string parsing in parse_expr() by passing in a transformer
for the tokenizer.

Aaron Meurer
> --
> You received this message because you are subscribed to the Google Groups "sympy" group.
> To unsubscribe from this group and stop receiving emails from it, send an email to sympy+un...@googlegroups.com.
> To view this discussion on the web visit https://groups.google.com/d/msgid/sympy/38551028-8785-4ecb-a407-e58b7ea4b037n%40googlegroups.com.

Paul Royik

unread,
Aug 12, 2024, 3:46:00 PM8/12/24
to sympy
Thank you.

Can you point me how it could look like?

Thank you.

Aaron Meurer

unread,
Aug 12, 2024, 6:09:29 PM8/12/24
to sy...@googlegroups.com
You need to write a function that takes the stream of tokens and
returns a new stream of tokens which are re-parenthesized. For
example, ['p', '>>', 'q', '>>', 'r'] would become ['p', '>>', '(',
'q', '>>', 'r', ')']. But you'd also need to handle the case where one
of the operands is itself parenthesized or involves operators with a
higher precedence than >>.

Unfortunately, this isn't the simplest thing in the world to do. It
would probably be useful to add something to SymPy that lets you take
a general transformer that can adjust operator precedence and
associative rules. Or we should write our own custom parser for
parse_expr that makes it easier to make these sorts of changes (both
of these are things we would like to see, but not easy tasks).

Here are examples of existing token transformers for parse_expr
https://github.com/sympy/sympy/blob/master/sympy/parsing/sympy_parser.py.
My guide to the Python tokenizer module can also be useful
https://www.asmeurer.com/brown-water-python/

Aaron Meurer


Aaron Meurer
> To view this discussion on the web visit https://groups.google.com/d/msgid/sympy/ba92bd20-1a6c-4eff-9c8a-b3402125365cn%40googlegroups.com.

Paul Royik

unread,
Aug 13, 2024, 1:39:35 AM8/13/24
to sympy
Thank you very much!
Reply all
Reply to author
Forward
0 new messages