Slide 20
Slide 20 text
Example: subs
def crawl(expr, func, *args, **kwargs):
"""Crawl the expression tree, and apply func to every node"""
val = func(expr, *args, **kwargs)
if val is not None:
return val
new_args = (crawl(arg, func, *args, **kwargs) for arg in expr.args)
return expr.func(*new_args)
def sub_func(expr, sub_dict):
"""Perform direct matching substitution"""
if expr in sub_dict:
return sub_dict[expr]
elif not expr.args:
return expr
# Compose the subs function
subs = lambda x, sub_dict: crawl(x, sub_func, sub_dict)