-
Notifications
You must be signed in to change notification settings - Fork 0
/
Poly.thy
2048 lines (1697 loc) · 64 KB
/
Poly.thy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
theory Poly
imports Main Basics Lists
begin
(* (** * Poly: Polymorphism and Higher-Order Functions *)
(* Version of 4/7/2010 *)
Require Export Lists.
(* ###################################################### *)
(** * Polymorphism *)
(* ###################################################### *)
(** ** Polymorphic lists *)
(** Up to this point, we've been working with lists of numbers.
Programs also need to be able to manipulate lists whose elements
are drawn from other types -- lists of strings, lists of booleans,
lists of lists, etc. We could define a new inductive datatype for
each of these, for example... *)
Inductive boollist : Type :=
| bool_nil : boollist
| bool_cons : bool -> boollist -> boollist.
(** ... but this would quickly become tedious,
partly because we have to make up different
constructor names for each datatype but mostly because
we would also need to define new versions of all our
list manipulating functions ([length], [rev], etc.)
for each new datatype definition. *)
(** To avoid all this repetition, Coq supports _polymorphic_
inductive type definitions. For example, here is a polymorphic
list data type. *)
Inductive list (X:Type) : Type :=
| nil : list X
| cons : X -> list X -> list X.
*)
(* CH: As we've previously discussed, there's polymorphic inductive datatypes
in Isabelle. Most of this material related to implicit parameters
isn't particularly relevant *)
(*
(** This is exactly like the definition of [natlist] from the
previous chapter, except that the [nat] argument to the [cons]
constructor has been replaced by an arbitrary type [X], a binding
for [X] has been added to the header, and the occurrences of
[natlist] in the types of the constructors have been replaced by
[list X]. (We're able to re-use the constructor names [nil] and
[cons] because the earlier definition of [natlist] was inside of a
[Module] definition that is now out of scope.) *)
(** With this definition, when we use the constructors [nil] and
[cons] to build lists, we need to specify what sort of lists we
are building -- that is, [nil] and [cons] are now "polymorphic
constructors". Observe the types of these constructors: *)
Check nil.
Check cons.
(** The "[forall X]" in these types should be read as an
additional argument to the constructors that determines the
expected types of the arguments that follow. When [nil] and
[cons] are used, these arguments are supplied in the same way as
the others. For example, the list containing [2] and [1] is
written like this: *)
Check (cons nat 2 (cons nat 1 (nil nat))).
(** We can now go back and make polymorphic (or "generic")
versions of all the list-processing functions that we wrote
before. Here is [length], for example: *)
Fixpoint length (X:Type) (l:list X) : nat :=
match l with
| nil => 0
| cons h t => S (length X t)
end.
(** The uses of [nil] and [cons] in [match] patterns do not
require any type annotations: we already know that the list [l]
contains elements of type [X], so there's no reason to include [X]
in the pattern. (More formally, the type [X] is a parameter of
the whole definition of [list], not of the individual
constructors.)
Just as we did with [nil] and [cons], to use [length] we apply it
first to a type and then to its list argument: *)
Example test_length1 :
length nat (cons nat 1 (cons nat 2 (nil nat))) = 2.
Proof. reflexivity. Qed.
(** (We are writing [nil] and [cons] here because we haven't yet
defined the [ [] ] and [::] notations. We'll do that in a
bit.) *)
(** To use our length with other kinds of lists, we simply
instantiate it with an appropriate type parameter: *)
Example test_length2 :
length bool (cons bool true (nil bool)) = 1.
Proof. reflexivity. Qed.
Fixpoint app (X : Type) (l1 l2 : list X)
: (list X) :=
match l1 with
| nil => l2
| cons h t => cons X h (app X t l2)
end.
Fixpoint snoc (X:Type) (l:list X) (v:X) : (list X) :=
match l with
| nil => cons X v (nil X)
| cons h t => cons X h (snoc X t v)
end.
Fixpoint rev (X:Type) (l:list X) : list X :=
match l with
| nil => nil X
| cons h t => snoc X (rev X t) h
end.
Example test_rev1 :
rev nat (cons nat 1 (cons nat 2 (nil nat)))
= (cons nat 2 (cons nat 1 (nil nat))).
Proof. reflexivity. Qed.
Example test_rev2:
rev bool (nil bool) = nil bool.
Proof. reflexivity. Qed.
(* ###################################################### *)
(** *** Argument Synthesis *)
*)
(*
(** Whenever we use a polymorphic function, we need to pass it
one or more types in addition to its other arguments. For
example, the recursive call in the body of the [length] function
above must pass along the type [X]. But this is a bit heavy and
verbose: Since the second argument to [length] is a list of [X]s,
it seems entirely obvious that the first argument can only be
[X] -- why should we have to write it explicitly?
Fortunately, Coq permits us to avoid this kind of redundancy. In
place of any type argument we can write the "implicit argument"
[_], which can be read as "Please figure out for yourself what
type belongs here." More precisely, when Coq encounters a [_], it
will attempt to "unify" all locally available information -- the
type of the function being applied, the types of the other
arguments, and the type expected by the context in which the
application appears -- to determine what concrete type should
replace the [_].
Using implicit arguments, the [length] function can be written
like this: *)
Fixpoint length' (X:Type) (l:list X) : nat :=
match l with
| nil => 0
| cons h t => S (length' _ t)
end.
(** In this instance, the savings of writing [_] instead of [X] is
small. But in other cases the difference is significant. For
example, suppose we want to write down a list containing the
numbers [1], [2], and [3]. Instead of writing this... *)
Definition list123'' :=
cons nat 1 (cons nat 2 (cons nat 3 (nil nat))).
(** ...we can use argument synthesis to write this: *)
Definition list123 := cons _ 1 (cons _ 2 (cons _ 3 (nil _))).
(* ###################################################### *)
(** *** Implicit arguments *)
(** To avoid writing too many [_]'s, we can also tell Coq that we
_always_ want it to infer the type argument(s) of a given
function. *)
Implicit Arguments nil [[X]].
Implicit Arguments cons [[X]].
Implicit Arguments length [[X]].
Implicit Arguments app [[X]].
Implicit Arguments rev [[X]].
Implicit Arguments snoc [[X]].
Check (length list123). (* note: no _ *)
(** We can also conveniently declare an argument to be implicit
while defining the function itself, by surrounding the argument in
curly braces. For example: *)
Fixpoint length'' {X:Type} (l:list X) : nat :=
match l with
| nil => 0
| cons h t => S (length'' t)
end.
(** Note that in this case, we didn't even have to provide a
type argument to the recursive call to [length'']. We will use
this style whenever possible, although we will continue to use use
explicit [Implicit Argument] declarations for [Inductive]
constructors. *)
(** One small problem with declaring arguments [Implicit] is
that, occasionally, there will not be enough local information to
determine a type argument and we will need to tell Coq specially
that we want to give it explicitly even though we've declared it
to be [Implicit]. For example, if we write: *)
(* Definition mynil := nil. *)
(** Coq will give us an error, because it doesn't know what type
argument to supply to [nil]. We can help it by providing an
explicit type declaration: *)
Definition mynil : list nat := nil.
(** Using argument synthesis and implicit arguments, we can
define convenient notation for lists, as before. Since we have
made the constructor type arguments implicit, Coq will know to
automatically infer the type when we use these. *)
Notation "x :: y" := (cons x y)
(at level 60, right associativity).
Notation "[ ]" := nil.
Notation "[ x , .. , y ]" := (cons x .. (cons y []) ..).
Notation "x ++ y" := (app x y)
(at level 60, right associativity).
(** Now lists can be written just the way we'd hope: *)
Definition list123' := [1, 2, 3].
(* ###################################################### *)
(** *** Exercises: Polymorphic lists *)
(** **** Exercise: 2 stars, optional (poly_exercises) *)
(** Here are a few simple exercises, just like ones in Lists.v, for
practice with polymorphism. Fill in the definitions and complete
the proofs below. *)
Fixpoint repeat (X : Type) (n : X) (count : nat) : list X :=
(* SOLUTION: *)
match count with
| O => nil
| S count' => cons n (repeat _ n count')
end.
Example test_repeat1:
repeat bool true 2 = cons true (cons true nil).
(* SOLUTION: *)
Proof. reflexivity. Qed.
Theorem nil_app : forall X:Type, forall l:list X,
app [] l = l.
Proof.
(* SOLUTION: *)
reflexivity.
Qed.
Theorem rev_snoc : forall X : Type,
forall v : X,
forall s : list X,
rev (snoc s v) = v :: (rev s).
Proof.
(* SOLUTION: *)
intros X v s. induction s as [| v' s'].
Case "s = []".
reflexivity.
Case "s = v' :: s'".
simpl. rewrite -> IHs'. reflexivity.
Qed.
(** **** Exercise: 2 stars, optional *)
Theorem snoc_with_append : forall X : Type,
forall l1 l2 : list X,
forall v : X,
snoc (l1 ++ l2) v = l1 ++ (snoc l2 v).
Proof.
(* SOLUTION: *)
intros X l1 l2 v. induction l1 as [| v1 l1'].
Case "l1 = []".
reflexivity.
Case "l1 = v1 :: l1'".
simpl. rewrite -> IHl1'. reflexivity.
Qed.
(** [] *)
(* ###################################################### *)
(** ** Polymorphic pairs *)
(** Similarly, the type definition we gave above for pairs of
numbers can be generalized to "polymorphic pairs": *)
Inductive prod (X Y : Type) : Type :=
pair : X -> Y -> prod X Y.
(** As with lists, we make the type arguments implicit and define the
familiar concrete notation. *)
Implicit Arguments pair [X Y].
Notation "( x , y )" := (pair x y).
(** We can also use the [Notation] mechanism to define the standard
notation for pair _types_: *)
Notation "X * Y" := (prod X Y) : type_scope.
(** (The annotation [: type_scope] tells Coq that this abbreviation
should be used when parsing types.) *)
(** The first and second projection functions now look pretty
much as they would in any functional programming language. *)
Definition fst {X Y : Type} (p : X * Y) : X :=
match p with (x,y) => x end.
Definition snd {X Y : Type} (p : X * Y) : Y :=
match p with (x,y) => y end.
(** The following function takes two lists and combines them
into a list of pairs. (In many functional programming languages,
it is called [zip]. We call it [combine] for consistency with
Coq's standard library.) *)
*)
(* CH: I'm going to do these using the built in list and product operators.
If that's cheating, let me know!
*)
(*
Fixpoint combine {X Y : Type} (lx : list X) (ly : list Y)
: list (X*Y) :=
match lx with
| [] => []
| x::tx => match ly with
| [] => []
| y::ty => (x,y) :: (combine tx ty)
end
end.
*)
fun combine :: "'a list \<Rightarrow> 'b list \<Rightarrow> ('a \<times> 'b) list" where
"combine [] _ = []" |
"combine _ [] = []" |
"combine (x # xs) (y # ys) = (x,y) # (combine xs ys)"
(*
(** **** Exercise: 1 star (combine_checks) *)
(** Try answering the following questions on paper and
checking your answers in coq:
- What is the type of [combine] (i.e., what does [Check
@combine] print?)
- What does
[[
Eval simpl in (combine [1,2] [false,false,true,true]).
]]
print? []
*)
(** **** Exercise: 2 stars *)
(** The function [split] is the inverse of combine: it takes a list of
pairs and returns a pair of lists. In many functional programing
languages, this function is called "unzip".
Uncomment the material below and fill in the definition of
[split]. Make sure it passes the given unit tests. *)
Fixpoint split
(* SOLUTION: *)
{X Y : Type} (l : list (X*Y))
: (list X) * (list Y) :=
match l with
| [] =>
([], [])
| cons (x,y) t =>
match split t with
(lx,ly) => (x::lx, y::ly)
end
end.
*)
fun split :: "('a \<times> 'b) list \<Rightarrow> ('a list \<times> 'b list)" where
"split [] = ([],[])" |
"split ((x,y) # xys) = (case (split xys) of
(xs,ys) \<Rightarrow> (x # xs, y # ys))"
(*
Example test_split:
split [(1,false),(2,false)] = ([1,2],[false,false]).
Proof. reflexivity. Qed.
(** [] *)
(* ###################################################### *)
(** ** Polymorphic options *)
(** One last polymorphic type for now: "polymorphic options".
The type declaration generalizes the one for [natoption] from the
previous chapter: *)
Inductive option (X:Type) : Type :=
| Some : X -> option X
| None : option X.
Implicit Arguments Some [X].
Implicit Arguments None [X].
(** We can now rewrite the [index] function so that it works
with any type of lists. *)
Fixpoint index
{X : Type} (n : nat)
(l : list X) : option X :=
match l with
| [] => None
| a :: l' => if beq_nat n O then Some a else index (pred n) l'
end.
Example test_index1 : index 0 [4,5,6,7] = Some 4.
Proof. reflexivity. Qed.
Example test_index2 : index 1 [[1],[2]] = Some [2].
Proof. reflexivity. Qed.
Example test_index3 : index 2 [true] = None.
Proof. reflexivity. Qed.
(** **** Exercise: 1 star *)
(** Complete the definition of a polymorphic version of the
[hd_opt] function from the last chapter. Be sure that it
passes the unit tests below. *)
Definition hd_opt {X : Type} (l : list X) : option X :=
(* SOLUTION: *)
match l with
| [] => None
| a :: l' => Some a
end.
(** To force the implicit arguments to be explicit, we can use [@]
before the name of a function. *)
Check @hd_opt.
Example test_hd_opt1 : hd_opt [1,2] = Some 1.
(* SOLUTION: *)
Proof. reflexivity. Qed.
Example test_hd_opt2 : hd_opt [[1],[2]] = Some [1].
(* SOLUTION: *)
Proof. reflexivity. Qed.
(** [] *)
(* ###################################################### *)
(** * Functions as Data *)
(* ###################################################### *)
(** ** Higher-order functions *)
(** Like many other modern programming languages -- including,
of course, all "functional languages" -- Coq treats functions as
first-class citizens: it allows functions to be passed as
arguments to other functions, returned as results from other
functions, stored in data structures, etc.
Functions that manipulate other functions are called
"higher-order" functions. Here's a simple one: *)
Definition doit3times {X:Type} (f:X->X) (n:X) : X :=
f (f (f n)).
(** The argument [f] here is itself a function (from [X] to
[X]); the body of [doit3times] applies [f] three times to some
value [n]. *)
Check @doit3times.
Example test_doit3times: doit3times minustwo 9 = 3.
Proof. reflexivity. Qed.
Example test_doit3times': doit3times negb true = false.
Proof. reflexivity. Qed.
(* ###################################################### *)
(** ** Partial application *)
(** In fact, the multiple-argument functions we have already
seen are also examples of higher-order functions. For instance,
the type of [plus] is [nat -> nat -> nat]. *)
Check plus.
(** Since [->] is _right-associative_, this type can
equivalently be written [nat -> (nat -> nat)] -- i.e., it can be
read as saying that "[plus] is a one-argument function that takes
a [nat] and returns a one-argument function that takes another
[nat] and returns a [nat]." In the examples above, we have always
applied [plus] to both of its arguments at once, but if we like we
can supply just the first. This is called "partial
application." *)
Definition plus3 := plus 3.
Check plus3.
Example test_plus3 : plus3 4 = 7.
Proof. reflexivity. Qed.
Example test_plus3' : doit3times plus3 0 = 9.
Proof. reflexivity. Qed.
Example test_plus3'' : doit3times (plus 3) 0 = 9.
Proof. reflexivity. Qed.
(* ###################################################### *)
(** ** Digression: Currying *)
(** **** Exercise: 2 stars, optional (currying) *)
(** In Coq, a function [f : A -> B -> C] really has the type [A
-> (B -> C)]. That is, if you give [f] a value of type [A], it
will give you function [f' : B -> C]. If you then give [f'] a
value of type [B], it will return a value of type [C]. This
allows for partial application, as in [plus3]. Processing a list
of arguments with functions that return functions is called
"currying", named in honor of the logician Haskell Curry.
Conversely, we can reinterpret the type [A -> B -> C] as [(A *
B) -> C]. This is called "uncurrying". In an uncurried binary
function, both arguments must be given at once as a pair; there is
no partial application. *)
(** We can define currying as follows: *)
Definition prod_curry {X Y Z : Type}
(f : X * Y -> Z) (x : X) (y : Y) : Z := f (x, y).
(** As an exercise, define its inverse, [prod_uncurry]. Then prove
the theorems below to show that the two are inverses. *)
Definition prod_uncurry {X Y Z : Type}
(f : X -> Y -> Z) (p : X * Y) : Z :=
(* SOLUTION: *)
match p with
(x,y) => f x y
end.
(** (Thought exercise: before running these commands, can you
calculate the types of [prod_curry] and [prod_uncurry]?) *)
Check @prod_curry.
Check @prod_uncurry.
Theorem uncurry_curry : forall (X Y Z : Type) (f : X -> Y -> Z) x y,
prod_curry (prod_uncurry f) x y = f x y.
Proof.
(* SOLUTION: *)
intros X Y Z f x y.
reflexivity.
Qed.
Theorem curry_uncurry : forall (X Y Z : Type) (f : (X * Y) -> Z) (p : X * Y),
prod_uncurry (prod_curry f) p = f p.
Proof.
(* SOLUTION: *)
intros X Y Z f p.
destruct p as [x y].
reflexivity.
Qed.
(** [] *)
(* ###################################################### *)
(** ** Filter *)
(** Here is a useful higher-order function, which takes a list
of [X]s and a predicate on [X] (a function from [X] to [bool]) and
"filters" the list, returning a new list containing just those
elements for which the predicate returns [true]. *)
Fixpoint filter {X:Type} (test: X->bool) (l:list X)
: (list X) :=
match l with
| [] => []
| h :: t => if test h then h :: (filter test t)
else filter test t
end.
(** For example, if we apply [filter] to the predicate [evenb]
and a list of numbers [l], it returns a list containing just the
even members of [l]. *)
Example test_filter1: filter evenb [1,2,3,4] = [2,4].
Proof. reflexivity. Qed.
Definition length_is_1 {X : Type} (l : list X) : bool :=
beq_nat (length l) 1.
Example test_filter2:
filter length_is_1
[ [1, 2], [3], [4], [5,6,7], [], [8] ]
= [ [3], [4], [8] ].
Proof. reflexivity. Qed.
(** We can use [filter] to give a concise version of the
[countoddmembers] function from [Lists.v]. *)
Definition countoddmembers' (l:list nat) : nat :=
length (filter oddb l).
Example test_countoddmembers'1: countoddmembers' [1,0,3,1,4,5] = 4.
Proof. reflexivity. Qed.
Example test_countoddmembers'2: countoddmembers' [0,2,4] = 0.
Proof. reflexivity. Qed.
Example test_countoddmembers'3: countoddmembers' nil = 0.
Proof. reflexivity. Qed.
(* ###################################################### *)
(** ** Anonymous functions *)
(** It was annoying to be forced to define the function
[length_is_1] and give it a name just to be able to pass it as an
argument to [filter], since we will probably never use it again.
This is not an isolated example. When using higher-order
functions, we will often pass as arguments "one-off" functions
that we will never use again; having to give each of these
functions a name would be tedious.
However, there is a solution. It is also possible to construct a
function "on the fly" without declaring it at the top level or
giving it a name; this is analogous to the notation we've been
using for writing down constant lists, etc. *)
*)
(* CH: In Isabelle, we declare anonymous function as lambda expressions
e.g. (\<lambda>x. x) *)
(*
Example test_anon_fun:
doit3times (fun (n:nat) => mult n n) 2 = 256.
Proof. reflexivity. Qed.
(** The expression [fun (n:nat) => mult n n] here can be read
"The function that, given a number [n], returns [mult n n]."
We don't actually need to bother declaring the type of the
argument [n]; Coq can see that it must be [nat] by looking at the
context. This convenient capability is called _type inference_. *)
Example test_anon_fun':
doit3times (fun n => mult n n) 2 = 256.
Proof. reflexivity. Qed.
(** Here is our motivating example from before, rewritten to use
an anonymous function. *)
Example test_filter2':
filter (fun l => beq_nat (length l) 1)
[ [1, 2], [3], [4], [5,6,7], [], [8] ]
= [ [3], [4], [8] ].
Proof. reflexivity. Qed.
(** **** Exercise: 2 stars, optional *)
(** Use [filter] to write a coq function [partition]:
[[
partition : forall X : Type, (X -> bool) -> list X -> list X * list X
]]
Given a set [X], a test function of type [X -> bool] and a [list
X], [partition] should return a pair of lists. The first member
the pair is the sublist of the original list containing the
elements that satisfy the test, and the second is the sublist
containing those that fail the test. The order of elements in the
two sublists should be the same as their order in the original
list.
*)
Definition partition {X : Type} (test : X -> bool) (l : list X)
: list X * list X :=
(* SOLUTION: *)
(filter test l, filter (fun x => negb (test x)) l).
Example test_partition1: partition oddb [1,2,3,4,5] = ([1,3,5], [2,4]).
(* SOLUTION: *)
Proof. reflexivity. Qed.
Example test_partition2: partition (fun x => false) [5,9,0] = ([], [5,9,0]).
(* SOLUTION: *)
Proof. reflexivity. Qed.
(** [] *)
(* ###################################################### *)
(** ** Map *)
(** Another handy higher-order function is called [map]. *)
Fixpoint map {X Y:Type} (f:X->Y) (l:list X)
: (list Y) :=
match l with
| [] => []
| h :: t => (f h) :: (map f t)
end.
(** It takes a function [f] and a list [ l = [n1, n2, n3, ...] ]
and returns the list [ [f n1, f n2, f n3,...] ], where [f] has
been applied to each element of [l] in turn. For example: *)
Example test_map1: map (plus 3) [2,0,2] = [5,3,5].
Proof. reflexivity. Qed.
(** The element types of the input and output lists need not be
the same ([map] takes _two_ type arguments, [X] and [Y]). This
version of [map] can thus be applied to a list of numbers and a
function from numbers to booleans to yield a list of booleans: *)
Example test_map2: map oddb [2,1,2,5] = [false,true,false,true].
Proof. reflexivity. Qed.
(** It can even be applied to a list of numbers and
a function from numbers to _lists_ of booleans to
yield a list of lists of booleans: *)
Example test_map3:
map (fun n => [evenb n,oddb n]) [2,1,2,5]
= [[true,false],[false,true],[true,false],[false,true]].
Proof. reflexivity. Qed.
Theorem map_snoc : forall (X Y : Type)
(f : X -> Y) (x : X) (l : list X),
map f (snoc l x) = snoc (map f l) (f x).
Proof.
intros X Y f x l. induction l as [| v l'].
Case "l = []".
reflexivity.
Case "l = v :: l'".
simpl. rewrite -> IHl'. reflexivity.
Qed.
(** **** Exercise: 2 stars, optional *)
(** Show that [map] and [rev] commute. You may need to define an
auxiliary lemma. *)
Theorem map_rev : forall (X Y : Type) (f : X -> Y) (l : list X),
map f (rev l) = rev (map f l).
Proof.
(* SOLUTION: *)
intros X Y f l. induction l as [| v l'].
Case "l = []".
reflexivity.
Case "l = v :: l'".
simpl. rewrite -> map_snoc. rewrite -> IHl'. reflexivity.
Qed.
(** [] *)
(** **** Exercise: 1 star *)
(** The function [map] maps a [list X] to a [list Y] using a function
of type [X -> Y]. We can define a similar function, [flat_map],
which maps a [list X] to a [list Y] using a function [f] of type
[X -> list Y]. Your definition should work by 'flattening' the
results of [f], like so:
[[
flat_map (fun n => [n,n,n]) [1,5,4]
= [1, 1, 1, 5, 5, 5, 4, 4, 4].
]]
*)
Fixpoint flat_map {X Y:Type} (f:X -> list Y) (l:list X)
: (list Y) :=
(* SOLUTION: *)
match l with
| [] => []
| h :: t => (f h) ++ (flat_map f t)
end.
Example test_flat_map1:
flat_map (fun n => [n,n,n]) [1,5,4]
= [1, 1, 1, 5, 5, 5, 4, 4, 4].
(* SOLUTION: *)
Proof. reflexivity. Qed.
(** [] *)
(** Lists are not the only inductive type that we can write a
[map] function for. Here is the definition of [map] for the
[option] type: *)
Definition map_option {X Y : Type} (f : X -> Y) (xo : option X)
: option Y :=
match xo with
| None => None
| Some x => Some (f x)
end.
(** **** Exercise: 1 star, optional (implicit_args) *)
(** The definitions and uses of [filter] and [map] use implicit
arguments in many places. Replace the curly braces around the
implicit arguments with parentheses, and then fill in explicit
type parameters where necessary and use Coq to check that you've
done so correctly. This exercise is not to be turned in; it is
probably easiest to do it on a _copy_ of this file that you can
throw away afterwards. [] *)
(* ###################################################### *)
(** ** Fold *)
(** An even more powerful higher-order function is called [fold]. It
is the inspiration for the "[reduce]" operation that lies at the
heart of Google's map/reduce distributed programming framework. *)
Fixpoint fold {X Y:Type} (f: X->Y->Y) (l:list X) (b:Y) : Y :=
match l with
| nil => b
| h :: t => f h (fold f t b)
end.
(** Intuitively, the behavior of the [fold] operation is to
insert a given binary operator [f] between every pair of elements
in a given list. For example, [ fold plus [1,2,3,4] ] intuitively
means [1+2+3+4]. To make this precise, we also need a "starting
element" that serves as the initial second input to [f]. So, for
example,
[[
fold plus [1,2,3,4] 0
]]
yields
[[
1 + (2 + (3 + (4 + 0))).
]]
Here are some more examples:
*)
Check (fold plus).
Eval simpl in (fold plus [1,2,3,4] 0).
Example fold_example1 : fold mult [1,2,3,4] 1 = 24.
Proof. reflexivity. Qed.
Example fold_example2 : fold andb [true,true,false,true] true = false.
Proof. reflexivity. Qed.
Example fold_example3 : fold app [[1],[],[2,3],[4]] [] = [1,2,3,4].
Proof. reflexivity. Qed.
(** **** Exercise: 1 star, optional *)
(** Observe that the type of [fold] is parameterized by _two_ type
variables, [X] and [Y], and the parameter [f] is a binary operator
that takes an [X] and a [Y] and returns a [Y]. Can you think of a
situation where it would be useful for [X] and [Y] to be
different? *)
(* ###################################################### *)
(** ** Functions For Constructing Functions *)
(** Most of the higher-order functions we have talked about so
far take functions as _arguments_. Now let's look at some
examples involving _returning_ functions as the results of other
functions.
To begin, here is a function that takes a value [x] (drawn from
some type [X]) and returns a function from [nat] to [X] that
yields [x] whenever it is called. *)
Definition constfun {X: Type} (x: X) : nat->X :=
fun (k:nat) => x.
Definition ftrue := constfun true.
Example constfun_example1 : ftrue 0 = true.
Proof. reflexivity. Qed.
Example constfun_example2 : (constfun 5) 99 = 5.
Proof. reflexivity. Qed.
(** Similarly, but a bit more interestingly, here is a function
that takes a function [f] from numbers to some type [X], a number
[k], and a value [x], and constructs a function that behaves
exactly like [f] except that, when called with the argument [k],
it returns [x]. *)
Definition override {X: Type} (f: nat->X) (k:nat) (x:X) : nat->X:=
fun (k':nat) => if beq_nat k k' then x else f k'.
(** For example, we can apply [override] twice to obtain a
function from numbers to booleans that returns [false] on [1] and
[3] and returns [true] on all other arguments. *)
Definition fmostlytrue := override (override ftrue 1 false) 3 false.
Example override_example1 : fmostlytrue 0 = true.
Proof. reflexivity. Qed.
Example override_example2 : fmostlytrue 1 = false.
Proof. reflexivity. Qed.
Example override_example3 : fmostlytrue 2 = true.
Proof. reflexivity. Qed.
Example override_example4 : fmostlytrue 3 = false.
Proof. reflexivity. Qed.
(** **** Exercise: 1 star *)
(** Before starting to work on the following proof, make sure you
understand exactly what the theorem is saying and can paraphrase
it in english. The proof itself is straightforward. *)
Theorem override_example : forall (b:bool),
(override (constfun b) 3 true) 2 = b.
Proof.
(* SOLUTION: *)
intros b.
simpl. reflexivity.
Qed.
(** [] *)
(** We'll use function overriding heavily in parts of the rest of the
course, and we will end up needing to know quite a bit about its
properties. To prove these properties, though, we need to know
about a few more of Coq's tactics; developing these is the main
topic of the rest of the chapter. *)
(* ###################################################### *)
(** * More About Coq *)
(** ###################################################### *)
(** ** The [unfold] tactic *)
(** The precise behavior of the [simpl] tactic is subtle: even
expert Coq users tend to work with it by just trying it and seeing
what it does in particular situations, rather than trying to
predict in advance. However, one point is worth noting: [simpl]
never expands names that have been declared as [Definition]s.
For example, these two expressions do not simplify to the same
thing.
*)
Eval simpl in (plus 3 5).
Eval simpl in (plus3 5).
(** The opacity of definitions shows up in other places too.
For example, there are times when a proof will get stuck because
Coq can't automatically see that two terms are equal because one
of them involves a definition. *)
Theorem unfold_example_bad : forall m n,
3 + n = m ->
plus3 n = m.
Proof.
intros m n H.
(* At this point, we'd like to do [rewrite -> H], but it fails
because Coq doesn't realize that [plus3 n] is definitionally
equal to [3 + n]. *)
Admitted.
(** The [unfold] tactic can be used to explicitly replace a
defined name by the right-hand side of its definition. *)
Theorem unfold_example : forall m n,
3 + n = m ->
plus3 n = m.
Proof.
intros m n H.
unfold plus3.
rewrite -> H.
reflexivity.
Qed.
(** Now we can prove a first property of [override]: If we
override a function at some argument [k] and then look up [k], we
get back the overriden value. *)
Theorem override_eq : forall (X:Type) x k (f : nat->X),
(override f k x) k = x.
Proof.
intros X x k f.
unfold override.
rewrite <- beq_nat_refl.
reflexivity.
Qed.
(** This proof was straightforward, but note that it requires
[unfold] to expand the definition of [override]. *)
(** **** Exercise: 2 stars *)
Theorem override_neq : forall (X:Type) x1 x2 k1 k2 (f : nat->X),
f k1 = x1 ->
beq_nat k2 k1 = false ->
(override f k2 x2) k1 = x1.
Proof.
(* SOLUTION: *)
intros X x1 x2 k1 k2 f. intros Hx1 Hneq.
unfold override.
rewrite -> Hneq.
apply Hx1.
Qed.
(** [] *)
(* ###################################################### *)
(** ** Inversion *)
(** Recall the definition of natural numbers:
[[
Inductive nat : Type :=
| O : nat