PL: Lecture #14  Tuesday, October 27th

Implementing rec Using Cyclic Structures

PLAI §10

Looking at the arrows in the environment diagrams, what we’re really looking for is a closure that has an environment pointer which is the same environment in which it was defined. This will make it possible for fact to be bound to a closure that can refer to itself since its environment is the same one in which it is defined. However, so far we have no tools that makes it possible to do this.

What we need is to create a “cycle of pointers”, and so far we do not have a way of achieving that: when we create a closure, we begin with an environment which is saved in the slot’s environment slot, but we want that closure to be the value of a binding in that same environment.

Boxes and Mutation

To actually implement a circular structure, we will now use side-effects, using a new kind of Racket value which supports mutation: a box. A box value is built with the box constructor:

(define my-thing (box 7))

the value is retrieved with the `unbox’ function,

(* 6 (unbox my-thing))

and finally, the value can be changed with the set-box! function.

(set-box! my-thing 17)
(* 6 (unbox my-thing))

An important thing to note is that set-box! is much like display etc, it returns a value that is not printed in the Racket REPL, because there is no point in using the result of a set-box!, it is called for the side-effect it generates. (Languages like C blur this distinction between returning a value and a side-effect with its assignment statement.)

As a side note, we now have side effects of two kinds: mutation of state, and I/O (at least the O part). (Actually, there is also infinite looping that can be viewed as another form of a side effect.) This means that we’re now in a completely different world, and lots of new things can make sense now. A few things that you should know about:

When any one of these things is used (in Racket or other languages), you can tell that side-effects are involved, because there is no point in any of them otherwise. In addition, any name that ends with a ! (“bang”) is used to mark a function that changes state (usually a function that only changes state).

So how do we create a cycle? Simple, boxes can have any value, and they can be put in other values like lists, so we can do this:

#lang pl untyped
(define foo (list 1 (box 3)))
(set-box! (second foo) foo)

and we get a circular value. (Note how it is printed.) And with types:

#lang pl
(: foo : (List Number (Boxof Any)))
(define foo (list 1 (box 3)))
(set-box! (second foo) foo)

Types for Boxes

Obviously, Any is not too great — it is the most generic type, so it provides the least information. For example, notice that

(unbox (second foo))

returns the right list, which is equal to foo itself — but if we try to grab some part of the resulting list:

(second (unbox (second foo)))

we get a type error, because the result of the unbox is Any, so Typed Racket knows nothing about it, and won’t allow you to treat it as a list. It is not too surprising that the type constructor that can help in this case is Rec which we have already seen — it allows a type that can refer to itself:

#lang pl
(: foo : (Rec this (List Number (Boxof (U #f this)))))
(define foo (list 1 (box #f)))
(set-box! (second foo) foo)

Note that either foo or the value in the box are both printed with a Rec type — the value in the box can’t just have a (U #f this) type, since this doesn’t mean anything in there, so the whole type needs to still be present.

There is another issue to be aware of with Boxof types. For most type constructors (like Listof), if T1 is a subtype of T2, then we also know that(Listof T1) is a subtype of (Listof T2). This makes the following code typecheck:

#lang pl
(: foo : (Listof Number) -> Number)
(define (foo l)
  (first l))
(: bar : Integer -> Number)
(define (bar x)
  (foo (list x)))

Since the (Listof Integer) is a subtype of the (Listof Number) input for foo, the application typechecks. But this is not the same for the output type, for example — if we change the bar type to:

(: bar : Integer -> Integer)

we get a type error since Number is not a subtype of Integer. So subtypes are required to “go up” on the input side and “down” on the other. So, in a sense, the fact that boxes are mutable means that their contents can be considered to be on the other side of the arrow, which is why for such T1 subtype of T2, it is (Boxof T2) that is a subtype of (Boxof T1), instead of the usual. For example, this doesn’t work:

#lang pl
(: foo : (Boxof Number) -> Number)
(define (foo b)
  (unbox b))
(: bar : Integer -> Number)
(define (bar x)
  (: b : (Boxof Integer))
  (define b (box x))
  (foo b))

And you can see why this is the case — the marked line is fine given a Number contents, so if the type checker allows passing in a box holding an integer, then that expression would mutate the contents and make it an invalid value.

However, boxes are not only mutable, they hold a value that can be read too, which means that they’re on both sides of the arrow, and this means that (Boxof T1) is a subtype of (Boxof T2) if T2 is a subtype of T1 and T1 is a subtype of T2 — in other words, this happens only when T1 and T2 are the same type. (See below for an extended demonstration of all of this.)

Note also that this demonstration requires that extra b definition, if it’s skipped:

(define (bar x)
  (foo (box x)))

then this will typecheck again — Typed Racket will just consider the context that requires a box holding a Number, and it is still fine to initialize such a box with an Integer value.

As a side comment, this didn’t always work. Earlier in its existence, Typed Racket would always choose a specific type for values, which would lead to confusing errors with boxes. For example, the above would need to be written as

(define (bar x)
  (foo (box (ann x : Number))))

to prevent Typed Racket from inferring a specific type. This is no longer the case, but there can still be some surprises. A similar annotation was needed in the case of a list holding a self-referential box, to avoid the initial #f from getting a specific-but-wrong type.

Boxof’s Lack of Subtyping

The lack of any subtype relations between (Boxof T) and (Boxof S) regardless of S and T can roughly be explained as follows.

First, a box is a container that you can pull a value out of — which makes it similar to lists. In the case of lists, we have:

if:          S  subtype-of          T
then: (Listof S)  subtype-of  (Listof T)

This is true for all such containers that you can pull a value out of: if you expect to pull a T but you’re given a container of a subtype S, then things are still fine. Such “containers” include functions that produce a value — for example:

if:        S  subtype-of      T
then:  Q -> S  subtype-of  Q -> T

However, functions also have the other side, where things are different — instead of a side of some produced value, it’s the side of the consumed value. We get the opposite rule there:

if:    T      subtype-of  S
then:  S -> Q  subtype-of  T -> Q

To see why this is right, use Number and Integer for S and T:

if:    Integer      subtype-of  Number
then:  Number -> Q  subtype-of  Integer -> Q

so — if you expect a function that takes a number is a subtype of one that takes an integer; in other words, every function that takes a number is also a function that takes an integer, but not the other way.

To summarize all of this, when you make the output type of a function “smaller” (more constrained), the resulting type is smaller, but on the input side things are flipped — a bigger input type means a more constrained function.

Now, a (Boxof T) is a producer of T when you pull a value out of the box, but it’s also a consumer of T when you put such a value in it. This means that — using the above analogy — the T is on both sides of the arrow. This means that

if:    S subtype-of T  *and*  T subtype-of S
then:  (Boxof S) subtype-of (Boxof T)

which is actually:

if:          S  is-the-same-type-as        T
then:  (Boxof S)  is-the-same-type-as  (Boxof T)

A different way to look at this conclusion is to consider the function type of (A -> A): when is it a subtype of some other (B -> B)? Only when A is a subtype of B and B is a subtype of A, which means that this happens only when A and B are the same type.

(Side note: this is related to the fact that in logic, P => Q is roughly equivalent to not(P) or Q — the left side, P, is inside a negation. It also explains why in ((S -> T) -> Q) the S obeys the first rule, as if it was on the right side — because it’s negated twice.)

The following piece of code makes the analogy to function types more formally. Boxes behave as if their contents is on both sides of a function arrow — on the right because they’re readable, and on the left because they’re writable, which the conclusion that a (Boxof A) type is a subtype of itself and no other (Boxof B).

#lang pl

;; a type for a "read-only" box
(define-type (Boxof/R A) = (-> A))
;; Boxof/R constructor
(: box/r : (All (A) A -> (Boxof/R A)))
(define (box/r x) (lambda () x))
;; we can see that (Boxof/R T1) is a subtype of (Boxof/R T2)
;; if T1 is a subtype of T2 (this is not surprising, since
;; these boxes are similar to any other container, like lists):
(: foo1 : Integer -> (Boxof/R Integer))
(define (foo1 b) (box/r b))
(: bar1 : (Boxof/R Number) -> Number)
(define (bar1 b) (b))
(test (bar1 (foo1 123)) => 123)

;; a type for a "write-only" box
(define-type (Boxof/W A) = (A -> Void))
;; Boxof/W constructor
(: box/w : (All (A) A -> (Boxof/W A)))
(define (box/w x) (lambda (new) (set! x new)))
;; in contrast to the above, (Boxof/W T1) is a subtype of
;; (Boxof/W T2) if T2 is a subtype of T1, *not* the other way
;; (and note how this is related to A being on the *left* side
;; of the arrow in the `Boxof/W' type):
(: foo2 : Number -> (Boxof/W Number))
(define (foo2 b) (box/w b))
(: bar2 : (Boxof/W Integer) Integer -> Void)
(define (bar2 b new) (b new))
(test (bar2 (foo2 123) 456))

;; combining the above two into a type for a "read/write" box
(define-type (Boxof/RW A) = (A -> A))
;; Boxof/RW constructor
(: box/rw : (All (A) A -> (Boxof/RW A)))
(define (box/rw x) (lambda (new) (let ([old x]) (set! x new) old)))
;; this combines the above two: `A' appears on both sides of the
;; arrow, so (Boxof/RW T1) is a subtype of (Boxof/RW T2) if T1
;; is a subtype of T2 (because there's an A on the right) *and*
;; if T2 is a subtype of T1 (because there's another A on the
;; left) -- and that can happen only when T1 and T2 are the same
;; type.  So this is a type error:
;;  (: foo3 : Integer -> (Boxof/RW Integer))
;;  (define (foo3 b) (box/rw b))
;;  (: bar3 : (Boxof/RW Number) Number -> Number)
;;  (define (bar3 b new) (b new))
;;  (test (bar3 (foo3 123) 456) => 123)
;;  ** Expected (Number -> Number), but got (Integer -> Integer)
;; And this a type error too:
;;  (: foo3 : Number -> (Boxof/RW Number))
;;  (define (foo3 b) (box/rw b))
;;  (: bar3 : (Boxof/RW Integer) Integer -> Integer)
;;  (define (bar3 b new) (b new))
;;  (test (bar3 (foo3 123) 456) => 123)
;;  ** Expected (Integer -> Integer), but got (Number -> Number)
;; The two types must be the same for this to work:
(: foo3 : Integer -> (Boxof/RW Integer))
(define (foo3 b) (box/rw b))
(: bar3 : (Boxof/RW Integer) Integer -> Integer)
(define (bar3 b new) (b new))
(test (bar3 (foo3 123) 456) => 123)