def evaluate_sequence(actions, environment): if is_null(actions): raise SyntaxError("Empty sequence") if is_null(cdr(actions)): return g.eval(car(actions), environment) g.eval(car(actions), environment) return evaluate_sequence(cdr(actions), environment)
def expand(clauses): if is_null(clauses): raise ValueError("COND: no values matched") if is_else_clause(car(clauses)): if is_null(cdr(clauses)): return cond_clause_consequent(car(clauses)) else: raise SyntaxError(f"COND: ELSE not last {cond_exp}") return make_if( cond_clause_predicate(car(clauses)), cond_clause_consequent(car(clauses)), expand(cdr(clauses)), )
def sequence_begin(seq): if is_null(seq): return seq if is_null(cdr(seq)): return car(seq) actions = tuple( map(lambda exp: begin_actions(exp) if is_begin(exp) else (exp, ), seq)) return make_begin(tuple(item for sublist in actions for item in sublist))
def loop(alts=alternative_execs): if is_pair(alts): return continue_with( car(alts), env, succeed, lambda *args: continue_with(loop, cdr(alts)), ) else: return continue_with(fail)
def display_pair(p, parens=True): if parens: print("(", end="") display(car(p)) if is_null(cdr(p)): # no more items pass elif is_pair(cdr(p)): print(" ", end="") display_pair(cdr(p), parens=False) else: print(" . ", end="") display(cdr(p)) if parens: print(")", end="")
def operator(exp): return car(exp)
def cond_clause_predicate(clause): return car(clause)
def initialize_repl(): global THE_GLOBAL_ENVIRONMENT THE_GLOBAL_ENVIRONMENT = make_initial_environment() def check_repl_initialized(): if THE_GLOBAL_ENVIRONMENT == "not initialized": raise RuntimeError("Interpreter not initialized. Run init() first.") if __name__ == "__main__": a = Symbol("a") b = Symbol("b") c = Symbol("c") print((a, b, c)) print(car((1, 2, 3)), cdr((1, 2, 3))) x = cons(1, (2, 3, 4)) print(x) print(car(x), cdr(x), cdr(cdr(x))) quote = Symbol("quote") x = Symbol("x") begin = Symbol("begin") # print(g.eval(((Symbol('lambda'), (x,), x), 42), ())) print(g.eval((begin, 1, 2, 3), ())) init()