<s> """<STR_LIT>""" <EOL> from __future__ import print_function , division <EOL> from sympy . core . compatibility import get_function_name <EOL> identity = lambda x : x <EOL> def exhaust ( rule ) : <EOL> """<STR_LIT>""" <EOL> def exhaustive_rl ( expr ) : <EOL> new , old = rule ( expr ) , expr <EOL> while ( new != old ) : <EOL> new , old = rule ( new ) , new <EOL> return new <EOL> return exhaustive_rl <EOL> def memoize ( rule ) : <EOL> """<STR_LIT>""" <EOL> cache = { } <EOL> def memoized_rl ( expr ) : <EOL> if expr in cache : <EOL> return cache [ expr ] <EOL> else : <EOL> result = rule ( expr ) <EOL> cache [ expr ] = result <EOL> return result <EOL> return memoized_rl <EOL> def condition ( cond , rule ) : <EOL> """<STR_LIT>""" <EOL> def conditioned_rl ( expr ) : <EOL> if cond ( expr ) : <EOL> return rule ( expr ) <EOL> else : <EOL> return expr <EOL> return conditioned_rl <EOL> def chain ( * rules ) : <EOL> """<STR_LIT>""" <EOL> def chain_rl ( expr ) : <EOL> for rule in rules : <EOL> expr = rule ( expr ) <EOL> return expr <EOL> return chain_rl <EOL> def debug ( rule , file = None ) : <EOL> """<STR_LIT>""" <EOL> if file is None : <EOL> from sys import stdout <EOL> file = stdout <EOL> def debug_rl ( * args , ** kwargs ) : <EOL> expr = args [ <NUM_LIT:0> ] <EOL> result = rule ( * args , ** kwargs ) <EOL> if result != expr : <EOL> file . write ( "<STR_LIT>" % get_function_name ( rule ) ) <EOL> file . write ( "<STR_LIT>" % ( expr , result ) ) <EOL> return result <EOL> return debug_rl <EOL> def null_safe ( rule ) : <EOL> """<STR_LIT>""" <EOL> def null_safe_rl ( expr ) : <EOL> result = rule ( expr ) <EOL> if result is None : <EOL> return expr <EOL> else : <EOL> return result <EOL> return null_safe_rl <EOL> def tryit ( rule ) : <EOL> """<STR_LIT>""" <EOL> def try_rl ( expr ) : <EOL> try : <EOL> return rule ( expr ) <EOL> except Exception : <EOL> return expr <EOL> return try_rl <EOL> def do_one ( * rules ) : <EOL> """<STR_LIT>""" <EOL> def do_one_rl ( expr ) : <EOL> for rl in rules : <EOL> result = rl ( expr ) <EOL> if result != expr : <EOL> return result <EOL> return expr <EOL> return do_one_rl <EOL> def switch ( key , ruledict ) : <EOL> """<STR_LIT>""" <EOL> def switch_rl ( expr ) : <EOL> rl = ruledict . get ( key ( expr ) , identity ) <EOL> return rl ( expr ) <EOL> return switch_rl <EOL> identity = lambda x : x <EOL> def minimize ( * rules , ** kwargs ) : <EOL> """<STR_LIT>""" <EOL> objective = kwargs . get ( '<STR_LIT>' , identity ) <EOL> def minrule ( expr ) : <EOL> return min ( [ rule ( expr ) for rule in rules ] , key = objective ) <EOL> return minrule </s>
