Library Poly
Poly: Polymorphism and Higher-Order Functions
Polymorphic Lists
... 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 datatype.
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 can 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.)
What sort of thing is list itself? One good way to think
about it is that list is a function from Types to
Inductive definitions; or, to put it another way, list is a
function from Types to Types. For any particular type X,
the type list X is an Inductively defined set of lists whose
elements are things of type X.
With this definition, when we use the constructors nil and
cons to build lists, we need to tell Coq the type of the
elements in the lists we are building -- that is, nil and cons
are now polymorphic constructors. Observe the types of these
constructors:
The "∀ X" in these types can 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:
(We've gone back to writing nil and cons explicitly here
because we haven't yet defined the [] and :: notations for
the new version of lists. We'll do that in a bit.)
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.
Note that the uses of nil and cons in match patterns
do not require any type annotations: Coq already knows that the list
l contains elements of type X, so there's no reason to include
X in the pattern. (More precisely, the type X is a parameter
of the whole definition of list, not of the individual
constructors. We'll come back to this point later.)
As with nil and cons, we can use length by applying it first
to a type and then to its list argument:
To use our length with other kinds of lists, we simply
instantiate it with an appropriate type parameter:
Let's close this subsection by re-implementing a few other standard list functions on our new polymorphic lists:
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.
Module MumbleBaz.
Inductive mumble : Type :=
| a : mumble
| b : mumble → nat → mumble
| c : mumble.
Inductive grumble (X:Type) : Type :=
| d : mumble → grumble X
| e : X → grumble X.
Which of the following are well-typed elements of grumble X for
some type X?
☐
Exercise: 2 stars (baz_num_elts)
Consider the following inductive definition:
How many elements does the type baz have?
☐
Type Annotation Inference
Indeed it will. Let's see what type Coq has assigned to app':
It has exactly the same type type as app. Coq was able to
use a process called type inference to deduce what the types of
X, l1, and l2 must be, based on how they are used. For
example, since X is used as an argument to cons, it must be a
Type, since cons expects a Type as its first argument;
matching l1 with nil and cons means it must be a list; and
so on.
This powerful facility means we don't always have to write
explicit type annotations everywhere, although explicit type
annotations are still quite useful as documentation and sanity
checks. You should try to find a balance in your own code between
too many type annotations (so many that they clutter and distract)
and too few (which forces readers to perform type inference in
their heads in order to understand your code).
Type Argument Synthesis
Fixpoint length' (X:Type) (l:list X) : nat :=
match l with
| nil ⇒ 0
| cons h t ⇒ S (length' _ t)
end.
In this instance, we don't save much by writing _ instead of
X. But in many cases the difference can be significant. For
example, suppose we want to write down a list containing the
numbers 1, 2, and 3. Instead of writing this...
...we can use argument synthesis to write this:
Implicit Arguments
Arguments nil {X}.
Arguments cons {X} _ _. Arguments length {X} l.
Arguments app {X} l1 l2.
Arguments rev {X} l.
Arguments snoc {X} l v.
Definition list123'' := cons 1 (cons 2 (cons 3 nil)).
Check (length list123'').
Fixpoint length'' {X:Type} (l:list X) : nat :=
match l with
| nil ⇒ 0
| cons h t ⇒ S (length'' t)
end.
(Note that we didn't even have to provide a type argument to
the recursive call to length''; indeed, it is invalid to provide
one.) We will use this style whenever possible, although we will
continue to use use explicit Argument declarations for
Inductive constructors.
One small problem with declaring arguments Implicit is
that, occasionally, Coq does not have enough local information to
determine a type argument; in such cases, we need to tell Coq that
we want to give the argument explicitly this time, even though
we've globally declared it to be Implicit. For example, suppose we
write this:
If we uncomment this definition, 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 (so that Coq
has more information available when it gets to the "application"
of nil):
Alternatively, we can force the implicit arguments to be explicit by
prefixing the function name with @.
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 these when we use the notations.
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:
Exercises: Polymorphic Lists
Exercise: 2 stars, optional (poly_exercises)
Here are a few simple exercises, just like ones in the Lists chapter, for practice with polymorphism. Fill in the definitions and complete the proofs below.Fixpoint repeat {X : Type} (n : X) (count : nat) : list X :=
admit.
Example test_repeat1:
repeat true 2 = cons true (cons true nil).
Admitted.
Theorem nil_app : ∀ X:Type, ∀ l:list X,
app [] l = l.
Proof.
Admitted.
Theorem rev_snoc : ∀ X : Type,
∀ v : X,
∀ s : list X,
rev (snoc s v) = v :: (rev s).
Proof.
Admitted.
Theorem rev_involutive : ∀ X : Type, ∀ l : list X,
rev (rev l) = l.
Proof.
Admitted.
Theorem snoc_with_append : ∀ X : Type,
∀ l1 l2 : list X,
∀ v : X,
snoc (l1 ++ l2) v = l1 ++ (snoc l2 v).
Proof.
Admitted.
☐
Polymorphic Pairs
As with lists, we make the type arguments implicit and define the
familiar concrete notation.
We can also use the Notation mechanism to define the standard
notation for pair types:
(The annotation : type_scope tells Coq that this abbreviation
should be used when parsing types. This avoids a clash with the
multiplication symbol.)
The first and second projection functions now look pretty
much as they would in any functional programming language.
A note of caution: it is easy at first to get (x,y) and X×Y confused. Remember that (x,y) is a value built from two other values; X×Y is a type built from two other types. If x has type X and y has type Y, then (x,y) has type X×Y.
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. Note that the pair notation can be used both in expressions and in
patterns...
Fixpoint combine {X Y : Type} (lx : list X) (ly : list Y)
: list (X×Y) :=
match (lx,ly) with
| ([],_) ⇒ []
| (_,[]) ⇒ []
| (x::tx, y::ty) ⇒ (x,y) :: (combine tx ty)
end.
Exercise: 1 star, optional (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 compute in (combine 1;2 false;false;true;true). print? ☐
Exercise: 2 stars (split)
The function split is the right 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.Fixpoint split
{X Y : Type} (l : list (X×Y))
: (list X) × (list Y) :=
admit.
Example test_split:
split [(1,false);(2,false)] = ([1;2],[false;false]).
Proof.
Admitted.
☐
Polymorphic Options
Inductive option (X:Type) : Type :=
| Some : X → option X
| None : option X.
Arguments Some {X} _.
Arguments None {X}.
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, optional (hd_opt_poly)
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.
Once again, to force the implicit arguments to be explicit,
we can use @ before the name of the function.
Check @hd_opt.
Example test_hd_opt1 : hd_opt [1;2] = Some 1.
Admitted.
Example test_hd_opt2 : hd_opt [[1];[2]] = Some [1].
Admitted.
☐
Higher-Order Functions
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
Each → in this expression is actually a binary operator
on types. (This is the same as saying that Coq primitively
supports only one-argument functions -- do you see why?) This
operator is right-associative, so the type of plus is really a
shorthand for 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, advanced (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, in honor of the logician Haskell Curry.
As an exercise, define its inverse, prod_uncurry. Then prove
the theorems below to show that the two are inverses.
(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 : ∀ (X Y Z : Type) (f : X → Y → Z) x y,
prod_curry (prod_uncurry f) x y = f x y.
Proof.
Admitted.
Theorem curry_uncurry : ∀ (X Y Z : Type)
(f : (X × Y) → Z) (p : X × Y),
prod_uncurry (prod_curry f) p = f p.
Proof.
Admitted.
☐
Filter
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.
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.
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.
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
Here is the 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 (filter_even_gt7)
Definition filter_even_gt7 (l : list nat) : list nat :=
admit.
Example test_filter_even_gt7_1 :
filter_even_gt7 [1;2;6;9;10;3;12;8] = [10;12;8].
Admitted.
Example test_filter_even_gt7_2 :
filter_even_gt7 [5;2;6;19;129] = [].
Admitted.
☐
Exercise: 3 stars (partition)
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 of 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 :=
admit.
Example test_partition1: partition oddb [1;2;3;4;5] = ([1;3;5], [2;4]).
Admitted.
Example test_partition2: partition (fun x ⇒ false) [5;9;0] = ([], [5;9;0]).
Admitted.
☐
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:
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:
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.
Map for options
Exercise: 3 stars (map_rev)
Show that map and rev commute. You may need to define an auxiliary lemma.Theorem map_rev : ∀ (X Y : Type) (f : X → Y) (l : list X),
map f (rev l) = rev (map f l).
Proof.
Admitted.
☐
Exercise: 2 stars (flat_map)
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+1;n+2) 1;5;10 = 1; 2; 3; 5; 6; 7; 10; 11; 12.Fixpoint flat_map {X Y:Type} (f:X → list Y) (l:list X)
: (list Y) :=
admit.
Example test_flat_map1:
flat_map (fun n ⇒ [n;n;n]) [1;5;4]
= [1; 1; 1; 5; 5; 5; 4; 4; 4].
Admitted.
☐
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 option_map {X Y : Type} (f : X → Y) (xo : option X)
: option Y :=
match xo with
| None ⇒ None
| Some x ⇒ Some (f x)
end.
Exercise: 2 stars, 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
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.
Check (fold andb).
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, advanced (fold_types_different)
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
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.
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 (override_example)
Before starting to work on the following proof, make sure you understand exactly what the theorem is saying and can paraphrase it in your own words. The proof itself is straightforward.
☐
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 next chapter. For now, though, let's introduce just
one very useful tactic that will also help us with proving
properties of some of the other functions we have introduced in
this chapter.
The unfold Tactic
The unfold tactic can be used to explicitly replace a
defined name by the right-hand side of its definition.
Theorem unfold_example : ∀ m n,
3 + n = m →
plus3 n + 1 = m + 1.
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 overridden value.
Theorem override_eq : ∀ {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 (override_neq)
Theorem override_neq : ∀ (X:Type) x1 x2 k1 k2 (f : nat→X),
f k1 = x1 →
beq_nat k2 k1 = false →
(override f k2 x2) k1 = x1.
Proof.
Admitted.
f k1 = x1 →
beq_nat k2 k1 = false →
(override f k2 x2) k1 = x1.
Proof.
Admitted.
☐
As the inverse of unfold, Coq also provides a tactic
fold, which can be used to "unexpand" a definition. It is used
much less often.
Additional Exercises
Exercise: 2 stars (fold_length)
Many common functions on lists can be implemented in terms of fold. For example, here is an alternative definition of length:Definition fold_length {X : Type} (l : list X) : nat :=
fold (fun _ n ⇒ S n) l 0.
Example test_fold_length1 : fold_length [4;7;0] = 3.
Proof. reflexivity. Qed.
Prove the correctness of fold_length.
Write down a theorem in Coq stating that fold_map is correct,
and prove it.
☐