traverse.py 798 B

123456789101112131415161718192021222324
  1. """ Branching Strategies to Traverse a Tree """
  2. from itertools import product
  3. from sympy.strategies.util import basic_fns
  4. from .core import chain, identity, do_one
  5. def top_down(brule, fns=basic_fns):
  6. """ Apply a rule down a tree running it on the top nodes first """
  7. return chain(do_one(brule, identity),
  8. lambda expr: sall(top_down(brule, fns), fns)(expr))
  9. def sall(brule, fns=basic_fns):
  10. """ Strategic all - apply rule to args """
  11. op, new, children, leaf = map(fns.get, ('op', 'new', 'children', 'leaf'))
  12. def all_rl(expr):
  13. if leaf(expr):
  14. yield expr
  15. else:
  16. myop = op(expr)
  17. argss = product(*map(brule, children(expr)))
  18. for args in argss:
  19. yield new(myop, *args)
  20. return all_rl