1. 解释器
An interpreter finds the meaning of a program by traversing its parse tree.
讲义里给了一个例子:
We're going to write a recursive procedure called interpret that's going to walk over abstract syntax trees and figure out what they mean.
For example, you could write out a webpage that said, "Hello, Friend", and it would be a list of 2 elements.
示例代码:
def interpret(trees): # Hello, friend
for tree in trees: # Hello,
# ("word-element","Hello")
nodetype=tree[0] # "word-element"
if nodetype == "word-element":
graphics.word(tree[1])
elif nodetype == "tag-element":
# <b>Strong text</b>
tagname = tree[1] # b
tagargs = tree[2] # []
subtrees = tree[3] # ...Strong Text!...
closetagname = tree[4] # b
if(tagname <> closetagname):
graphics.warning()
else:
graphics.begintag(tagname, tagargs)
interpret(subtrees)
graphics.endtag()
复制代码
2. 变量与环境
There is a special global environment that can hold variable values. Other environments have parent pointers to keep track of nesting or scoping. Environments hold storage locations and map variables to values.
关于chained environment:遇见变量名先查自己的scope,再依照chain查找parent environment。
For this assignment, you should write a procedure:
eval_while(while_statement, evnironment)
Your procedure can (and should!) call those other procedures.
Higher Order Function
Suppose that we know that we will be filtering many lists down to only their odd
elements. Then we might want something like this:
# filter_odds = filter_maker(lambda n : n % 2 == 1)
# odds = filter_odds(numbers)
In this example, "filter_maker()" is a function that takes a function as # an argument and returns a function as its result. We say that filter_maker is a *higher order function*.