update arith1.ml
[lambda.git] / exercises / assignment1_answers.mdwn
1 1.  Define a function `zero?` that expects a single number as an argument, and returns `'true` if that number is `0`, else returns `'false`.
2
3         let
4           zero? match lambda x. case x of
5                                   0 then 'true;
6                                   y then 'false
7                                 end
8         in zero?
9
10
11 2.  Define a function `empty?` that expects a sequence of values as an argument (doesn't matter what type of values), and returns `'true` if that sequence is the empty sequence `[]`, else returns `'false`.
12
13         let
14           empty? match lambda xs. case xs of
15                                     []    then 'true;
16                                     _ & _ then 'false
17                                   end
18         in empty?
19
20     The second `case` clause could also just be `_ then 'false`.
21
22 3.  Define a function `tail` that expects a sequence of values as an argument (doesn't matter what type of values), and returns that sequence with the first element (if any) stripped away. (Applying `tail` to the empty sequence `[]` can just give us back the empty sequence.)
23
24         let
25           tail match lambda xs. case xs of
26                                   []      then [];
27                                   _ & xs' then xs'
28                                 end
29         in tail
30
31
32 4.  Define a function `drop` that expects two arguments, in the form (*number*, *sequence*), and works like this:
33
34         drop (0, [10, 20, 30])  # evaluates to [10, 20, 30]
35         drop (1, [10, 20, 30])  # evaluates to [20, 30]
36         drop (2, [10, 20, 30])  # evaluates to [30]
37         drop (3, [10, 20, 30])  # evaluates to []
38         drop (4, [10, 20, 30])  # evaluates to []
39
40     <!-- -->
41
42         letrec
43           drop match lambda (n, xs). case (n, xs) of
44                                        (0, _)       then xs;
45                                        (_, [])      then [];
46                                        (_, _ & xs') then drop (n-1, xs')
47                                      end
48         in drop
49
50     What is the relation between `tail` and `drop`?
51
52         let
53           tail xs = drop (1, xs)
54         in ...
55
56     That uses [[the shorthand explained here|topics/week1_kapulet_advanced#funct-declarations]], which I will continue to use below.
57
58 5.  Define a function `take` that expects two arguments, in the same form as `drop`, but works like this instead:
59
60         take (0, [10, 20, 30])  # evaluates to []
61         take (1, [10, 20, 30])  # evaluates to [10]
62         take (2, [10, 20, 30])  # evaluates to [10, 20]
63         take (3, [10, 20, 30])  # evaluates to [10, 20, 30]
64         take (4, [10, 20, 30])  # evaluates to [10, 20, 30]
65
66     <!-- -->
67
68         letrec
69           take (n, xs) = case (n, xs) of
70                            (0, _)        then [];
71                            (_, [])       then [];
72                            (_, x' & xs') then x' & take (n-1, xs')
73                          end
74         in take
75
76
77 6.  Define a function `split` that expects two arguments, in the same form as `drop` and `take`, but this time evaluates to a pair of results. It works like this:
78
79         split (0, [10, 20, 30])  # evaluates to ([], [10, 20, 30])
80         split (1, [10, 20, 30])  # evaluates to ([10], [20, 30])
81         split (2, [10, 20, 30])  # evaluates to ([10, 20], [30])
82         split (3, [10, 20, 30])  # evaluates to ([10, 20, 30], [])
83         split (4, [10, 20, 30])  # evaluates to ([10, 20, 30], [])
84
85     <!-- -->
86
87         letrec
88           split (n, xs) = case (n, xs) of
89                            (0, _)        then ([], xs);
90                            (_, [])       then ([], []);
91                            (_, x' & xs') then let
92                                                 (ys, zs) match split (n-1, xs')
93                                               in (x' & ys, zs)
94                           end
95         in split
96
97 7.  Write a function `filter` that expects two arguments. The second argument will be a sequence `xs` with elements of some type *t*, for example numbers. The first argument will be a function `p` that itself expects arguments of type *t* and returns `'true` or `'false`. What `filter` should return is a sequence that contains exactly those members of `xs` for which `p` returned `'true`.
98
99         letrec
100           filter (p, xs) = case xs of
101                              [] then [];
102                              x' & xs' when p x' then x' & filter (p, xs');
103                              _  & xs'           then      filter (p, xs')
104                            end
105         in filter
106
107     The above solution uses [[pattern guards|/topics/week1_kapulet_advanced#guards]].
108
109
110 8.  Write a function `partition` that expects two arguments, in the same form as `filter`, but this time evaluates to a pair of results. It works like this:
111
112         partition (odd?, [11, 12, 13, 14])  # evaluates to ([11, 13], [12, 14])
113         partition (odd?, [11])              # evaluates to ([11], [])
114         partition (odd?, [12, 14])          # evaluates to ([], [12, 14])
115
116     <!-- -->
117
118         letrec
119           partition (p, xs) = case xs of
120                                 []       then ([], []);
121                                 x' & xs' then let
122                                                 (ys, zs) match partition (p, xs')
123                                               in if p x' then (x' & ys, zs) else (ys, x' & zs)
124                               end
125         in partition
126
127
128 9.  Write a function `double` that expects one argument which is a sequence of numbers, and returns a sequence of the same length with the corresponding elements each being twice the value of the original element.
129
130         letrec
131           double xs = case xs of
132                         []       then [];
133                         x' & xs' then (2*x') & double xs'
134                       end
135         in double
136
137
138 10.  Write a function `map` that generalizes `double`. This function expects a pair of arguments, the second being a sequence `xs` with elements of some type *t*, for example numbers. The first argument will be a function `f` that itself expects arguments of type *t* and returns some type *t'* of result. What `map` should return is a sequence of the results, in the same order as the corresponding original elements. The result should be that we could say:
139
140         letrec
141           map match lambda (f, xs). case xs of
142                                       []       then [];
143                                       x' & xs' then (f x') & map (f, xs')
144                                     end;
145           double match lambda xs. map ((lambda x. 2*x), xs)
146         in ...
147
148 11. Write a function `map2` that generalizes `map`. This function expects a triple of arguments: the first being a function `f` as for `map`, and the second and third being two sequences. In this case `f` is a function that expects *two* arguments, one from the first of the sequences and the other from the corresponding position in the other sequence. The result should behave like this:
149
150         map2 ((lambda (x,y). 10*x + y), [1, 2, 3], [4, 5, 6])  # evaluates to [14, 25, 36]
151
152     <!-- -->
153
154         letrec
155           map2 (f, xs, ys) = case (xs, ys) of
156                                ([], _)              then [];
157                                (_, [])              then [];
158                                (x' & xs', y' & ys') then (f x' y') & map2 (f, xs', ys')
159                              end
160         in map2
161
162
163 ###Extra credit problems###
164
165 *   In class I mentioned a function `&&` which occupied the position *between* its arguments, rather than coming before them (this is called an "infix" function). The way that it works is that `[1, 2, 3] && [4, 5]` evaluates to `[1, 2, 3, 4, 5]`. Define this function, making use of `letrec` and the simpler infix operation `&`.
166
167         letrec
168           xs && ys = case xs of
169                        []       then ys;
170                        x' & xs' then x' & (xs' && ys)
171                      end
172         in (&&)
173
174     This solution is using a variation of [[the shorthand explained here|topics/week1_kapulet_advanced#funct-declarations]]. We didn't expect you'd know how to deal with the special syntax of `&&`. You might have just defined this using a regular name, like `append`.
175
176 *   Write a function `unmap2` that is something like the inverse of `map2`. This function expects two arguments, the second being a sequence of elements of some type *t*. The first is a function `g` that expects a single argument of type *t* and returns a *pair* of results, rather than just one result. We want to collate these results, the first into one sequence, and the second into a different sequence. Then `unmap2` should return those two sequences. Thus if:
177
178         g z1  # evaluates to (x1, y1)
179         g z2  # evaluates to (x2, y2)
180         g z3  # evaluates to (x3, y3)
181
182     Then `unmap2 (g, [z1, z2, z3])` should evaluate to `([x1, x2, x3], [y1, y2, y3])`.
183
184         letrec
185           unmap2 (g, zs) = case zs of
186                              []       then ([], []);
187                              z' & zs' then let
188                                              (x, y)   match g z';
189                                              (xs, ys) match unmap2 (g, zs')
190                                            in (x & xs, y & ys)
191                            end
192         in unmap2
193
194 *   Write a function `takewhile` that expects a `p` argument like `filter`, and also a sequence. The result should behave like this:
195
196         takewhile ((lambda x. x < 10), [1, 2, 20, 4, 40]) # evaluates to [1, 2]
197
198     Note that we stop "taking" once we reach `20`, even though there are still later elements in the sequence that are less than `10`.
199
200         letrec
201           takewhile (p, xs) = case xs of
202                                 []       then [];
203                                 x' & xs' then if p x' then x' & takewhile (p, xs')
204                                                       else []
205                               end
206         in takewhile
207
208 *   Write a function `dropwhile` that expects a `p` argument like `filter`, and also a sequence. The result should behave like this:
209
210         dropwhile ((lambda x. x < 10), [1, 2, 20, 4, 40]) # evaluates to [20, 4, 40]
211
212     Note that we stop "dropping" once we reach `20`, even though there are still later elements in the sequence that are less than `10`.
213
214         letrec
215           dropwhile (p, xs) = case xs of
216                                 x' & xs' when p x' then dropwhile (p, xs');
217                                 _ & _              then xs;
218                                 []                 then []
219                               end
220         in dropwhile
221
222     Unlike the previous solution, this one uses [[pattern guards|/topics/week1_kapulet_advanced#guards]], merely for variety. (In this solution the last two `case` clauses could also be replaced by the single clause `_ then xs`.)
223
224 *   Write a function `reverse` that returns the reverse of a sequence. Thus, `reverse [1, 2, 3, 4]` should evaluate to `[4, 3, 2, 1]`.
225
226         letrec
227           aux (ys, xs) = case xs of
228                            []       then ys;
229                            x' & xs' then aux (x' & ys, xs')
230                          end;
231           reverse xs = aux ([], xs)
232         in reverse
233