7. An Example
Consider: (define test 6) More on this later
(+ test 1) ['+', 'test', '1']
Recall:
def evalApplication(expr, env):
subexprs = expr
subexprvals = map (lambda sexpr: meval(sexpr, env), subexprs)
return mapply(subexprvals[0], subexprvals[1:])
Because of map, meval is called with 'test' sub-expression too !
'test' is an instance of string object, so isinstance evaluates to true
In isName from previous slide
8. What about evalName?
def evalName(expr, env):
assert isName(expr)
return env.lookupVariable(expr)
To fully understand this, we need to understand how our Environment works
But first ...
9. For a Chance To Earn Some Candy
On the first US flag, why were the 13 stars sewn in a circle?
10. Back To Environment
class Environment:
def
__init__(self, parent):
self._parent = Start Off With Empty Dictionary
parent
self._frame = {}
def
addVariable(self, name, valu
e):
self._frame[name] =
The global environment has no parent
value
The frame contains the places that have been defined
Places are name-value tuples, but values can change
def
lookupVariable(self, name):
...
11. Recall the Lookup Rules
First, we search the current environment’s frame for
a place with a name that matches the name in the
expression. If we have a match, the value in that
place is the value of the expression
Else we evaluate the name expression in the
parent environment.
If the current evaluation environment has no
parent, the name is not defined and the
expression evaluates to an error.
14. lookupVariable Cont.
def lookupVariable(self, name):
if self._frame.has_key(name):
return self._frame[name]
elif (self._parent):
return self._parent.lookupVariable(name)
else:
evalError('Undefined name: %s' % (name))
public Object lookupVariable(String name) throws EvalError{
if (frame.containsKey(name)) {
return frame.get(name);
}
else if (parent != null) {
return parent.lookupVariable(name);
}
else {
throw new EvalError("Undefined name "+name);
}
}
15. evalDefinition:
def evalDefinition(expr, env):
assert isDefinition(expr)
if len(expr) != 3:
evalError ('Bad definition: %s' % str(expr))
name = expr[1]
if isinstance(name, str):
value = meval(expr[2], env)
env.addVariable(name, value)
else:
evalError ('Bad definition: %s' % str(expr))
16. Charge
You should have a good understanding
of the Charme interpreter now.
We have not explained in detail all primitive operations,
parsing and evaluating lambdas.
Though they should be easy to understand now.
Don't Forget - PS7 is due Wednesday