One-Slide Summary • Building an interpreter is a fundamental idea in computing. Eval and Apply are mutually recursive . • The most complicated parts of meval are the handling of function abstraction (lambda) and function application. • The most complicated part of mapply is handling a non-primitive procedure: create a new environment, add variables to that environment corresponding to the arguments, and then apply the procedure body in that new environment. • In lazy evaluation , a value is not computed until it is Laziness needed. A thunk is a piece of code that performs a Laziness delayed computation. #2 def meval(expr, env): Outline if isPrimitive(expr): return evalPrimitive(expr) elif isConditional(expr): • Eval return evalConditional(expr, env) • Apply elif isLambda(expr): • Lazy return evalLambda(expr, env) elif isDefinition(expr): • Thunk evalDefinition(expr, env) elif isName(expr): return evalName(expr, env) elif isApplication(expr): return evalApplication(expr, env) else: evalError ("Unknown expression type: " + str(expr)) #3 #4 Conditionals Implementing Procedures def evalConditional(expr, env): What do we need to record? assert isConditional(expr) if len(expr) <= 2: Recall the conditional: Environment evalError ("Bad ...”) (cond ((< x 5) “small”) pointer (< x 10) “medium”) for clause in expr[1:]: (< x 99) “large”))) if len(clause) != 2: evalError ("Bad ...”) predicate = clause[0] x result = meval(predicate, env) (+ x x) if not result == False: Input parameters (in mouth) Procedure Body return meval(clause[1], env) evalError ("No ...”) return None #5 #6
Procedure Class Evaluating Lambda Expressions class Procedure : def __init__(self, params, body, env): def evalLambda (expr,env): self._params = params assert isLambda(expr) self._body = body if len(expr) != 3: self._env = env evalError ("Bad lambda ...”) def getParams(self): return Procedure(expr[1], expr[2], env) return self._params def getBody(self): return self._body def getEnvironment(self): return self._env #7 #8 Evaluating Applications evalApplication def meval(expr, env): def evalApplication(expr, env): ... # To evaluate an application elif isApplication(expr): # evaluate all the subexpressions return evalApplication(expr, env) subexprvals = map ( lambda subexpr: else: meval(subexpr, env), expr) evalError (...) # then, apply the value of the meval meval # first subexpression to the rest return mapply(subexprvals[0], subexprvals[1:]) mapply mapply #9 #10 Liberal Arts Trivia: Liberal Arts Trivia: Geography Italian Literature • This island nation in southeast Asia is located • This Florentine poet of the Middle Ages is called il Sommo Poeta . His central work, the Divinia about 20 miles off the southern coast of India. Commedia , is often considered the greatest It is home to 20 million people (mostly literary work composed in the Italian language Sinhalese and Tamils), is a center of the and is a masterpiece of world literature. He is Buddhist religion, and possesses rich tropical often called the Father of the Italian Language: forests. during WWII it was used as a base for he wrote the Commedia in th early 14 th century in Allied forces against the Japanese Empire. It a new language he called “Italian” based on the was known as Ceylon before 1972. regional dialect of Tuscany with some Latin and other bits thrown in. • Bonus: Who guides him in Hell and Purgatory? #11 #12
mapply mapply def mapply(proc, operands): def mapply(proc, operands): if (isPrimitiveProcedure(proc)): if (isPrimitiveProcedure(proc)): return proc(operands) return proc(operands) elif isinstance (proc, Procedure): elif isinstance (proc, Procedure): params = proc.getParams() params = proc.getParams() newenv = ??? newenv = Environment(proc.getEnvironment()) if len(params) != len(operands): if len(params) != len(operands): evalError ("Parameter length mismatch ... ") evalError ("Parameter length mismatch ... ") for i in range(0, len(params)): for i in range(0, len(params)): ??? ??? return ??? return ??? else: else: evalError("Application of non-procedure: %s" % (proc)) evalError("Application of non-procedure: %s" % (proc)) #13 #14 mapply mapply def mapply(proc, operands): def mapply(proc, operands): if (isPrimitiveProcedure(proc)): if (isPrimitiveProcedure(proc)): return proc(operands) return proc(operands) elif isinstance (proc, Procedure): elif isinstance (proc, Procedure): params = proc.getParams() params = proc.getParams() newenv = Environment(proc.getEnvironment()) newenv = Environment(proc.getEnvironment()) if len(params) != len(operands): if len(params) != len(operands): evalError ("Parameter length mismatch ... ") evalError ("Parameter length mismatch ... ") for i in range(0, len(params)): for i in range(0, len(params)): newenv.addVariable(params[i], operands[i]) newenv.addVariable(params[i], operands[i]) return ??? return meval(proc.getBody(), newenv) else: else: evalError("Application of non-procedure: %s" % (proc)) evalError("Application of non-procedure: %s" % (proc)) #15 #16 Implemented Lazy Evaluation Interpreter! meval meval • Don’t evaluate expressions until their value is really needed What’s missing? – We might save work this way, since sometimes Special forms: we don’t need the value of an expression if, begin, set! mapply mapply Primitive procedures: – We might change the meaning of some lots and lots expressions, since the order of evaluation Built-in types: matters floating point numbers, strings, lists, etc. • Not a wise policy for problem sets (all answer values will always be needed!) #17 #18
Ordinary men and women, having the opportunity of a happy life, Lazy Examples will become more kindly and less persecuting and less inclined to view others with suspicion. The taste for war will die out, partly Charme> ((lambda (x) 3) (* 2 2)) for this reason, and partly because it will involve long and severe 3 work for all. Good nature is, of all moral qualities, the one that the LazyCharme> ((lambda (x) 3) (* 2 2)) world needs most, and good nature is the result of ease and 3 security, not of a life of arduous struggle. Modern methods of Charme>((lambda (x) 3) (car 3)) (Assumes extensions production have given us the possibility of ease and security for error: car expects a pair, applied to 3 from ps7) all; we have chosen, instead, to have overwork for some and LazyCharme> ((lambda (x) 3) (car 3)) starvation for others. Hitherto we have continued to be as 3 energetic as we were before there were machines; in this we Charme> ((lambda (x) 3) (loop-forever)) have been foolish, but there is no reason to go on being foolish no value – loops forever forever. LazyCharme> ((lambda (x) 3) (loop-forever)) 3 Bertrand Russell, In Praise of Idleness, 1932 (co-author of Principia Mathematica , Laziness can be useful! proved wrong by Gödel’s proof) #19 #20 How do we make our How do we make our evaluation rules lazier ? evaluation rules lazier ? Original Evaluation Rule 3: Application. Evaluation Rule 3: Application. To evaluate an application, To evaluate an application, a. evaluate all the subexpressions a. evaluate all the subexpressions b. apply the value of the first subexpression to b. apply the value of the first subexpression to the values of the other subexpressions. the values of the other subexpressions. • evaluate the first subexpression, and delay evaluating the operand subexpressions until their values are needed. #21 #22 Liberal Arts Trivia: Liberal Arts Trivia: Canadian Literature Neuroscience • In this 1908 book, the title character is a • This medical visualization technique is most talkative red-haired orphan. She moves to the commonly used to visualize the internal village of Avonlea to live with farmers Matthew structure and function fo the body. Notably, it and Marilla Cuthbert. She becomes bosom uses no ionizing radiation, but instead uses friends with Diana Barry and has a complex powerful fields to align the hydrogen atoms in relationship with Gilbert Blythe. Her vivid water in the body. Radiofrequency fields are imagination and cheerful outlook often land used to alter the alignment of the hydrogen her in trouble. atoms, which can then be detected by a scanner. The process was first used on humans • Bonus: Name the setting's Canadian Province. in 1977. #23 #24
Recommend
More recommend