1 # System F and recursive types
3 In the simply-typed lambda calculus, we write types like <code>σ
4 -> τ</code>. This looks like logical implication. We'll take
5 that resemblance seriously when we discuss the Curry-Howard
6 correspondence. In the meantime, note that types respect modus
10 Expression Type Implication
11 -----------------------------------
12 fn α -> β α ⊃ β
14 ------ ------ --------
15 (fn arg) β β
18 The implication in the right-hand column is modus ponens, of course.
20 System F was discovered by Girard (the same guy who invented Linear
21 Logic), but it was independently proposed around the same time by
22 Reynolds, who called his version the *polymorphic lambda calculus*.
23 (Reynolds was also an early player in the development of
26 System F enhances the simply-typed lambda calculus with abstraction
27 over types. In order to state System F, we'll need to adopt the
28 notational convention that "<code>x:α</code>" represents a
29 expression whose type is <code>α</code>.
31 Then System F can be specified as follows (choosing notation that will
32 match up with usage in O'Caml, whose type system is based on System F):
35 types τ ::= c | 'a | τ1 -> τ2 | ∀'a. τ
36 expressions e ::= x | λx:τ. e | e1 e2 | Λ'a. e | e [τ]
38 In the definition of the types, "`c`" is a type constant (e.g., `e` or
39 `t`). "`'a`" is a type variable (the tick mark just indicates that
40 the variable ranges over types rather than values). "`τ1 -> τ2`" is
41 the type of a function from expressions of type `τ1` to expressions of
42 type `τ2`. And "`∀'a. τ`" is called a universal type, since it
43 universally quantifies over the type variable `'a`.
45 In the definition of the expressions, we have variables "`x`".
46 Abstracts "`λx:τ. e`" are similar to abstracts in the simply-typed lambda
47 calculus, except that they have their shrug variable annotated with a
48 type. Applications "`e1 e2`" are just like in the simply-typed lambda calculus.
49 In addition to variables, abstracts, and applications, we have two
50 additional ways of forming expressions: "`Λ'a. e`" is a type
51 abstraction, and "`e [τ]`" is a type application. The idea is that
52 <code>Λ</code> is a capital <code>λ</code>. Just like
53 the lower-case <code>λ</code>, <code>Λ</code> binds
54 variables in its body; unlike <code>λ</code>,
55 <code>Λ</code> binds type variables. So in the expression
57 <code>Λ 'a (λ x:'a . x)</code>
59 the <code>Λ</code> binds the type variable `'a` that occurs in
60 the <code>λ</code> abstract. This expression is a polymorphic
61 version of the identity function. It says that this one general
62 identity function can be adapted for use with expressions of any
63 type. In order to get it ready to apply to, say, a variable of type
64 boolean, just do this:
66 <code>(Λ 'a (λ x:'a . x)) [t]</code>
68 The type application (where `t` is a type constant for Boolean truth
69 values) specifies the value of the type variable `α`, which is
70 the type of the variable bound in the `λ` expression. Not
71 surprisingly, the type of this type application is a function from
74 <code>((Λ 'a (λ x:'a . x)) [t]): (b -> b)</code>
76 Likewise, if we had instantiated the type variable as an entity (base
77 type `e`), the resulting identity function would have been a function
80 <code>((Λ 'a (λ x:'a . x)) [e]): (e -> e)</code>
82 Clearly, for any choice of a type `'a`, the identity function can be
83 instantiated as a function from expresions of type `'a` to expressions
84 of type `'a`. In general, then, the type of the unapplied
85 (polymorphic) identity function is
87 <code>(Λ 'a (λ x:'a . x)): (\forall 'a . 'a -> 'a)
99 OCaml has type inference: the system can often infer what the type of
100 an expression must be, based on the type of other known expressions.
102 For instance, if we type
106 The system replies with
108 val f : int -> int = <fun>
110 Since `+` is only defined on integers, it has type
113 - : int -> int -> int = <fun>
115 The parentheses are there to turn off the trick that allows the two
116 arguments of `+` to surround it in infix (for linguists, SOV) argument
122 In general, tuples with one element are identical to their one
128 though OCaml, like many systems, refuses to try to prove whether two
129 functional objects may be identical:
132 Exception: Invalid_argument "equal: functional value".
136 [Note: There is a limited way you can compare functions, using the
137 `==` operator instead of the `=` operator. Later when we discuss mutation,
138 we'll discuss the difference between these two equality operations.
139 Scheme has a similar pair, which they name `eq?` and `equal?`. In Python,
140 these are `is` and `==` respectively. It's unfortunate that OCaml uses `==` for the opposite operation that Python and many other languages use it for. In any case, OCaml will accept `(f) == f` even though it doesn't accept
141 `(f) = f`. However, don't expect it to figure out in general when two functions
142 are equivalent. (That question is not Turing computable.)
144 # (f) == (fun x -> x + 3);;
147 Here OCaml says (correctly) that the two functions don't stand in the `==` relation, which basically means they're not represented in the same chunk of memory. However as the programmer can see, the functions are extensionally equivalent. The meaning of `==` is rather weird.]
151 Booleans in OCaml, and simple pattern matching
152 ----------------------------------------------
154 Where we would write `true 1 2` in our pure lambda calculus and expect
155 it to evaluate to `1`, in OCaml boolean types are not functions
156 (equivalently, they're functions that take zero arguments). Instead, selection is
157 accomplished as follows:
159 # if true then 1 else 2;;
162 The types of the `then` clause and of the `else` clause must be the
165 The `if` construction can be re-expressed by means of the following
166 pattern-matching expression:
168 match <bool expression> with true -> <expression1> | false -> <expression2>
172 # match true with true -> 1 | false -> 2;;
177 # match 3 with 1 -> 1 | 2 -> 4 | 3 -> 9;;
183 All functions in OCaml take exactly one argument. Even this one:
185 # let f x y = x + y;;
189 Here's how to tell that `f` has been curry'd:
192 - : int -> int = <fun>
194 After we've given our `f` one argument, it returns a function that is
195 still waiting for another argument.
197 There is a special type in OCaml called `unit`. There is exactly one
198 object in this type, written `()`. So
203 Just as you can define functions that take constants for arguments
209 you can also define functions that take the unit as its argument, thus
212 val f : unit -> int = <fun>
214 Then the only argument you can possibly apply `f` to that is of the
215 correct type is the unit:
220 Now why would that be useful?
222 Let's have some fun: think of `rec` as our `Y` combinator. Then
224 # let rec f n = if (0 = n) then 1 else (n * (f (n - 1)));;
225 val f : int -> int = <fun>
229 We can't define a function that is exactly analogous to our ω.
230 We could try `let rec omega x = x x;;` what happens?
232 [Note: if you want to learn more OCaml, you might come back here someday and try:
235 val id : 'a -> 'a = <fun>
236 # let unwrap (`Wrap a) = a;;
237 val unwrap : [< `Wrap of 'a ] -> 'a = <fun>
238 # let omega ((`Wrap x) as y) = x y;;
239 val omega : [< `Wrap of [> `Wrap of 'a ] -> 'b as 'a ] -> 'b = <fun>
240 # unwrap (omega (`Wrap id)) == id;;
242 # unwrap (omega (`Wrap omega));;
243 <Infinite loop, need to control-c to interrupt>
245 But we won't try to explain this now.]
248 Even if we can't (easily) express omega in OCaml, we can do this:
250 # let rec blackhole x = blackhole x;;
252 By the way, what's the type of this function?
254 If you then apply this `blackhole` function to an argument,
258 the interpreter goes into an infinite loop, and you have to type control-c
261 Oh, one more thing: lambda expressions look like this:
265 # (fun x -> x) true;;
268 (But `(fun x -> x x)` still won't work.)
270 You may also see this:
272 # (function x -> x);;
275 This works the same as `fun` in simple cases like this, and slightly differently in more complex cases. If you learn more OCaml, you'll read about the difference between them.
277 We can try our usual tricks:
279 # (fun x -> true) blackhole;;
282 OCaml declined to try to fully reduce the argument before applying the
283 lambda function. Question: Why is that? Didn't we say that OCaml is a call-by-value/eager language?
285 Remember that `blackhole` is a function too, so we can
286 reverse the order of the arguments:
288 # blackhole (fun x -> true);;
292 Now consider the following variations in behavior:
294 # let test = blackhole blackhole;;
295 <Infinite loop, need to control-c to interrupt>
297 # let test () = blackhole blackhole;;
298 val test : unit -> 'a = <fun>
301 - : unit -> 'a = <fun>
304 <Infinite loop, need to control-c to interrupt>
306 We can use functions that take arguments of type `unit` to control
307 execution. In Scheme parlance, functions on the `unit` type are called
308 *thunks* (which I've always assumed was a blend of "think" and "chunk").
310 Question: why do thunks work? We know that `blackhole ()` doesn't terminate, so why do expressions like:
312 let f = fun () -> blackhole ()
317 Bottom type, divergence
318 -----------------------
320 Expressions that don't terminate all belong to the **bottom type**. This is a subtype of every other type. That is, anything of bottom type belongs to every other type as well. More advanced type systems have more examples of subtyping: for example, they might make `int` a subtype of `real`. But the core type system of OCaml doesn't have any general subtyping relations. (Neither does System F.) Just this one: that expressions of the bottom type also belong to every other type. It's as if every type definition in OCaml, even the built in ones, had an implicit extra clause:
322 type 'a option = None | Some of 'a;;
323 type 'a option = None | Some of 'a | bottom;;
325 Here are some exercises that may help better understand this. Figure out what is the type of each of the following:
333 let rec blackhole x = blackhole x in blackhole;;
335 let rec blackhole x = blackhole x in blackhole 1;;
337 let rec blackhole x = blackhole x in fun (y:int) -> blackhole y y y;;
339 let rec blackhole x = blackhole x in (blackhole 1) + 2;;
341 let rec blackhole x = blackhole x in (blackhole 1) || false;;
343 let rec blackhole x = blackhole x in 2 :: (blackhole 1);;
345 By the way, what's the type of this:
347 let rec blackhole (x:'a) : 'a = blackhole x in blackhole
350 Back to thunks: the reason you'd want to control evaluation with
351 thunks is to manipulate when "effects" happen. In a strongly
352 normalizing system, like the simply-typed lambda calculus or System F,
353 there are no "effects." In Scheme and OCaml, on the other hand, we can
354 write programs that have effects. One sort of effect is printing.
355 Another sort of effect is mutation, which we'll be looking at soon.
356 Continuations are yet another sort of effect. None of these are yet on
357 the table though. The only sort of effect we've got so far is
358 *divergence* or non-termination. So the only thing thunks are useful
359 for yet is controlling whether an expression that would diverge if we
360 tried to fully evaluate it does diverge. As we consider richer
361 languages, thunks will become more useful.