-
Notifications
You must be signed in to change notification settings - Fork 86
/
Copy pathFirstClassFunctions.v
1372 lines (1148 loc) · 41.7 KB
/
FirstClassFunctions.v
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
(** Formal Reasoning About Programs <http://adam.chlipala.net/frap/>
* Supplementary Coq material: first-class functions and continuations
* Author: Adam Chlipala
* License: https://creativecommons.org/licenses/by-nc-nd/4.0/ *)
Require Import Frap Program.
(* Next stop in touring the basic Coq ingredients of functional programming and
* proof: functions as first-class data. These days, most trendy programming
* languages contain this feature, though it can't hurt to review; and we'll see
* patterns in specification and proof that are helpful to handle first-class
* functions. *)
(** * Some data fodder for us to compute with later *)
(* Records are a handy way to define datatypes in terms of the named fields that
* each value must contain. *)
Record programming_language := {
Name : string;
PurelyFunctional : bool;
AppearedInYear : nat
}.
(* Here's a quick example of a set of programming languages, which we will use
* below in some example computations. *)
Definition pascal := {|
Name := "Pascal";
PurelyFunctional := false;
AppearedInYear := 1970
|}.
Definition clang := {|
Name := "C";
PurelyFunctional := false;
AppearedInYear := 1972
|}.
Definition gallina := {|
Name := "Gallina";
PurelyFunctional := true;
AppearedInYear := 1989
|}.
Definition haskell := {|
Name := "Haskell";
PurelyFunctional := true;
AppearedInYear := 1990
|}.
Definition ocaml := {|
Name := "OCaml";
PurelyFunctional := false;
AppearedInYear := 1996
|}.
Definition languages := [pascal; clang; gallina; haskell; ocaml].
(** * Classic list functions *)
(* The trio of "map/filter/reduce" are commonly presented as workhorse
* *higher-order functions* for lists. That is, they are functions that take
* functions as arguments. *)
(* [map] runs a function on every position of a list to make a new list. *)
Fixpoint map {A B} (f : A -> B) (ls : list A) : list B :=
match ls with
| nil => nil
| x :: ls' => f x :: map f ls'
end.
Compute map (fun n => n + 2) [1; 3; 8].
(* Note the use of an *anonymous function* above via [fun]. *)
(* [filter] keeps only those elements of a list that pass a Boolean test. *)
Fixpoint filter {A} (f : A -> bool) (ls : list A) : list A :=
match ls with
| nil => nil
| x :: ls' => if f x then x :: filter f ls' else filter f ls'
end.
Compute filter (fun n => if n <=? 3 then true else false) [1; 3; 8].
(* The [if ... then true else false] bit might seem wasteful. Actually, the
* [<=?] operator has a fancy type that needs converting to [bool]. We'll get
* more specific about such types in a future class. *)
(* [fold_left], a relative of "reduce," repeatedly applies a function to all
* elements of a list. *)
Fixpoint fold_left {A B} (f : B -> A -> B) (ls : list A) (acc : B) : B :=
match ls with
| nil => acc
| x :: ls' => fold_left f ls' (f acc x)
end.
Compute fold_left max [1; 3; 8] 0.
(* Another way to see [fold_left] in action: *)
Theorem fold_left3 : forall {A B} (f : B -> A -> B) (x y z : A) (acc : B),
fold_left f [x; y; z] acc = f (f (f acc x) y) z.
Proof.
simplify.
equality.
Qed.
(* Let's use these classics to implement a few simple "database queries" on the
* list of programming languages. Note that each field name from
* [programming_language] is itself a first-class function, for projecting that
* field from any record! *)
Compute map Name languages.
(* names of languages *)
Compute map Name (filter PurelyFunctional languages).
(* names of purely functional languages *)
Compute fold_left max (map AppearedInYear languages) 0.
(* maximum year in which a language appeared *)
Compute fold_left max (map AppearedInYear (filter PurelyFunctional languages)) 0.
(* maximum year in which a purely functional language appeared *)
(* To avoid confusing things, we'll revert to the standard library's (identical)
* versions of these functions for the remainder. *)
Reset map.
(** * Sorting, parameterized in a comparison operation *)
(* Another classic family of higher-order functions is for sorting, where we
* typically take a *comparator* as input. Such a function helps us compare
* data elements with each other. Let's do insertion sort as an example. *)
(* Important helper function: take in an assumed-sorted list [ls]; generate a
* new list that is like [ls] but with [new] inserted at the appropriate
* position to maintain sortedness. We use "less than or equal to" test [le] to
* define sortedness. *)
Fixpoint insert {A} (le : A -> A -> bool) (new : A) (ls : list A) : list A :=
match ls with
| [] => [new]
| x :: ls' =>
if le new x then
new :: ls
else
x :: insert le new ls'
end.
(* Now insertion sort is just repeated use of [insert]. *)
Fixpoint insertion_sort {A} (le : A -> A -> bool) (ls : list A) : list A :=
match ls with
| [] => []
| x :: ls' => insert le x (insertion_sort le ls')
end.
(* To help us state our main theorem, we define sortedness. *)
Fixpoint sorted {A} (le : A -> A -> bool) (ls : list A) : bool :=
match ls with
| [] => true
| x1 :: ls' =>
match ls' with
| x2 :: _ => le x1 x2 && sorted le ls'
| [] => true
end
end.
(* [insert] preserves sortedness. Note the crucial hypothesis that comparator
* [le] is *total*: any two elements are related by it, in one order or the
* other. *)
Lemma insert_sorted : forall {A} (le : A -> A -> bool) a,
(forall x y, le x y = false -> le y x = true)
-> forall ls, sorted le ls = true
-> sorted le (insert le a ls) = true.
Proof.
induct ls; simplify; trivial.
cases (le a a0); simplify.
rewrite Heq; simplify.
trivial.
cases ls; simplify.
rewrite H; trivial.
apply andb_true_iff in H0; propositional.
cases (le a a1); simplify.
apply andb_true_iff in H0; propositional.
rewrite H; trivial.
simplify.
rewrite H3, H4; trivial.
rewrite H1; simplify.
trivial.
Qed.
(* Main theorem: [insertion_sort] produces only sorted lists. *)
Theorem insertion_sort_sorted : forall {A} (le : A -> A -> bool),
(forall x y, le x y = false -> le y x = true)
-> forall ls,
sorted le (insertion_sort le ls) = true.
Proof.
induct ls; simplify; trivial.
apply insert_sorted; trivial.
Qed.
(* The other classic requirement of a sorting function is that it return a
* permutation of its input, but we will skip that element here, since it is
* orthogonal to practicing with higher-order functions. *)
(* Let's do a quick example of using [insertion_sort] with a concrete
* comparator. *)
Definition not_introduced_later (l1 l2 : programming_language) : bool :=
if AppearedInYear l1 <=? AppearedInYear l2 then true else false.
Compute insertion_sort
not_introduced_later
[gallina; pascal; clang; ocaml; haskell].
Corollary insertion_sort_languages : forall langs,
sorted not_introduced_later (insertion_sort not_introduced_later langs) = true.
Proof.
simplify.
apply insertion_sort_sorted.
unfold not_introduced_later.
simplify.
cases (AppearedInYear x <=? AppearedInYear y); try equality.
cases (AppearedInYear y <=? AppearedInYear x); try equality.
linear_arithmetic.
Qed.
(** * A language of functions and its interpreter *)
(* Let's now work through an example of a language and its interpreter.
* Specifically, we'll define a language of first-class functions and
* higher-order functions. It would be natural to make our language statically
* typed, but it turns out we need a bit more Coq sophistication to implement a
* proper interpreter for such an embedded language, which we'll postpone for
* module DependentInductiveTypes. Instead, here's a simple "universal type"
* along the lines of dynamically typed languages like Python. *)
Inductive dyn :=
| Bool (b : bool)
| Number (n : nat)
| List (ds : list dyn).
(* Next, we implement dynamic versions of a few handy library functions.
* Notice that they have arbitrary default behavior when passed improperly typed
* arguments. *)
Definition dmap (f : dyn -> dyn) (x : dyn) : dyn :=
match x with
| List ds => List (map f ds)
| _ => x
end.
Definition dfilter (f : dyn -> dyn) (x : dyn) : dyn :=
match x with
List ds => List (filter (fun arg => match f arg with
| Bool b => b
| _ => false
end) ds)
| _ => x
end.
Definition disZero (x : dyn) : dyn :=
match x with
| Number 0 => Bool true
| Number _ => Bool false
| _ => x
end.
Definition dnot (x : dyn) : dyn :=
match x with
| Bool b => Bool (negb b)
| x => x
end.
(* Here's our syntax-tree type for functions (transformations). *)
Inductive xform :=
| Identity
| Compose (xf1 xf2 : xform)
| Map (xf1 : xform)
| Filter (xf1 : xform)
| ConstantBool (b : bool)
| ConstantNumber (n : nat)
| IsZero
| Not.
(* And here's our simple interpreter. *)
Fixpoint transform (xf : xform) : dyn -> dyn :=
match xf with
| Identity => id (* from the Coq standard library *)
| Compose f1 f2 => compose (transform f1) (transform f2)
(* ditto for [compose] *)
| Map f => dmap (transform f)
| Filter f => dfilter (transform f)
| ConstantBool b => fun _ => Bool b
| ConstantNumber n => fun _ => Number n
| IsZero => disZero
| Not => dnot
end.
Compute transform (Map IsZero) (List [Number 0; Number 1; Number 2; Number 0; Number 3]).
Compute transform (Filter IsZero) (List [Number 0; Number 1; Number 2; Number 0; Number 3]).
(* Here's a grab bag of optimizations of our programs. *)
Fixpoint optimize (xf : xform) : xform :=
match xf with
| Compose xf1 xf2 =>
match optimize xf1, optimize xf2 with
| Identity, xf2' => xf2'
| xf1', Identity => xf1'
| Not, Not => Identity
| Map xf1', Map xf2' => Map (Compose xf1' xf2')
| Not, ConstantBool b => ConstantBool (negb b)
| IsZero, ConstantNumber 0 => ConstantBool true
| IsZero, ConstantNumber (S _) => ConstantBool false
| xf1', xf2' => Compose xf1' xf2'
end
| Map xf1 =>
match optimize xf1 with
| Identity => Identity
| xf1' => Map xf1'
end
| Filter xf1 =>
match optimize xf1 with
| ConstantBool true => Identity
| xf1' => Filter xf1'
end
| _ => xf
end.
(* This tactic turns out to work well to prove our optimizations correct. We'll
* have to wait for module IntroToProofScripting to understand better what is
* going on. *)
Ltac optimize_ok :=
simplify; unfold compose, dmap in *;
repeat match goal with
| [ H : forall x : dyn, _ = _ |- _ ] => rewrite H
end;
repeat match goal with
| [ H : forall x : dyn, _ = _ |- _ ] => rewrite <- H
end; auto.
(* Now, a few useful alegbraic properties of our wrapper functions. *)
Lemma dnot_dnot : forall d, dnot (dnot d) = d.
Proof.
induct d; simplify; trivial.
SearchRewrite (negb (negb _)).
rewrite negb_involutive.
trivial.
Qed.
Global Hint Rewrite dnot_dnot.
Lemma map_identity : forall A (f : A -> A) (ls : list A),
(forall x, x = f x)
-> map f ls = ls.
Proof.
induct ls; simplify; equality.
Qed.
Global Hint Rewrite map_identity map_map using assumption.
Lemma map_same : forall A B (f1 f2 : A -> B) ls,
(forall x, f1 x = f2 x)
-> map f1 ls = map f2 ls.
Proof.
induct ls; simplify; equality.
Qed.
Lemma List_map_same : forall A (f1 f2 : A -> dyn) ls,
(forall x, f1 x = f2 x)
-> List (map f1 ls) = List (map f2 ls).
Proof.
simplify.
f_equal.
apply map_same; assumption.
Qed.
Lemma filter_same : forall A (f1 f2 : A -> bool) ls,
(forall x, f1 x = f2 x)
-> filter f1 ls = filter f2 ls.
Proof.
induct ls; simplify; try equality.
rewrite H.
cases (f2 a); simplify; equality.
Qed.
Lemma List_filter_same : forall (f1 f2 : dyn -> bool) ls,
(forall x, f1 x = f2 x)
-> List (filter f1 ls) = List (filter f2 ls).
Proof.
simplify.
f_equal.
apply filter_same; assumption.
Qed.
Global Hint Resolve List_map_same List_filter_same : core.
Global Hint Extern 5 (_ = match _ with Bool _ => _ | _ => _ end) =>
match goal with
| [ H : forall x : dyn, _ |- _ ] => rewrite <- H
end : core.
Lemma filter_ident : forall A (f : A -> bool) ls,
(forall x, f x = true)
-> filter f ls = ls.
Proof.
induct ls; simplify; try equality.
rewrite H.
equality.
Qed.
Theorem optimize_ok : forall xf x, transform (optimize xf) x = transform xf x.
Proof.
induct xf; simplify; try equality.
{
cases (optimize xf1); optimize_ok;
(cases (optimize xf2); optimize_ok).
cases x; simplify; trivial.
cases n; trivial.
}
{
cases (optimize xf); optimize_ok;
(cases x; optimize_ok).
}
{
cases (optimize xf); optimize_ok;
(cases x; optimize_ok);
repeat match goal with
| [ |- context[match ?E with _ => _ end] ] => cases E; simplify; trivial
end; auto.
rewrite filter_ident; trivial.
intro.
rewrite <- IHxf.
trivial.
}
Qed.
(** ** Are these really optimizations? Can they ever grow a term's size? *)
Fixpoint size (xf : xform) : nat :=
match xf with
| Identity
| Not
| IsZero
| ConstantBool _
| ConstantNumber _ => 1
| Compose xf1 xf2 => 1 + size xf1 + size xf2
| Map xf
| Filter xf => 1 + size xf
end.
(* Answer: no! *)
Theorem optimize_optimizes : forall xf, size (optimize xf) <= size xf.
Proof.
induct xf; simplify; try linear_arithmetic;
repeat match goal with
| [ |- context[match ?E with _ => _ end] ] =>
cases E; simplify; try linear_arithmetic
end.
Qed.
(** ** More interestingly, the same is true of the action of these
transformations on concrete values! *)
Fixpoint sum (ls : list nat) : nat :=
match ls with
| nil => 0
| x :: ls' => x + sum ls'
end.
Fixpoint dsize (d : dyn) : nat :=
match d with
| Bool _
| Number _ => 1
| List ds => 1 + sum (map dsize ds)
end.
(* Some lemmas first, and then the main theorem result *)
Lemma dsize_positive : forall d, 1 <= dsize d.
Proof.
induct d; simplify; linear_arithmetic.
Qed.
Global Hint Immediate dsize_positive : core.
Lemma sum_map_monotone : forall A (f1 f2 : A -> nat) ds,
(forall x, f1 x <= f2 x)
-> sum (map f1 ds) <= sum (map f2 ds).
Proof.
induct ds; simplify; try linear_arithmetic; propositional.
specialize (H a).
linear_arithmetic.
Qed.
Lemma neverGrow_filter : forall f ds,
sum (map dsize (filter f ds)) <= sum (map dsize ds).
Proof.
induct ds; simplify; try linear_arithmetic.
cases (f a); simplify; linear_arithmetic.
Qed.
Theorem neverGrow : forall xf x,
dsize (transform xf x) <= dsize x.
Proof.
induct xf; simplify; try linear_arithmetic.
unfold id.
trivial.
unfold compose.
eauto using le_trans.
unfold dmap.
cases x; trivial.
simplify.
Search (S _ <= S _).
apply le_n_S.
apply sum_map_monotone.
trivial.
unfold dfilter.
cases x; trivial.
simplify.
apply le_n_S.
apply neverGrow_filter.
apply dsize_positive.
apply dsize_positive.
unfold disZero.
cases x; trivial.
cases n; trivial.
unfold dnot.
cases x; trivial.
Qed.
(** * Combinators for syntax-tree transformations *)
(* Let's reprise the imperative language from the end of Interpreters. *)
Inductive arith : Set :=
| Const (n : nat)
| Var (x : var)
| Plus (e1 e2 : arith)
| Minus (e1 e2 : arith)
| Times (e1 e2 : arith).
Definition valuation := fmap var nat.
Fixpoint interp (e : arith) (v : valuation) : nat :=
match e with
| Const n => n
| Var x =>
match v $? x with
| None => 0
| Some n => n
end
| Plus e1 e2 => interp e1 v + interp e2 v
| Minus e1 e2 => interp e1 v - interp e2 v
| Times e1 e2 => interp e1 v * interp e2 v
end.
Inductive cmd :=
| Skip
| Assign (x : var) (e : arith)
| Sequence (c1 c2 : cmd)
| Repeat (e : arith) (body : cmd).
Fixpoint selfCompose {A} (f : A -> A) (n : nat) : A -> A :=
match n with
| O => fun x => x
| S n' => fun x => selfCompose f n' (f x)
end.
Lemma selfCompose_extensional : forall {A} (f g : A -> A) n x,
(forall y, f y = g y)
-> selfCompose f n x = selfCompose g n x.
Proof.
induct n; simplify; try equality.
rewrite H.
apply IHn.
trivial.
Qed.
Fixpoint exec (c : cmd) (v : valuation) : valuation :=
match c with
| Skip => v
| Assign x e => v $+ (x, interp e v)
| Sequence c1 c2 => exec c2 (exec c1 v)
| Repeat e body => selfCompose (exec body) (interp e v) v
end.
Fixpoint seqself (c : cmd) (n : nat) : cmd :=
match n with
| O => Skip
| S n' => Sequence c (seqself c n')
end.
(* Now consider a more abstract way of describing optimizations concisely.
* We package tree-rewriting functions of two kinds, in records. *)
Record rule := {
OnCommand : cmd -> cmd;
OnExpression : arith -> arith
}.
(* Such a strategy can be applied *bottom-up* in a syntax tree. *)
Fixpoint bottomUp (r : rule) (c : cmd) : cmd :=
match c with
| Skip => r.(OnCommand) Skip
| Assign x e => r.(OnCommand) (Assign x (r.(OnExpression) e))
| Sequence c1 c2 => r.(OnCommand) (Sequence (bottomUp r c1) (bottomUp r c2))
| Repeat e body => r.(OnCommand) (Repeat (r.(OnExpression) e) (bottomUp r body))
end.
(* Here are a few handy *combinators* for building [rule]s. *)
Definition crule (f : cmd -> cmd) : rule :=
{| OnCommand := f; OnExpression := fun e => e |}.
Definition erule (f : arith -> arith) : rule :=
{| OnCommand := fun c => c; OnExpression := f |}.
Definition andThen (r1 r2 : rule) : rule :=
{| OnCommand := compose r2.(OnCommand) r1.(OnCommand);
OnExpression := compose r2.(OnExpression) r1.(OnExpression) |}.
(* Two basic examples of rules *)
Definition plus0 := erule (fun e =>
match e with
| Plus e' (Const 0) => e'
| _ => e
end).
Definition unrollLoops := crule (fun c =>
match c with
| Repeat (Const n) body => seqself body n
| _ => c
end).
(* Let's see what effects they have on simple examples. *)
Compute bottomUp plus0
(Sequence (Assign "x" (Plus (Var "x") (Const 0)))
(Assign "y" (Var "x"))).
Compute bottomUp unrollLoops
(Repeat (Plus (Const 2) (Const 0))
(Sequence (Assign "x" (Plus (Var "x") (Const 0)))
(Assign "y" (Var "x")))).
Compute bottomUp (andThen plus0 unrollLoops)
(Repeat (Plus (Const 2) (Const 0))
(Sequence (Assign "x" (Plus (Var "x") (Const 0)))
(Assign "y" (Var "x")))).
(* Here is a good semantic correctness notion for rules. *)
Definition correct (r : rule) :=
(forall c v, exec (r.(OnCommand) c) v = exec c v)
/\ (forall e v, interp (r.(OnExpression) e) v = interp e v).
(* Some theorems for proving correctness of our combinators *)
Theorem crule_correct : forall f,
(forall c v, exec (f c) v = exec c v)
-> correct (crule f).
Proof.
first_order.
Qed.
Theorem erule_correct : forall f,
(forall e v, interp (f e) v = interp e v)
-> correct (erule f).
Proof.
first_order.
Qed.
Theorem andThen_correct : forall r1 r2,
correct r1
-> correct r2
-> correct (andThen r1 r2).
Proof.
unfold andThen; first_order; simplify; eauto using eq_trans.
Qed.
(* A bottom-up traversal with a correct rule is also correct. *)
Theorem bottomUp_correct : forall r,
correct r
-> forall c v, exec (bottomUp r c) v = exec c v.
Proof.
unfold correct; induct c; simplify; propositional.
rewrite H0.
trivial.
rewrite H0.
simplify.
equality.
rewrite H0.
simplify.
equality.
rewrite H0.
simplify.
rewrite H1.
apply selfCompose_extensional.
trivial.
Qed.
(* A twist: we can also package bottom-up traversal as a rule in its own right,
* which can then be used in other bottom-up traversals! *)
Definition rBottomUp (r : rule) : rule :=
{| OnCommand := bottomUp r;
OnExpression := r.(OnExpression) |}.
Theorem rBottomUp_correct : forall r,
correct r
-> correct (rBottomUp r).
Proof.
unfold correct; simplify; propositional.
apply bottomUp_correct.
unfold correct; propositional.
Qed.
(* This example demonstrates how this kind of nested traversal can find
* additional optimizations. Watch as the program shrinks while we ratchet up
* the level of nesting. *)
Definition zzz := Assign "x" (Plus (Plus (Plus (Var "x") (Const 0)) (Const 0)) (Const 0)).
Compute bottomUp plus0 zzz.
Compute bottomUp (rBottomUp plus0) zzz.
Compute bottomUp (rBottomUp (rBottomUp plus0)) zzz.
Compute bottomUp (rBottomUp (rBottomUp (rBottomUp plus0))) zzz.
(** * Motivating continuations with search problems *)
(* We're getting into advanced material here, so it may often make sense to stop
* before this point in a class presentation. But, if you want to learn about
* one of the classic cool features of functional programming.... *)
(* One fascinating flavor of first-class functions is *continuations*, which are
* essentially functions that are meant to be called on the *results* of other
* functions. To motivate the idea, let's first develop a somewhat slow
* function. We'll switch to a continuation-based version to see the
* benefit. *)
(* Here's a simple way to compute all lists that can be formed by dropping zero
* or more elements out of some original list. *)
Fixpoint allSublists {A} (ls : list A) : list (list A) :=
match ls with
| [] => [[]]
| x :: ls' =>
let lss := allSublists ls' in
lss ++ map (fun ls'' => x :: ls'') lss
end.
Compute allSublists [1; 2; 3].
(* This is the main function we want to define. It looks for a sublist whose
* sum matches some target. *)
Fixpoint sublistSummingTo (ns : list nat) (target : nat) : option (list nat) :=
match filter (fun ns' => if sum ns' ==n target then true else false) (allSublists ns) with
| ns' :: _ => Some ns'
| [] => None
end.
Compute sublistSummingTo [1; 2; 3] 6.
Compute sublistSummingTo [1; 2; 3] 5.
Compute sublistSummingTo [1; 2; 3] 7.
(* This function will be handy to generate some test cases. *)
Fixpoint countingDown (from : nat) :=
match from with
| O => []
| S from' => from' :: countingDown from'
end.
Compute countingDown 10.
(* This one is pretty slow! There are quite a few sublists of
* [countingDown 18], you know. *)
Time Compute sublistSummingTo (countingDown 18) 1.
(* Can we set things up so that we can avoid generating *all* sublists, instead
* checking each one for the right sum, as it is generated? And can we do it in
* a *generic* way, where we still have sublists calculation that isn't
* specialized to any particular acceptance condition? Continuations provide a
* nice ingredient! *)
(* This variant of [allSublists] takes a while to digest. Both of the new
* arguments are continuations. *)
Fixpoint allSublistsK {A R} (ls : list A)
(* First, notice new type parameter [R], for "result."
* The function will return a value of this type. *)
(failed : unit -> R)
(* If no acceptable sublist is found, return the result of calling this
* function. [unit] is the degenerate standard-library type inhabited
* only by [tt]. *)
(found : list A -> (unit -> R) -> R)
(* Whenever an acceptable sublist is found, return the result of
* calling this function on it. The 2nd argument is a failure
* continuation, just like our own [failed]. That is, when [found]
* "doesn't like" the list, it returns the result of calling the
* function we pass to it. See below for why this is a perfect
* plumbing strategy. *)
: R :=
match ls with
| [] =>
found [] failed
(* [ls] is empty? Then the only sublist is [[]], which we should send to
* our success continuation [found] for vetting. *)
| x :: ls' =>
(* [ls] is nonempty? Let's proceed to finding all sublists of [ls']. *)
allSublistsK ls'
failed
(* Any failure here bubbles up to a failure in the original
* call. *)
(fun sol failed' =>
(* Any success here should first be passed on to the
* original success continuation [found]. *)
found sol (fun _ =>
(* However, if [found] doesn't like [sol], then
* maybe it likes [x :: sol]! Note how we
* customize the failure continuation passed to
* [found], to implement a kind of backtracking
* search, interleaved with generation of
* candidates. *)
found (x :: sol) failed'))
end.
(* Now it is easy to define a variant of [sublistSummingTo], where result type
* [R] gets instantiated as [option (list nat)]. *)
Definition sublistSummingToK (ns : list nat) (target : nat) : option (list nat) :=
allSublistsK ns
(fun _ => None)
(* Failure continuation: return None. *)
(fun sol failed =>
if sum sol ==n target then Some sol else failed tt)
(* Success continuation: check if sum is right, if so returning
* [Some]. *).
Time Compute sublistSummingToK (countingDown 18) 1.
(* Significantly faster now! We avoid materializing the full list of sublists,
* before starting to filter them. We will return below to proof of this
* function, which is irksomely involved. *)
(** * The classics in continuation-passing style *)
(* We can rewrite the classic list higher-order functions in
* *continuation-passing style*, where they return answers by calling
* continuations rather than just returning normally. This style might be
* familiar from, e.g., how *asynchronous programming* works in JavaScript. *)
(* Notice how, not only does [mapK] have a CPS (continuation-passing style)
* type, but its function argument also has a CPS type. *)
Fixpoint mapK {A B R} (f : A -> (B -> R) -> R) (ls : list A) (k : list B -> R) : R :=
match ls with
| nil => k nil
| x :: ls' => f x (fun x' => mapK f ls' (fun ls'' => k (x' :: ls'')))
end.
Fixpoint filterK {A R} (f : A -> (bool -> R) -> R) (ls : list A) (k : list A -> R) : R :=
match ls with
| nil => k nil
| x :: ls' => f x (fun b => filterK f ls' (fun ls'' => k (if b then x :: ls'' else ls'')))
end.
Fixpoint fold_leftK {A B R} (f : B -> A -> (B -> R) -> R) (ls : list A) (acc : B) (k : B -> R) : R :=
match ls with
| nil => k acc
| x :: ls' => f acc x (fun x' => fold_leftK f ls' x' k)
end.
(* And CPS versions of the additional functions used in our examples earlier *)
Definition NameK {R} (l : programming_language) (k : string -> R) : R :=
k (Name l).
Definition PurelyFunctionalK {R} (l : programming_language) (k : bool -> R) : R :=
k (PurelyFunctional l).
Definition AppearedInYearK {R} (l : programming_language) (k : nat -> R) : R :=
k (AppearedInYear l).
Definition maxK {R} (n1 n2 : nat) (k : nat -> R) : R :=
k (max n1 n2).
(* The examples from before give the same answers, when suitably translated. *)
Compute mapK NameK languages (fun ls => ls).
Compute filterK PurelyFunctionalK languages (fun ls => mapK NameK ls (fun x => x)).
Compute mapK AppearedInYearK languages (fun ls => fold_leftK maxK ls 0 (fun x => x)).
Compute filterK PurelyFunctionalK languages
(fun ls1 => mapK AppearedInYearK ls1
(fun ls2 => fold_leftK maxK ls2 0 (fun x => x))).
(* We can prove that each such example always gives correct answers, for any
* list of languages. *)
Theorem mapK_ok : forall {A B R} (f : A -> (B -> R) -> R) (f_base : A -> B),
(forall x k, f x k = k (f_base x))
-> forall (ls : list A) (k : list B -> R),
mapK f ls k = k (map f_base ls).
Proof.
induct ls; simplify; try equality.
rewrite H.
apply IHls.
Qed.
Theorem names_ok : forall langs,
mapK NameK langs (fun ls => ls) = map Name langs.
Proof.
simplify.
apply mapK_ok with (f_base := Name).
unfold NameK.
trivial.
Qed.
Theorem filterK_ok : forall {A R} (f : A -> (bool -> R) -> R) (f_base : A -> bool),
(forall x k, f x k = k (f_base x))
-> forall (ls : list A) (k : list A -> R),
filterK f ls k = k (filter f_base ls).
Proof.
induct ls; simplify; try equality.
rewrite H.
apply IHls.
Qed.
Theorem purenames_ok : forall langs,
filterK PurelyFunctionalK langs (fun ls => mapK NameK ls (fun x => x))
= map Name (filter PurelyFunctional langs).
Proof.
simplify.
rewrite filterK_ok with (f_base := PurelyFunctional); trivial.
apply mapK_ok with (f_base := Name); trivial.
Qed.
Theorem fold_leftK_ok : forall {A B R} (f : B -> A -> (B -> R) -> R) (f_base : B -> A -> B),
(forall x acc k, f x acc k = k (f_base x acc))
-> forall (ls : list A) (acc : B) (k : B -> R),
fold_leftK f ls acc k = k (fold_left f_base ls acc).
Proof.
induct ls; simplify; try equality.
rewrite H.
apply IHls.
Qed.
Theorem latest_ok : forall langs,
mapK AppearedInYearK langs (fun ls => fold_leftK maxK ls 0 (fun x => x))
= fold_left max (map AppearedInYear langs) 0.
Proof.
simplify.
rewrite mapK_ok with (f_base := AppearedInYear); trivial.
apply fold_leftK_ok with (f_base := max); trivial.
Qed.
Theorem latestpure_ok : forall langs,
filterK PurelyFunctionalK langs
(fun ls1 => mapK AppearedInYearK ls1
(fun ls2 => fold_leftK maxK ls2 0 (fun x => x)))
= fold_left max (map AppearedInYear (filter PurelyFunctional langs)) 0.
Proof.
simplify.
rewrite filterK_ok with (f_base := PurelyFunctional); trivial.
rewrite mapK_ok with (f_base := AppearedInYear); trivial.
apply fold_leftK_ok with (f_base := max); trivial.
Qed.
(** * Tree traversals *)
(* Let's see how the way of continuations can guide us toward defining a tree
* traversal as a "loop" rather than a general recursive function. *)
(* Recall this type from last week. *)
Inductive tree {A} :=
| Leaf
| Node (l : tree) (d : A) (r : tree).
Arguments tree : clear implicits.
(* And here's an in-order traversal that we also already worked with. *)
Fixpoint flatten {A} (t : tree A) : list A :=
match t with
| Leaf => []
| Node l d r => flatten l ++ d :: flatten r
end.