HPAC / matchpy

A library for pattern matching on symbolic expressions in Python.
MIT License
164 stars 25 forks source link

Inconsistent output of match_anywhere #60

Closed flex361 closed 4 years ago

flex361 commented 4 years ago

Function match_anywhere in one_to_one.py produces different result when using patterns refering to the same subexpression but with different amount of hierarchical context:

using these functions:

plus = Operation.new('plus', Arity.variadic, associative=True, commutative=True)
f_B = Operation.new('B', Arity.nullary, associative=False, commutative=True)

and having the subject:

plus( f_B(), f_B(), f_B() );

these to pattern result differently:

pattern_1 = Pattern(f_B(), rest[0] );
pattern_2 = Pattern(plus( f_B(), rest[0] ) );

using pattern_1 results in:

{} matched with (0,)
{} matched with (1,)
{} matched with (2,)

using pattern_2 results in:

{rest0 ↦ {B(), B()}} matched with ()

I would expect pattern_2 to also result in 3 times the same match. One for every f_B() pattern_2 can refer to.

hbarthels commented 4 years ago

To me, it looks like the problem is how you are using the Pattern class for pattern_1: Only the first argument is the actual pattern expressions, all the remaining arguments are expected to be constraints (see the docs). As a result, the actual pattern in the first case is only f_B(), which is correctly found three times. The second pattern is quite different, so you also get a different match.

Is rest[0] a sequence variable? It would be helpful if you could provide those details.

What do you want pattern_1 to look like? By itself, f_B(), rest[0] (without any enclosing operator) is not a valid expression.

I am a bit surprised that pattern_1 = Pattern(f_B(), rest[0]) doesn't produce an error. Perhaps it would be good if it did.

flex361 commented 4 years ago

rest[0] is indeed a sequence variable. I wanted pattern_1 to look like pattern_2. The reason I wrote pattern_1 this way is that I found this different behavior per accident and this result looked exactly like what I am looking for.

hbarthels commented 4 years ago

Do you know now how to achieve what you are looking for? If yes, I will close this issue.

flex361 commented 4 years ago

Yes, now i know what i needed to know. Thank you.