Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Adding Booleans; Scope and Substitution

This lecture we will continue to grow our language. Last time, we ended with a language for if-then-else and numbers. Today, we will add a new type of values (Booleans) as well as local variables.

import Lait
#lait

IfLang with Booleans

Recall the IfLang language from last time:

type IfLang := | NumI (value : Int)
               | PlusI (e1 : IfLang) (e2 : IfLang)
               | IfI (guard : IfLang) (thn : IfLang) (els : IfLang)

(We only need to consider addition here; multiplication will behave similarly.) Last time, we gave this language a semantics via a definitional interpreter with the following type:

def interp_if_old (e : IfLang) : Int := ...

In other words, we made the choice that every value in IfLangOld was a Lait Int. Thus, to interpret a guard for an if/then/else, we had to make a decision about how to think of an integer as an if-condition.

Let’s think of another semantics that matches our intuition better: numbers will be interpreted as Int, and guards will be interpreted as Bool. Thus, let’s change our language to support booleans.

type IfLang := | NumI (value : Int)
               | BoolI (value : Bool)
               | PlusI (e1 : IfLang) (e2 : IfLang)
               | AndI (e1 : IfLang) (e2 : IfLang)
               | IfI (guard : IfLang) (thn : IfLang) (els : IfLang)

Above, we only made two changes: we have a way to construct Boolean constants (via BoolI); and we have a way to join two Booleans together (via AndI). (Adding disjunction via OrI will be the same.)

Before writing our interpreter, let’s think about a few examples and how they should evaluate. First, ordinary numberic expressions should evaluate as before:

PlusI (NumI 1) (NumI 2) ===> NumI 3

Next, Boolean expressions should evaluate as expected:

AndI (BoolI true) (BoolI false) ==> BoolI false

Similarly for IfI:

IfI (AndI (BoolI true) (BoolI false)) (NumI 1) (NumI 2) ==> NumI 2

Now, what should happen if we add a number to a Boolean? We should get that this raises an error in the Lait code:

AndI (BoolI true) (NumI 3) ==> ERROR

Similarly, evaluating IfI where the guard is a number should give us an error.

The Interpreter

How should we define an interpreter for IfLang, now that we have multiple kinds of values (numbers and booleans)? We will define a type of value, for a number-or-boolean value:

type Value := | NumV (v : Int)
              | BoolV (v : Bool)

Then, we will have the type of our interprer return a value:

def interp_if (e : IfLang) : Value := ...

Let’s now think of how to write this function by cases. If we are interpreting NumI or BoolI, we just take the inner value and call the appropriate constructor in Value:

def interp_if (e : IfLang) : Value :=
  match e with 
  | NumI v => NumV v
  | BoolI v => BoolV v
  | _ => ...
  end

Now, let’s think of how to interpret PlusI e1 e2. Recursively, we will obtain values v1 := interp_if e1, and v2 := interp_if e2. However, we cannot add these values together yet, as they are not guaranteed to be numbers. Indeed, this won’t be the case if e1 is a boolean. In this case, we want to throw an error. We will do this by defining two helper functions which will cast Values to numbers or booleans, and throw an error if it isn’t of the desired form:

def Value.toInt (v : Value) : Int :=
  match v with
  | NumV i => i
  | _ => error "Value.toInt: not an Int"
  end

and similarly for Booleans:

def Value.toBool (v : Value) : Bool :=
  match v with 
  | BoolV b => b
  | _ => error "Value.toBool: not a Bool"
  end

Given these definitions, we can now define our interpreter.

def interp_if (e : IfLang) : Value :=
  match e with 
  | NumI v => NumV v
  | BoolI v => BoolV v
  | PlusI e1 e2 => 
    let v1 := interp_if e1 in 
    let v2 := interp_if e2 in 
    NumV (Value.toInt v1 + Value.toInt v2)
  | AndI e1 e2 => 
    let v1 := interp_if e1 in 
    let v2 := interp_if e2 in 
    BoolV (Value.toBool v1 && Value.toBool v2)
  | IfI e1 e2 e3 => 
    let v := interp_if e1 in 
    let b := Value.toBool v in 
    if b then interp_if e2 else interp_if e3
  end

-- Runs successfully
#eval interp_if (IfI (BoolI true) (NumI 1) (NumI 2)))>> NumV 1
 
-- Errors
#eval interp_if (IfI (NumI 0) (NumI 1) (NumI 2)))

-- Errors
#eval interp_if (PlusI (BoolI true) (NumI 24))

Static vs Dynamic languages

Of course, you don’t want to write programs that crash. There are multiple kinds of ways of preventing crashes. One way is using static types, which means you have a type system that catches these kinds of errors before trying to run the program. Lait is a statically typed language:

#eval true + 24

Another point in the design space are dynamic languages, which keep track of typing information at runtime. For example, see the below interaction with Racket:

> (+ 3 2)
5

> (+ #t 3)
; +: contract violation
;   expected: number?
;   given: #t
; [,bt for context]

Above we raise a contract violation, which is a concept that appears during runtime, rather than during a static type checking phase.

One difference between Lait and Racket is that certain expressions that happen to run fine but only due to their runtime semantics will work fine in Racket, but won’t work in Lait. For example, consider if true then (1 + 2) else true + false. If we try to run this in Lait, we will get a type error:

#eval if true then (1 + 2) else (true + false)

But if we run it in Racket:

> (if #t (+ 1 2) (+ #t #f))
3

The choice to use a static or dynamic language requires a tradeoff. Statically-typed languages help programmers find unintentional crashes before the program runs, while dynamic languages provide more flexibility, at the cost of preventing fewer crashes ahead of time.

As it stands, IfLang currently behaves like a dynamic language, using Lait-level errors to catch type mismatches at runtime.

#eval interp_if (IfI (BoolI true) (PlusI (NumI 1) (NumI 2)) (PlusI (BoolI true) (BoolI false))))>> NumV 3

Later on in this course, we will study type systems, which will allow our languages to be statically typed.

Question: Lazy vs Eager. Currently interp_if allows you to run if/then/else expressions where one of the two sides is guaranteed to crash. What would happen if we changed our interpreter to evaluate both sides before running a Lait-level if, rather than evaluating only the relevant side?

Question: Checking the types for if/then/else. Currently interp_if allows the “then” branch to return a number, while the “else” branch returns a Boolean. How might we prevent this behavior in the interpreter, if we wanted to?

Adding Variables

Now, let’s move onto adding local variables. Our goal is to have local variables behave as in Lait, so let’s first see how they behave. In Lait, local variables (i.e., variables inside of expressions) are introduced using the syntax let .. := .. in ..:

#eval let myvar := 10 in myvar + 1>> 11

Let’s make the terminology more precise here. The name myvar is an identifier, which is bound to the result of the expression 10. The body of the let is what happens after the if; in the above, myvar + 10 is the body.

What makes a local variable local is that it is not visible outside of the body of the let expression. For example, the second #eval below will raise an error:

#eval let myvar := 10 in myvar + 1>> 11
#eval myvar + 20

Above, the second #eval raises the error that “myvar is not found”. The way to make this precise is with a notion of scope. The scope of an identifier in a let expression is the body of the let expression. Thus, myvar is out of scope for the second #eval.

Shadowing

What happens if you try to redefine a local variable? Let’s see:

#eval let myvar := 10 in let myvar := 20 in myvar>> 20

What happens here is that we prefer the inner-most binding in the syntax tree: the most recent variable binding is the one we use. This is called lexical scope, because the scope of the binding depends on its position in the syntax tree. If we use the same identifier twice, we say that the inner binding code let myvar := 20 in myvar shadows the outer binding let myvar := 10 in .... Hence, the first binding goes out of scope, and can no longer be accessed. Most languages you’ve used use lexical scope.

Under lexical scope, the above example is exactly equivalent to just using a new identifier:

#eval let myvar := 10 in let myvar' := 20 in myvar'>> 20

Substitution

Now, let’s move on to understanding how we might go about implementing local variables. First, let’s define an abstract syntax tree for LetLang, a small language with let expressions:

type LetLang := | NumE (n : Int)
                | PlusE (l : LetLang) (r : LetLang)
                | VarE (var : String)
                | LetE (var : String) (assignment : LetLang) 
                                      (body : LetLang)

There are a few different ways to implement a semantics for LetLang. The one we will tackle here is a substitution-based semantics. It is like a “find-and-replace” for expressions. Let’s first see how LetLang steps intuitively before defining its semantics.

-- In a surface syntax: let x := 10 in x + x
LetE "x" (NumE 10) (PlusE (VarE "x") (VarE "x"))

==>

-- Substitute (VarE "x") with (NumE 10) in the body
PlusE (NumE 10) (NumE 10)

-- Finally, simplify the addition as before
(NumE 20)

To evaluate a LetE, you evaluate the body, but first substitute the value of "x" in. However, there is a choice for how to do this. Consider the following example:

LetE "x" (PlusE (NumE 10) (NumE 10)) (PlusE (VarE "x") (VarE "x"))

There are two possible things we can do:

  1. First simplify PlusE (NumE 10) (NumE 10) to a value (NumE 20), and then substitute NumE 20 in for "x";
  2. Substitute the entire expression PlusE (NumE 10) (NumE 10) in for "x", giving us the expression (PlusE (PlusE (NumE 10) (NumE 10) (PlusE (NumE 10) (NumE 10)))).

The first strategy is called eager evaluation while the second is called lazy. Most languages are eager languages, but there are some exceptions; for example, Haskell is a call-by-need language that does not use eager evaluation. We will discuss this in the future. We will use eager evaluation today.

Implementing Substitution

To implement substitution, we will need to be very careful to not violate how shadowing should work. For example, our semantics should do something roughly like this:

LetE "x" (NumE 10) (LetE "x" (NumE 20) (VarE "x"))

==>

LetE "x" (NumE 20) (VarE "x")

==>

NumE 20

After we evaluate NumE 10, we will eventually “throw away” the result, because we are going to shadow the binding to a new one with the same name.

We will do this with a helper function called subst:

def subst (var : String) (assignment : LetLang) (body : LetLang) : LetLang :=
  match body with 
  | NumE i => NumE i
  | PlusE e1 e2 => PlusE (subst var assignment e1) (subst var assignment e2)
  | VarE var' => if var == var' then assignment else VarE var'
  | LetE var' e1 e2 => 
     let e1' := subst var assignment e1 in 
     let e2' := 
      if var == var' then e2 
                     else subst var assignment e2 in 
     LetE var' e1' e2'
  end

The idea of subst var assignment body is that we replace all instances of VarE var with assignment. If we find another let expression that defines var, then we stop recursing.

Let’s see some unit tests:

#test subst "x" (NumE 10) (PlusE (VarE "x") (VarE "x"))
      ===
      PlusE (NumE 10) (NumE 10)

#test subst "x" (NumE 10) (LetE "x" (NumE 20) (VarE "x"))
      ===
      (LetE "x" (NumE 20) (VarE "x"))

Interpreting LetLang

Now that we have defined substitution, let’s implement an interpreter.

def interp_let (e : LetLang) : Int :=
  match e with
  | NumE v => v
  | PlusE e1 e2 => interp_let e1 + interp_let e2
  | VarE v => error "interp_let: got a variable"
  | LetE x e1 e2 => 
    let v := interp_let e1 in 
    let e2' := subst x (NumE v) e2 in 
    interp_let e2'
  end

#eval interp_let (LetE "x" (NumE 10) (PlusE (VarE "x") (VarE "x")))>> 20

#eval interp_let (LetE "x" (NumE 10) (LetE "y" (NumE 20) (PlusE (VarE "x") (VarE "y")))))>> 30

#eval interp_let (LetE "x" (NumE 10) (LetE "x" (NumE 20) (PlusE (VarE "x") (VarE "x")))))>> 40

Open and Closed Expressions

Note that interp_let throws an error if we hit a variable. This is because we assume that the only expressions we interpret are closed: every variable is defined by an enclosing let. Hence, the below are closed expressions:

LetE "x" (NumE 10) (VarE "x")
LetE "x" (LetE "y" (NumE 1) (VarE "y")) (VarE "x")

However, the below are not. They are open: there exists a variable that is not defined by a prior let.

VarE "x"
LetE "x" (NumE 1) (VarE "y")
LetE "x" (VarE "x") (VarE "x")

Note that for the third example above, the scope of the let is the body, but not the assigned value of the expression. Hence, "x" is out of scope for the first VarE "x", but in scope for the second one.

Dynamic Scope

A key property of our scoping rules so far is that they are static, meaning that the scope of an identifier does not depend on the runtime behavior of a program. This might seem like an obvious requirement – most languages you have used satisfy this requirement – but there are examples of languages where which variables are in-scope can depend on the runtime behavior of a program. This is an actual common Lisp program that prints out 5 5:

(defvar x 100)
 
(defmethod fun1 (x)
  (print x)
  (fun2))
 
(defmethod fun2 ()
  (print x))
 
(fun1 5)

Why don’t we print 100? The defvar function introduces a special global variable x. Then, when fun1 is called, it introduces a variable x into scope, and binds it to the value 5. Then, it prints x, which has value 5, so the first 5 gets printed. But now, fun1 will call fun2, which takese no arguments. It also prints x, which outputs 5, but we surely expect 100 to be printed!

This is because the scoping rules in Common Lisp are dynamic: once introduced, a variable never leaves scope, and hence variables always refers to the most recently declared identifier encountered while running the program. (Note: Common Lisp also has a local-like facility that supports lexical scope.) Because of this unintuitive behavior, dynamic scope by default is less popular for modern languages. For more reading on scope, see this blog post.