Discussion 10: Interpreters๐จ๏ธ
Attendance
Your TA will come around during discussion to check you in. You can start on the worksheet before being checked in; you don't need to wait for your TA to get started.
If you didn't attend for a good reason (such as being sick), fill out this form (within 2 weeks of your discussion): attendance form
Getting Started
Intros: Say your name and your favorite food or beverage to enjoy in Berkeley. Optionally go have that food or beverage as a group after section!
The Animator Evaluator
You can expect the final exam to ask questions about how values and expressions are represented in the Animator project's evaluator, and how expressions are evaluated.
These tools run the Animator project's parser and evaluator on any example:
- The parsing tool shows the
Exprthat represents some Gleam code. - The evaluation tool shows each
expression evaluated and each function applied while evaluating some Gleam
code, and (if you check "Include the result's
Value") theValueof the result.
These questions only use the subset of Gleam that the Animator project's evaluator supports.
Q1: Representing Expressions
How is each Gleam expression represented as an Expr in the Animator project's
evaluator?
Lecture 30: The Expr type
pub type Expr {
Var(String)
LiteralBool(Bool)
LiteralInt(Int)
LiteralList(elems: List(Expr), rest: Option(Expr))
Call(fn_expr: Expr, operands: List(Expr))
Lambda(params: List(String), body: Expr)
// Each Arm is an "arm" of a case expression
Case(subject: Expr, arms: List(Arm))
// The body is the expression on the line after the let line
Let(name: String, value: Expr, body: Expr)
FieldAccess(record: Expr, field: String)
}
Example expressions: x, True, 61, [1, 2] or [1, 2, ..s], f(5),
fn (x) {x > 5}, case x {0 -> False _ -> True}, let x = 5, point.x.
Each arm of a Case pairs a Pattern with the Expr to evaluate if the subject
matches that pattern:
pub type Arm =
#(Pattern, Expr)
pub type Pattern {
PBool(Bool)
PInt(Int)
PWildcard
PVar(String)
PList(elems: List(Pattern), rest: Option(String))
}
Gleam to Expr. For each Gleam expression below, return the Expr that
represents it. Operators such as + and > are names of built-in functions, so
x > 5 is a Call. Each "Answer" link opens the
parsing tool on the expression,
which shows its Expr.
(a) f(2) Answer
/// The Expr that represents:
/// f(2)
pub fn expr_a() -> Expr {
// YOUR CODE HERE (replace the code below)
todo
}
Hint: Calls
A one-argument call expression has the template Call( ___ , [ ___ ]).
(b) 1 + 1 Answer
/// The Expr that represents:
/// 1 + 1
pub fn expr_b() -> Expr {
// YOUR CODE HERE (replace the code below)
todo
}
Hint: Arithmetic
Binary arithmetic operators such as +, -, *, and / are converted to Call records by the parser, and the operator is the fn_expr: Call(Var("+"), [ ___ , ___ ]).
(c) [y + 2] Answer
/// The Expr that represents:
/// [y + 2]
pub fn expr_c() -> Expr {
// YOUR CODE HERE (replace the code below)
todo
}
Hint: Lists
A one-item list with no .. has the template LiteralList([ ___ ], None).
(d) [2, x, ..s] Answer
/// The Expr that represents:
/// [2, x, ..s]
pub fn expr_d() -> Expr {
// YOUR CODE HERE (replace the code below)
todo
}
Hint: Lists with ..
A list with two items before a .. has the template LiteralList([ ___ , ___ ], Some( ___ )), where the expression after .. goes in the Some.
(e) f(y).x Answer
/// The Expr that represents:
/// f(y).x
pub fn expr_e() -> Expr {
// YOUR CODE HERE (replace the code below)
todo
}
Hint: Dot expressions
A dot expression has the template FieldAccess( ___ , "x"), where the first argument is the Expr before the dot.
(f) fn(x) { x > 5 } Answer
/// The Expr that represents:
/// fn(x) { x > 5 }
pub fn expr_f() -> Expr {
// YOUR CODE HERE (replace the code below)
todo
}
Hint: Anonymous functions
An anonymous function fn(x) { ... } has the template Lambda(["x"], ___ ): a list of parameter names (strings), then its body, an Expr. Like +, the comparison > is converted to a Call.
Expr to Gleam. Now go the other way. For each Expr below, return a
string containing the Gleam expression that it represents. Verify ignores spaces
and line breaks, so "f(x,y)" and "f(x, y)" are both fine. The "Answer" link
shows the answer in the parsing tool, so try it after you've verified.
IMPORTANT: Put every expression in quotes!
(g) Call(Var("abs"), [Var("x")]) Answer
/// The Gleam expression that this Expr represents:
/// Call(Var("abs"), [Var("x")])
pub fn expr_g() -> String {
// YOUR CODE HERE (replace the code below)
todo
}
Hint: Calls
A Call whose fn_expr is Var(name) is a call to the function named by name, so this one has the template abs( ___ ).
(h) LiteralList([LiteralInt(1)], Some(Var("s"))) Answer
/// The Gleam expression that this Expr represents:
/// LiteralList([LiteralInt(1)], Some(Var("s")))
pub fn expr_h() -> String {
// YOUR CODE HERE (replace the code below)
todo
}
Hint: Lists
A LiteralList whose rest is Some(r) ends with .. followed by r, so this one has the template [ ___ , .. ___ ].
(i) Call(Call(Var("f"), [Var("x")]), [LiteralBool(True)]) Answer
/// The Gleam expression that this Expr represents:
/// Call(Call(Var("f"), [Var("x")]), [LiteralBool(True)])
pub fn expr_i() -> String {
// YOUR CODE HERE (replace the code below)
todo
}
Hint: Calls of calls
The fn_expr of the outer Call is another Call, so this one has the template ___ ( ___ )( ___ ).
Q2: Representing Values
How is the value of each Gleam expression represented as a Value in the
Animator project's evaluator?
Lecture 30: The Value type
Evaluating an expression in an environment produces a value (or an evaluation error).
pub type Value {
VBool(Bool)
VInt(Int)
VList(List(Value))
// A record (e.g., a Point or Line). The tag indicates its type.
VData(tag: String, fields: List(Value))
VFunc(Callable)
}
pub type Callable {
Builtin( name: String, num_args: Int, run: fn(List(Value)) -> Result(Value, EvalError))
UserFn(name: String, params: List(String), body: Expr, env: Env)
}
Example values: True, 61, [1, 2], Point(5, 10).
For each Gleam expression below, return the Value of
that expression. The "Answer" link opens the
evaluation tool on the expression
with "Include the result's Value" checked, so that its last line shows the
Value.
(a) 61 Answer
/// The Value of:
/// 61
pub fn value_a() -> Value {
// YOUR CODE HERE (replace the code below)
todo
}
Explanation
The value of an integer literal is a VInt holding that integer.
VInt(61)
(b) [1, 2] Answer
/// The Value of:
/// [1, 2]
pub fn value_b() -> Value {
// YOUR CODE HERE (replace the code below)
todo
}
Explanation
The value of a list literal is a VList of the values of its elements.
VList([VInt(1), VInt(2)])
(c) [1 + 1] Answer
/// The Value of:
/// [1 + 1]
pub fn value_c() -> Value {
// YOUR CODE HERE (replace the code below)
todo
}
Explanation
Evaluating the list evaluates its element 1 + 1, whose value is 2. A Value
contains no expressions to evaluate: compare it to the Expr for [1 + 1],
which is LiteralList([Call(Var("+"), [LiteralInt(1), LiteralInt(1)])], None).
VList([VInt(2)])
(d) [1, ..[2, 3]] Answer
/// The Value of:
/// [1, ..[2, 3]]
pub fn value_d() -> Value {
// YOUR CODE HERE (replace the code below)
todo
}
Explanation
A VList has no rest: evaluating the list literal combines its elements and
its rest into one list.
VList([VInt(1), VInt(2), VInt(3)])
Q3: Evaluating Expressions
What expressions are evaluated while evaluating each Gleam expression below in the Animator project's evaluator? Return a list of strings, one for each expression, in the order that their evaluation begins. Don't include the whole expression itself. See the example below.
The "Answer" link opens the
evaluation tool on the expression. It
prints eval followed by each expression as its evaluation begins.
Lecture 30: eval and apply
fn eval(expr: Expr, env: Env) -> Result(Value, EvalError) {
case expr {
Var(name) -> lookup(env, name)
LiteralBool(b) -> Ok(VBool(b))
LiteralInt(n) -> Ok(VInt(n))
LiteralList(elems, rest) -> // Evaluate & combine the elems and rest
Call(fn_expr, operands) -> // Evaluate the fn_expr & operands, then call apply
Lambda(params, body) -> // Construct a UserFn("lambda", ...)
Case(s, arms) -> // Evaluate s, then match its value to one of the arms
Let(x, v, body) -> // Evaluate v, bind its value to x, and then evaluate body
FieldAccess(record, field) -> // Evaluate record, make sure it's a VData, and get a field
}
}
pub fn apply(f: Value, args: List(Value)) -> Result(Value, EvalError) {
case f {
VFunc(Builtin(name, num_args, run)) -> // Call run (a Gleam function) on args
VFunc(UserFn(name, params, body, parent)) -> // Make a Local frame e, then eval(body, e)
}
}
Example: abs(-3)
Evaluating the call abs(-3) evaluates its fn_expr abs and then its
operand -3. Then apply applies the built-in abs to -3, which evaluates no
more expressions. The answer is:
["abs", "-3"]
The evaluation tool shows the same thing.
(a) add_two(3), where add_two is defined as follows: Answer
fn add_two(y) {
[y + 2]
}
/// The expressions evaluated while evaluating add_two(3), in order, not including
/// add_two(3) itself.
pub fn eval_a() -> List(String) {
// YOUR CODE HERE (replace the code below)
todo
}
Hint: Function calls
When the call expression add_two(3) is evaluated, first add_two and then 3 are evaluated, then the body of the add_two function is evaluated.
Explanation
Evaluating the call evaluates its fn_expr add_two and its operand 3. Then
apply evaluates the body of add_two, the list [y + 2], in a new frame where
y is 3. Evaluating that list evaluates its element y + 2, which is a call:
its fn_expr +, then its operands y and 2.
["add_two", "3", "[y + 2]", "y + 2", "+", "y", "2"]
(b) list.map([], fn(x) { x * x }). Answer
Note: list.map is evaluated as one variable, not a dot expression, in the Animator's interpreter.
/// The expressions evaluated while evaluating list.map([], fn(x) { x * x }), in order, not including
/// list.map([], fn(x) { x * x }) itself.
pub fn eval_b() -> List(String) {
// YOUR CODE HERE (replace the code below)
todo
}
Hint: Standard library functions
There is no body expression of list.map, since it is a standard library function.
Explanation
Evaluating the call evaluates its fn_expr list.map and its operands [] and
fn(x) { x * x }. The body x * x is never evaluated: evaluating the fn
creates a function value without evaluating its body, and list.map never
applies that function because the list is empty.
["list.map", "[]", "fn(x) { x * x }"]
(c) pick(3), where pick is defined as follows: Answer
fn pick(n) {
case n {
0 -> 1
_ -> n * 2
}
}
Note: Write a case expression on one line, as in "case n { 0 -> 1 _ -> n * 2 }".
/// The expressions evaluated while evaluating pick(3), in order, not including
/// pick(3) itself.
pub fn eval_c() -> List(String) {
// YOUR CODE HERE (replace the code below)
todo
}
Hint: Case expressions
The patterns of a case are not an expression, so they don't get evaluated. (They get matched.) Exactly one of the arm expressions within the case (following a ->) gets evaluated.
Explanation
Evaluating the call evaluates pick and 3, and then apply evaluates the
body of pick, the case expression, where n is 3. Evaluating the case
evaluates its subject n. Patterns such as 0 and _ are not expressions, so
they are never evaluated: the subject's value is matched against each pattern,
and only the body of the first arm that matches, n * 2, is evaluated. The 1
is never evaluated.
["pick", "3", "case n { 0 -> 1 _ -> n * 2 }", "n", "n * 2", "*", "n", "2"]
Working with Expressions and Values
Q4: Remove Lets
A let can always be replaced by a call to an anonymous function. For example,
these two expressions have the same value, 9:
let y = 3
y * y
fn(y) { y * y }(3)
Evaluating the first one binds y to 3 in the current frame and then evaluates
y * y. Evaluating the second binds y to 3 in a new frame and then evaluates
y * y. Either way, y * y is evaluated in an environment where y is 3.
Compare the first and the
second in the evaluation tool.
The code below includes five of the variants of the Animator project's Expr
type. Implement remove_lets, which takes an Expr e and returns an Expr
with the same value that contains no Let. Replace each Let with a Call of
a Lambda that has one parameter. Assume that any Expr can contain a Let:
the value or body of another Let, an operand, a function body, and so on.
let square = Call(Var("*"), [Var("y"), Var("y")])
assert remove_lets(Let("y", LiteralInt(3), square))
== Call(Lambda(["y"], square), [LiteralInt(3)])
list.map(s, f) returns a list of the results of calling f on each element of
s. For example, list.map([1, 2, 3], fn(x) { x * 10 }) returns [10, 20, 30].
/// Five of the variants of the Animator project's Expr type.
pub type Expr {
Var(String)
LiteralInt(Int)
Call(fn_expr: Expr, operands: List(Expr))
Lambda(params: List(String), body: Expr)
Let(name: String, value: Expr, body: Expr)
}
/// An expression with the same value as e that contains no Let.
pub fn remove_lets(e: Expr) -> Expr {
// YOUR CODE HERE (replace the code below)
todo
}
Hint: Recursive calls
To find all of the places where a recursive call is needed, look at the Expr type and find all of the places where a field is or contains an Expr.
Hint: Template
A Var or LiteralInt contains no Let. Every other variant contains
expressions that might, so call remove_lets on each of them.
case e {
Var(_) | LiteralInt(_) -> e
Call(f, operands) -> Call( ___ , list.map( ___ , ___ ))
Lambda(params, body) -> Lambda(params, ___ )
Let(name, value, body) -> Call(Lambda([name], ___ ), [ ___ ])
}
Q5: Connect the Dots
In the Animator project's evaluator, a record is a VData whose tag is the
name of its type and whose fields are the values of its fields, in order. For
example, Line(Point(0, 0), Point(3, 4)) evaluates to:
VData("Line", [
VData("Point", [VInt(0), VInt(0)]),
VData("Point", [VInt(3), VInt(4)]),
])
Lecture 30: The Value type
Evaluating an expression in an environment produces a value (or an evaluation error).
pub type Value {
VBool(Bool)
VInt(Int)
VList(List(Value))
VData(tag: String, fields: List(Value))
// ... and VFunc for functions, which this question skips
}
Example values: True, 61, [1, 2], Point(5, 10).
First, implement point, which returns the Value of Point(x, y) for
integers x and y.
Then, implement lines, which takes a list of Point values and returns a
list of Line values: one from each point to the next. Then connect, which
is already implemented, returns the Value of a list of those lines. For
example, connect([point(0, 0), point(3, 4), point(6, 0)]) returns the Value
of [Line(Point(0, 0), Point(3, 4)), Line(Point(3, 4), Point(6, 0))].
let a = point(0, 0)
let b = point(3, 4)
let c = point(6, 0)
assert a == VData("Point", [VInt(0), VInt(0)])
assert connect([a, b, c]) == VList([VData("Line", [a, b]), VData("Line", [b, c])])
To see the whole Value of that list, open the
evaluation tool on it.
/// The value of Point(x, y).
pub fn point(x: Int, y: Int) -> Value {
// YOUR CODE HERE (replace the code below)
todo
}
/// The value of a list of Line records, each from one of the points to the next.
pub fn connect(points: List(Value)) -> Value {
VList(lines(points))
}
/// A Line value from each of the points to the next.
pub fn lines(points: List(Value)) -> List(Value) {
// YOUR CODE HERE (replace the code below)
todo
}
Hint: Template for point
A Point record is a VData whose tag is "Point" and whose fields are the
values of x and y, in that order.
pub fn point(x: Int, y: Int) -> Value {
VData( ___ , [VInt( ___ ), ___ ])
}
Hint: Template for lines
A list with two or more points needs a Line from the first point a to the
second point b, followed by the lines that connect b and the rest of the
points. A shorter list needs no lines.
pub fn lines(points: List(Value)) -> List(Value) {
case points {
[a, b, ..rest] -> [VData("Line", [ ___ , ___ ]), ..lines([ ___ , ..rest])]
_ -> []
}
}