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.
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.
- 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)
- You will have to import the pymbolic.primitives:
import pymbolic.primitives as primitives
Start with initializing a set where you put in the variables.
- Search the expression for variables and constants. Add the variables to the set but don't add the constants.
- Also search the children of the expression for variables and constants.
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.
When comparing your solution with the "official" version, think about extensibility:
- What happens if a new expression node type gets added to the code?
- What happens if someone wants to change one minor aspect of the mapper's behavior?
Also see the Wikipedia article on the so-called "Visitor Pattern".