Dependency Mapper

Practice Problem

Using pymbolic, write a piece of code that, given an expression, finds the set of variables that it depends on. There is already a dependency mapper implemented in pymbolic (see pymbolic/pymbolic/mapper/dependency.py). It may be educational to compare your solution with this existing code, but you'll likely get more out of this exercise if you try to do this on your own first.

Motivation

The goal of the dependency mapper is to search an expression for all variables it depends on. E.g. for an input x*y+z the output shall be something like set(["x", "y", "z"]). Hedge uses this type of mapper (and a large number of others) in order to provide an easy-accessible user interface.

Hints

  1. The following code should give you an overview of what the dependency mapper does:
    import pymbolic as p
    from pymbolic.mapper.dependency import DependencyMapper
    expr = p.parse("x**r*y+z+5")
    print "Dependency Mapper:", DependencyMapper()(expr)
  2. You will have to import the pymbolic.primitives:
    import pymbolic.primitives as primitives
  3. Start with initializing a set where you put in the variables.

  4. Search the expression for variables and constants. Add the variables to the set but don't add the constants.
  5. Also search the children of the expression for variables and constants.
  6. Try this expression: expr = p.parse("x**r*y+z+5"). Does it work? If it doesn't work, try to understand why and fix it.

More Information

When comparing your solution with the "official" version, think about extensibility:

Also see the Wikipedia article on the so-called "Visitor Pattern".

Hedge/Exercises/DependencyMapper (last edited 2013-01-16 23:15:22 by AndreasKloeckner)