Skip to content

Commit

Permalink
Fixed a small bug. Cleaned up the code.
Browse files Browse the repository at this point in the history
  • Loading branch information
wheerd committed May 18, 2017
1 parent 7561764 commit f7d80e9
Show file tree
Hide file tree
Showing 7 changed files with 29 additions and 14 deletions.
2 changes: 2 additions & 0 deletions matchpy/expressions/expressions.py
Original file line number Diff line number Diff line change
Expand Up @@ -585,6 +585,7 @@ def __copy__(self) -> 'Operation':
Operation.register(set)
Operation.register(frozenset)


class AssociativeOperation(metaclass=ABCMeta):
@classmethod
def __subclasshook__(cls, C):
Expand All @@ -602,6 +603,7 @@ def __subclasshook__(cls, C):
return C.commutative
return NotImplemented


CommutativeOperation.register(set)
CommutativeOperation.register(frozenset)

Expand Down
6 changes: 6 additions & 0 deletions matchpy/expressions/functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
'is_anonymous', 'contains_variables_from_set', 'register_operation_factory', 'create_operation_expression'
]


def is_constant(expression):
"""Check if the given expression is constant, i.e. it does not contain Wildcards."""
if isinstance(expression, Operation):
Expand Down Expand Up @@ -46,13 +47,15 @@ def match_head(subject, pattern):
assert subject_head is not None
return issubclass(subject_head, pattern_head)


def preorder_iter(expression):
"""Iterate over the expression in preorder."""
yield expression
if isinstance(expression, Operation):
for operand in expression:
yield from preorder_iter(operand)


def preorder_iter_with_position(expression):
"""Iterate over the expression in preorder.
Expand All @@ -64,6 +67,7 @@ def preorder_iter_with_position(expression):
for child, pos in preorder_iter_with_position(operand):
yield child, (i, ) + pos


def is_anonymous(expression):
"""Returns True iff the expression does not contain any variables."""
if hasattr(expression, 'variable_name') and expression.variable_name:
Expand All @@ -72,6 +76,7 @@ def is_anonymous(expression):
return all(is_anonymous(o) for o in expression)
return True


def contains_variables_from_set(expression, variables):
"""Returns True iff the expression contains any of the variables from the given set."""
if hasattr(expression, 'variable_name') and expression.variable_name in variables:
Expand All @@ -93,6 +98,7 @@ def simple_operation_factory(op, args, variable_name):
# TODO: Add support for dicts
}


def register_operation_factory(operation, factory):
_operation_factories[operation] = factory

Expand Down
4 changes: 3 additions & 1 deletion matchpy/functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,9 @@

from multiset import Multiset

from .expressions.expressions import (Expression, Operation, Pattern, Wildcard, SymbolWildcard, AssociativeOperation, CommutativeOperation)
from .expressions.expressions import (
Expression, Operation, Pattern, Wildcard, SymbolWildcard, AssociativeOperation, CommutativeOperation
)
from .expressions.substitution import Substitution
from .expressions.functions import preorder_iter_with_position, create_operation_expression
from .matching.one_to_one import match
Expand Down
16 changes: 7 additions & 9 deletions matchpy/matching/many_to_one.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,9 @@
Digraph = None
from multiset import Multiset

from ..expressions.expressions import (Expression, Operation, Symbol, SymbolWildcard, Wildcard, Pattern, AssociativeOperation, CommutativeOperation)
from ..expressions.expressions import (
Expression, Operation, Symbol, SymbolWildcard, Wildcard, Pattern, AssociativeOperation, CommutativeOperation
)
from ..expressions.substitution import Substitution
from ..expressions.functions import is_anonymous, contains_variables_from_set, create_operation_expression
from ..utils import (VariableWithCount, commutative_sequence_variable_partition_iter)
Expand Down Expand Up @@ -109,10 +111,7 @@ def any(self):
def _internal_iter(self):
for pattern_index in self.patterns:
renaming = self.matcher.pattern_vars[pattern_index]
new_substitution = self.substitution.rename({
renamed: original
for original, renamed in renaming.items()
})
new_substitution = self.substitution.rename({renamed: original for original, renamed in renaming.items()})
pattern, label, _ = self.matcher.patterns[pattern_index]
valid = True
for constraint in pattern.global_constraints:
Expand Down Expand Up @@ -177,9 +176,6 @@ def _check_transition(self, transition, subject, restore_subject=True):

finally:
if restore_subject and subject is not None:
assert isinstance(
subject, Expression
), "Matching for sequence variables restores the subject on its own"
self.subjects.appendleft(subject)
self.constraints |= restore_constraints
self.patterns |= restore_patterns
Expand Down Expand Up @@ -376,7 +372,9 @@ def rename_variables(cls, expression, renaming):
if isinstance(expression, Operation):
if hasattr(expression, 'variable_name'):
variable_name = renaming.get(expression.variable_name, expression.variable_name)
return create_operation_expression(expression, [cls.rename_variables(o, renaming) for o in expression], variable_name=variable_name)
return create_operation_expression(
expression, [cls.rename_variables(o, renaming) for o in expression], variable_name=variable_name
)
operands = [cls.rename_variables(o, renaming) for o in expression]
return create_operation_expression(expression, operands)
elif isinstance(expression, Expression):
Expand Down
8 changes: 6 additions & 2 deletions matchpy/matching/one_to_one.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@

from multiset import Multiset

from ..expressions.expressions import (Expression, Pattern, Operation, Symbol, SymbolWildcard, Wildcard, AssociativeOperation, CommutativeOperation)
from ..expressions.expressions import (
Expression, Pattern, Operation, Symbol, SymbolWildcard, Wildcard, AssociativeOperation, CommutativeOperation
)
from ..expressions.constraints import Constraint
from ..expressions.substitution import Substitution
from ..expressions.functions import is_constant, preorder_iter_with_position, match_head, create_operation_expression
Expand Down Expand Up @@ -186,7 +188,9 @@ def _build_full_partition(sequence_var_partition: Sequence[int], subjects: Seque

if wrap_associative and len(operand_expressions) > wrap_associative:
fixed = wrap_associative - 1
operand_expressions = tuple(operand_expressions[:fixed]) + (create_operation_expression(operation, operand_expressions[fixed:]), )
operand_expressions = tuple(operand_expressions[:fixed]) + (
create_operation_expression(operation, operand_expressions[fixed:]),
)

result.append(operand_expressions)

Expand Down
4 changes: 3 additions & 1 deletion matchpy/matching/syntactic.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,9 @@
except ImportError:
Digraph = None

from ..expressions.expressions import (Expression, Operation, Symbol, SymbolWildcard, Wildcard, Pattern, AssociativeOperation, CommutativeOperation)
from ..expressions.expressions import (
Expression, Operation, Symbol, SymbolWildcard, Wildcard, Pattern, AssociativeOperation, CommutativeOperation
)
from ..expressions.substitution import Substitution
from ..expressions.functions import is_syntactic
from ..utils import slot_cached_property
Expand Down
3 changes: 2 additions & 1 deletion matchpy/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,8 @@ def weak_composition_iter(n: int, num_parts: int) -> Iterator[Tuple[int, ...]]:
yield tuple(v - u - 1 for u, v in zip(first + t, t + last))


_linear_diop_solution_cache = {} # type: Dict[Tuple[int, ...], List[Tuple[int, ...]]]
_linear_diop_solution_cache = {} # type: Dict[Tuple[int, ...], List[Tuple[int, ...]]]


def _make_variable_generator_factory(value, total, variables: List[VariableWithCount]):
var_counts = [v.count for v in variables]
Expand Down

0 comments on commit f7d80e9

Please sign in to comment.