Merge branch 'pryor'
[lambda.git] / assignment5.mdwn
1 Types and OCAML
2
3 1. Which of the following expressions is well-typed in OCAML?  
4    For those that are, give the type of the expression as a whole.
5    For those that are not, why not?
6
7     let rec f x = f x;;
8
9     let rec f x = f f;;
10
11     let rec f x = f x in f f;;
12
13     let rec f x = f x in f ();;
14
15     let rec f () = f f;;
16
17     let rec f () = f ();;
18
19     let rec f () = f () in f f;;
20
21     let rec f () = f () in f ();;
22
23 2. Throughout this problem, assume that we have 
24
25     let rec omega x = omega x;;
26
27    All of the following are well-typed.
28    Which ones terminate?  What are the generalizations?
29
30     omega;;
31
32     omega ();;
33
34     fun () -> omega ();;
35
36     (fun () -> omega ()) ();;
37
38     if true then omega else omega;;
39
40     if false then omega else omega;;
41
42     if true then omega else omega ();;
43
44     if false then omega else omega ();;
45
46     if true then omega () else omega;;
47
48     if false then omega () else omega;;
49
50     if true then omega () else omega ();;
51
52     if false then omega () else omega ();;
53
54     let _ = omega in 2;;
55
56     let _ = omega () in 2;;
57
58 3. The following expression is an attempt to make explicit the
59 behavior of `if`-`then`-`else` explored in the previous question.
60 The idea is to define an `if`-`then`-`else` expression using 
61 other expression types.  So assume that "yes" is any OCAML expression,
62 and "no" is any other OCAML expression (of the same type as "yes"!),
63 and that "bool" is any boolean.  Then we can try the following:
64 "if bool then yes else no" should be equivalent to
65
66     let b = bool in
67     let y = yes in 
68     let n = no in 
69     match b with true -> y | false -> n
70
71 This almost works.  For instance, 
72
73     if true then 1 else 2;;
74
75 evaluates to 1, and 
76
77     let b = true in let y = 1 in let n = 2 in 
78     match b with true -> y | false -> n;;
79
80 also evaluates to 1.  Likewise,
81
82     if false then 1 else 2;;
83
84 and
85
86     let b = false in let y = 1 in let n = 2 in 
87     match b with true -> y | false -> n;;
88
89 both evaluate to 2.
90
91 However,
92
93     let rec omega x = omega x in 
94     if true then omega else omega ();;
95
96 terminates, but 
97
98     let rec omega x = omega x in 
99     let b = true in
100     let y = omega in 
101     let n = omega () in 
102     match b with true -> y | false -> n;;
103
104 does not terminate.  Incidentally, `match bool with true -> yes |
105 false -> no;;` works as desired, but your assignment is to solve it
106 without using the magical evaluation order properties of either `if`
107 or of `match`.  That is, you must keep the `let` statements, though
108 you're allowed to adjust what `b`, `y`, and `n` get assigned to.
109
110 [[Hint assignment 5 problem 3]]