week9 tweak
[lambda.git] / week6.mdwn
1 [[!toc]]
2
3 Polymorphic Types and System F
4 ------------------------------
5
6 [Notes still to be added. Hope you paid attention during seminar.]
7
8 <!--
9
10 8.      The simply-typed lambda calculus<p>
11 9.      Parametric polymorphism, System F, "type inference"<p>
12
13 1.      Product or record types, e.g. pairs and triples
14 2.      Sum or variant types; tagged or "disjoint" unions
15 3.      Maybe/option types; representing "out-of-band" values
16 10.     [Phil/ling application] inner/outer domain semantics for positive free logic
17         <http://philosophy.ucdavis.edu/antonelli/papers/pegasus-JPL.pdf>
18 11.     [Phil/ling application] King vs Schiffer in King 2007, pp 103ff. [which paper?](http://rci.rutgers.edu/~jeffreck/pub.php)
19 12. [Phil/ling application] King and Pryor on that clauses, predicates vs singular property-designators
20         Russell On Denoting / Kaplan on plexy
21 13.     Possible excursion: [Frege's "On Concept and Object"](http://www.persiangig.com/pages/download/?dl=http://sahmir.persiangig.com/document/Frege%27s%20Articles/On%20Concept%20And%20object%20%28Jstore%29.pdf)<p>
22
23 6.      Inductive types (numbers, lists)
24
25 5.      Unit type
26 4.      Zero/bottom types
27 7.      "Pattern-matching" or type unpacking<p>
28
29 -->
30
31
32 Types in OCaml
33 --------------
34
35 OCaml has type inference: the system can often infer what the type of
36 an expression must be, based on the type of other known expressions.
37
38 For instance, if we type
39
40     # let f x = x + 3;;
41
42 The system replies with
43
44     val f : int -> int = <fun>
45
46 Since `+` is only defined on integers, it has type
47
48      # (+);;
49      - : int -> int -> int = <fun>
50
51 The parentheses are there to turn off the trick that allows the two
52 arguments of `+` to surround it in infix (for linguists, SOV) argument
53 order. That is,
54
55     # 3 + 4 = (+) 3 4;;
56     - : bool = true
57
58 In general, tuples with one element are identical to their one
59 element:
60
61     # (3) = 3;;
62     - : bool = true
63
64 though OCaml, like many systems, refuses to try to prove whether two
65 functional objects may be identical:
66
67     # (f) = f;;
68     Exception: Invalid_argument "equal: functional value".
69
70 Oh well.
71
72 [Note: There is a limited way you can compare functions, using the
73 `==` operator instead of the `=` operator. Later when we discuss mutation,
74 we'll discuss the difference between these two equality operations.
75 Scheme has a similar pair, which they name `eq?` and `equal?`. In Python,
76 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
77 `(f) = f`. However, don't expect it to figure out in general when two functions
78 are equivalent. (That question is not Turing computable.)
79
80         # (f) == (fun x -> x + 3);;
81         - : bool = false
82
83 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.]
84
85
86
87 Booleans in OCaml, and simple pattern matching
88 ----------------------------------------------
89
90 Where we would write `true 1 2` in our pure lambda calculus and expect
91 it to evaluate to `1`, in OCaml boolean types are not functions
92 (equivalently, they're functions that take zero arguments). Instead, selection is
93 accomplished as follows:
94
95     # if true then 1 else 2;;
96     - : int = 1
97
98 The types of the `then` clause and of the `else` clause must be the
99 same.
100
101 The `if` construction can be re-expressed by means of the following
102 pattern-matching expression:
103
104     match <bool expression> with true -> <expression1> | false -> <expression2>
105
106 That is,
107
108     # match true with true -> 1 | false -> 2;;
109     - : int = 1
110
111 Compare with
112
113     # match 3 with 1 -> 1 | 2 -> 4 | 3 -> 9;;
114     - : int = 9
115
116 Unit and thunks
117 ---------------
118
119 All functions in OCaml take exactly one argument.  Even this one:
120
121     # let f x y = x + y;;
122     # f 2 3;;
123     - : int = 5
124
125 Here's how to tell that `f` has been curry'd:
126
127     # f 2;;
128     - : int -> int = <fun>
129
130 After we've given our `f` one argument, it returns a function that is
131 still waiting for another argument.
132
133 There is a special type in OCaml called `unit`.  There is exactly one
134 object in this type, written `()`.  So
135
136     # ();;
137     - : unit = ()
138
139 Just as you can define functions that take constants for arguments
140
141     # let f 2 = 3;;
142     # f 2;;
143     - : int = 3;;
144
145 you can also define functions that take the unit as its argument, thus
146
147     # let f () = 3;;
148     val f : unit -> int = <fun>
149
150 Then the only argument you can possibly apply `f` to that is of the
151 correct type is the unit:
152
153     # f ();;
154     - : int = 3
155
156 Now why would that be useful?
157
158 Let's have some fun: think of `rec` as our `Y` combinator.  Then
159
160     # let rec f n = if (0 = n) then 1 else (n * (f (n - 1)));;
161     val f : int -> int = <fun>
162     # f 5;;
163     - : int = 120
164
165 We can't define a function that is exactly analogous to our &omega;.
166 We could try `let rec omega x = x x;;` what happens?
167
168 [Note: if you want to learn more OCaml, you might come back here someday and try:
169
170         # let id x = x;;
171         val id : 'a -> 'a = <fun>
172         # let unwrap (`Wrap a) = a;;
173         val unwrap : [< `Wrap of 'a ] -> 'a = <fun>
174         # let omega ((`Wrap x) as y) = x y;;
175         val omega : [< `Wrap of [> `Wrap of 'a ] -> 'b as 'a ] -> 'b = <fun>
176         # unwrap (omega (`Wrap id)) == id;;
177         - : bool = true
178         # unwrap (omega (`Wrap omega));;
179     <Infinite loop, need to control-c to interrupt>
180
181 But we won't try to explain this now.]
182
183
184 Even if we can't (easily) express omega in OCaml, we can do this:
185
186     # let rec blackhole x = blackhole x;;
187
188 By the way, what's the type of this function?
189
190 If you then apply this `blackhole` function to an argument,
191
192     # blackhole 3;;
193
194 the interpreter goes into an infinite loop, and you have to type control-c
195 to break the loop.
196
197 Oh, one more thing: lambda expressions look like this:
198
199     # (fun x -> x);;
200     - : 'a -> 'a = <fun>
201     # (fun x -> x) true;;
202     - : bool = true
203
204 (But `(fun x -> x x)` still won't work.)
205
206 You may also see this:
207
208         # (function x -> x);;
209         - : 'a -> 'a = <fun>
210
211 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.
212
213 We can try our usual tricks:
214
215     # (fun x -> true) blackhole;;
216     - : bool = true
217
218 OCaml declined to try to fully reduce the argument before applying the
219 lambda function. Question: Why is that? Didn't we say that OCaml is a call-by-value/eager language?
220
221 Remember that `blackhole` is a function too, so we can
222 reverse the order of the arguments:
223
224     # blackhole (fun x -> true);;
225
226 Infinite loop.
227
228 Now consider the following variations in behavior:
229
230     # let test = blackhole blackhole;;
231     <Infinite loop, need to control-c to interrupt>
232
233     # let test () = blackhole blackhole;;
234     val test : unit -> 'a = <fun>
235
236     # test;;
237     - : unit -> 'a = <fun>
238
239     # test ();;
240     <Infinite loop, need to control-c to interrupt>
241
242 We can use functions that take arguments of type `unit` to control
243 execution.  In Scheme parlance, functions on the `unit` type are called
244 *thunks* (which I've always assumed was a blend of "think" and "chunk").
245
246 Question: why do thunks work? We know that `blackhole ()` doesn't terminate, so why do expressions like:
247
248         let f = fun () -> blackhole ()
249         in true
250
251 terminate?
252
253 Bottom type, divergence
254 -----------------------
255
256 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:
257
258         type 'a option = None | Some of 'a;;
259         type 'a option = None | Some of 'a | bottom;;
260
261 Here are some exercises that may help better understand this. Figure out what is the type of each of the following:
262
263         fun x y -> y;;
264
265         fun x (y:int) -> y;;
266
267         fun x y : int -> y;;
268
269         let rec blackhole x = blackhole x in blackhole;;
270
271         let rec blackhole x = blackhole x in blackhole 1;;
272
273         let rec blackhole x = blackhole x in fun (y:int) -> blackhole y y y;;
274
275         let rec blackhole x = blackhole x in (blackhole 1) + 2;;
276
277         let rec blackhole x = blackhole x in (blackhole 1) || false;;
278
279         let rec blackhole x = blackhole x in 2 :: (blackhole 1);;
280
281 By the way, what's the type of this:
282
283         let rec blackhole (x:'a) : 'a = blackhole x in blackhole
284
285
286 Back to thunks: the reason you'd want to control evaluation with thunks is to
287 manipulate when "effects" happen. In a strongly normalizing system, like the
288 simply-typed lambda calculus or System F, there are no "effects." In Scheme and
289 OCaml, on the other hand, we can write programs that have effects. One sort of
290 effect is printing (think of the [[damn]] example at the start of term).
291 Another sort of effect is mutation, which we'll be looking at soon.
292 Continuations are yet another sort of effect. None of these are yet on the
293 table though. The only sort of effect we've got so far is *divergence* or
294 non-termination. So the only thing thunks are useful for yet is controlling
295 whether an expression that would diverge if we tried to fully evaluate it does
296 diverge. As we consider richer languages, thunks will become more useful.
297
298
299 Towards Monads
300 --------------
301
302 This has now been moved to the start of [[week7]].
303