Skip to content

Instantly share code, notes, and snippets.

@jtpaasch
Created July 25, 2018 11:34
Show Gist options
  • Select an option

  • Save jtpaasch/006fef3015b1b124d259ebb66bd5eb31 to your computer and use it in GitHub Desktop.

Select an option

Save jtpaasch/006fef3015b1b124d259ebb66bd5eb31 to your computer and use it in GitHub Desktop.
Software Foundations, Logical Foundations, Tactics.v
(** * Tactics: More Basic Tactics *)
(** This chapter introduces several additional proof strategies
and tactics that allow us to begin proving more interesting
properties of functional programs. We will see:
- how to use auxiliary lemmas in both "forward-style" and
"backward-style" proofs;
- how to reason about data constructors (in particular, how to use
the fact that they are injective and disjoint);
- how to strengthen an induction hypothesis (and when such
strengthening is required); and
- more details on how to reason by case analysis. *)
Set Warnings "-notation-overridden,-parsing".
Require Export Poly.
(* ################################################################# *)
(** * Trying to understand the [apply] Tactic *)
Theorem experiment1:
forall p q : Prop, (p -> q) -> p -> q.
Proof.
Show Proof. (* We have the [?Goal]. *)
intros p q. (* Suppose [p] and [q] are each a fixed number. *)
Show Proof. (* This is a function from [p q : Prop] to the [?Goal]. *)
intros H1. (* Suppose the antecedent [H : p -> q]. The goal is now [p -> q]. *)
Show Proof. (* Now it's a function from [p q : Prop] and [H1 : p -> q] to the [?Goal]. *)
intros H2. (* Suppose the antecedent [H: p]. The goal is now [q]. *)
Show Proof. (* And finally, it's a function from [p q : Prop], [H1 : p ->], and [H2 : p],
to the [?Goal]. *)
(* Our task is to fill in that [?Goal] in the proof object.
We can only use things from the proof context. *)
apply H1.
Show Proof. (* Now, in the body of the proof object, we have an application: [H1 ?Goal].
So [H1] must be a function that can take an argument, and return a result.
As a lambda, [H1] must be something like [\x.q], i.e., it takes an argument
called [x], and it returns [q]. The argument must be the right type, though,
which in this case, must be [p]. So at this point in the proof, we've constructed
a lambda application: we have a function [H1] that needs an argument, and
we're ready to apply it to an argument (hence [H1 ?Goal]), but we don't
know what the [?Goal] argument is yet. *)
(* assumption. *) (* This tactic finds a hypothesis that exactly matches the goal. It then
applies it to complete the goal. *)
apply H2. (* This does the same as [assumption]. This takes the hypothesis [H2], and applies it to
the proof object function. *)
Show Proof. (* Now the [?Goal] is filled in with [H2]. So we have [H1] applied to [H2],
which in lambda terms is something like this: [\x.q p]. That is, we have an
function that takes an argument and returns [q]. Then we give it the argument
[p], so it takes a [p], and returns a [q]. That's what solving [p -> q] means here. *)
Qed.
(* So I think the idea behind [apply] must be [lambda application]. If we can use [apply],
we're in a state where we have a function, like [H1], and we want to apply it to an argument.
But we don't know the argument. Stipulating [apply A] will tell Coq that the argument is [A],
so that Coq can apply the function to [A]. *)
Theorem experiment2 : True -> True.
Proof.
Show Proof. (* At this point, we've done nothing. So we have a [?Goal] we need to fill in. *)
intros H. (* Suppose the antecedent, and call it [H]. So we have [H : True]. The goal is now
to prove the consequent [True]. *)
Show Proof. (* We have a function. from a hypothesis [True] to a [?Goal]. But we still don't
know how to fill in the [?Goal] yet. *)
apply H. (* Use [apply] to apply [H] and solve the goal. *)
Show Proof. (* Now we have a function from [H : True] to [H]. *)
Qed.
Print experiment1. (* The proof object is a function from [H : True] to [H], and that of course
has the type [True -> True]. *)
Module Playground.
Variables P Q R : Prop.
Theorem experiment_1 : P -> P.
Proof.
(* Show the proof object. *)
Show Proof.
(* There is just a [?Goal]. That's like a hole. We need to fill it in to "solve" the goal. *)
(* In the interactive editor, the goal is displayed as [P -> P]. *)
(* To prove an implication, we need to assume the antecedent, and then prove the consequent.
In other words, we assume the antecedent, and show that the consequent follows from it. *)
(* We can assume the antecedent (and give it a name [H]) like this: *)
intros H.
(* This says: suppose that the antecedent of the goal [P -> P] is true. Let's call it
[H]. That is, let's assume as a hypothesis [H] the proposition [P]. Then let's try
to prove the consequent (which is also [P]). *)
(* In the interactive editor, there is a hypothesis [H: P], and the goal is now [P]. *)
Show Proof.
(* The proof object, on the other hand, is now a function that takes an [H : P] as an argument,
and returns a [?Goal]. So the body of this function -- the thing the function returns -- is
at this point still unknown. That's our task: to fill the [?Goal] in as we go. *)
(* Think about the argument type to this function: [H : P]. So, the bound variable name is [H].
It's type must be [P]. [P] is a proposition, so the argument here must be an _inhabitant_
of that proposition. What is an inhabitant of a proposition? A proof! (That is, a proof
object.) So the proof object at this point is a function that takes as an argument a proof
object (in particular, it takes a proof object of [P]), and it returns the [?Goal]. *)
apply H.
(* This solves the goal. But how? *)
Show Proof.
(* The proof object is now a completed function. The [?Goal] has been filled in with [H].
So this function takes a proof of [P] as an argument, ad it returns that same proof.
It is the identity function for [P]. *)
(* This makes sense in constructive logic. A proof of an implication [A -> B] is a procedure
that takes us from a proof of A to a proof of B. That's exactly what we've generated here.
It's a function that takes a proof of the antecedent (which is [P]), and it returns a proof
of the consequent (which is [P]). Since in this case the implication is from a proposition
to itself (i.e., it is from [P] to [P]), then the function that takes us from any proof
of the antecedent to a proof of the consequent is easy: the antecedent and the consequent
are the same proposition, so the same proof can be used for both. Hence, we have an
identity function on proofs of [P]: take a proof of [P], and return that proof. *)
Qed.
Theorem experiment_2 : P -> P.
Proof.
Show Proof.
(* We just have a [?Goal]. Our job is to fill it in.
Our goal here is [P -> P]. To prove an implication, we assume the antecedent,
and then prove the consequent. So let's assume the antecedent, and name it [H]. *)
intros H.
(* Now we have [H : P] in the proof context, as an assumption. The goal is [H]. *)
Show Proof.
(* Now we have a function, that takes an argument [H : P], and returns a [?Goal].
The argument is a proof of [P]. So we have to give this function a proof of [P]
as an argument, i.e., we can only apply this function to a proof of [P]. *)
(* It just so happens that we have a proof of [P] in our context. It is [H : P].
By the [Var] rule in the CIC, [H] is a valid proof term/proof object of [P]. *)
exact H.
(* This solves the goal. But how? *)
Show Proof.
(* Now the proof object is a function from [H : P] to [H]. *)
(* This is the same as [assumption], except [assumption] searches the proof context for
a hypothesis that matches the goal exactly. This is nice because you don't need to
know the name of it, whereas [exact H] specifies exactly which proof object you
want to use here. *)
Qed.
Theorem experiment_3 : P -> R.
Proof.
intros H.
Show Proof.
(* exact H. *) (* This doesn't work, because [P] doesn't have type [R], and Coq is expecting
that the goal has type [R]. In other words, the goal is looking for a proof of [R].
So Coq must be keeping track of expected type information for the [?Goal].
We are trying to prove [P -> R], so we are trying to build a proof that takes
a proof of [P] and returns a proof of [R]. *)
Abort.
(* If we have a goal [P -> R], that's the type: it's a proposition [P -> R]. The inhabitants of
the propositions [P] and [R] are proofs. So a proof of [P -> R] is a function from a proof
of [P] to a proof of [R]. I.e., an [x : P] to a [y : R].
When we assume the antecedent, we assume an [x : P], and then we want to show that a [y : R]
follows. So, that means we end up with a new function, which takes [x : P] as an argument,
and returns a [y : R]. But we don't know how to return that [y : R] when we first assume
the antecedent [x : P]. So our function is [fun x : P => ??]. Our new goal is to show how
to return that [y : R], i.e., we need to tell Coq how to fill in the [??].
Now, if we already have a [y : R] in the proof context, called [H] let's say, then we can
just use that. So we can say [exact H], or [apply H], or even [assumption], to do that.
And [Coq] will take that [H] and fill in the function body: [fun x : P => H].
That must be what's going on here. When we build up a proof of an implication, we start
by assuming the antecedent, and then we need to prove the consequent. That gives us
a function from the antecedent to a [??]. And our next step is to fill in the [??].
After _that_, we have a function that takes us from [x : P] to a [y : R], and we can
then apply this function to other arguments which are also inhabitants of [P]. For
instance, we could apply the function to [t : P] or [s : P]. *)
End Playground.
(* ################################################################# *)
(** * The [apply] Tactic *)
(** We often encounter situations where the goal to be proved is
_exactly_ the same as some hypothesis in the context or some
previously proved lemma. *)
Theorem silly1 : forall (n m o p : nat),
n = m ->
[n;o] = [n;p] ->
[n;o] = [m;p].
Proof.
Show Proof. (* Right now, we just have a [?goal], which is like a hole we need to fill in. *)
intros n m o p. (* Suppose [n], [m], [o], and [p] are each a fixed number. *)
(* The goal is now to show [n = m -> [n; o] = [n; p] -> [n; o] = [m; p]]. This is an implication.
How do we prove implications? We assume the antecedent, and show that it leads to
the consequent. (Think of the impilication introduction rule).
In Coq, we can assume the antecedent with [intros H]. That will put the antecedent into
the proof context as a hypothesis, called [H]. The goal to prove then becomes the consequent.
For instance, if the goal is [A -> B], you can do [intros H], which will put [H: A] into
the proof context as a hypothesis, and the goal will become [B].
In this case, we have two antecedents, so we can [intros] both. The goal then
becomes [n; o] = [m; p]. *)
Show Proof. (* Now we have a function from [n m o p : nat] to [?Goal]. So,
we're putting together a function that will build a proof from
those particular nats to the goal. *)
intros eq1. (* Suppose that [eq1] is [n = m]. The goal now is to prove the consequent
[[n; o] = [n; p] -> [n; o] = [m; p]]. *)
Show Proof. (* Now the proof is a function that takes us from [n m o p : nat] and the proposition
[eq1 : n = m] to the [?Goal]. *)
intros eq2. (* Suppose that [eq2] is [[n; o] = [n; p]]. The goal is now to prove the
consequent [[n; o] = m; p]]. *)
Show Proof. (* Now the proof is a function that takes the nats [n m o p], the proposition
[eq1 : n = m], and the proposition [eq2 : [n; o] = [n; p]], and from those
it builds a proof of the [?Goal]. *)
rewrite <- eq1. (* [eq1] says that [n] is the same as [m], so let's replace every [m] in
the goal with [n]. That yields [[n; o] = [n; p]]. *)
Show Proof. (* Now we have something in the body of the proof. In particular, it is an [eq_ind]
that takes
- some [n]
- a function that takes an [m0 : nat] and, when applied, replaces [m0] with
the provided argument in [[n; o] = [m0; p]].
- the goal [?Goal].
- some [m]
- [eq1]. *)
(* At this point, We could do the following:
rewrite -> eq2. (* [eq2] says [n; o] is the same as [n; p]. So we could replace
every [n; o] in the goal with [n; p]. *)
reflexivity. (* And then both sides of the equation are the same. *)
*)
(** Here, we could finish with "[rewrite -> eq2. reflexivity.]" as we
have done several times before. We can achieve the same effect in
a single step by using the [apply] tactic instead: *)
apply eq2. (* It's not at all clear to me how/why this works. *)
Show Proof. (* What happened was that Coq replaced [?Goal] with [eq2]. And now there are no
more holes (like [?Goal]) to fill. So the proof is complete. *)
(* assumption. *) (* This would equally solve it.
What's the difference between [assumption] and [apply]? *)
Qed.
(* Informal proof:
Theorem: [forall (n m o p : nat), n = m -> [n; o] = [n; p] -> [n; o] = [m; p]].
Proof: by implication introduction [?]
- Suppose [n], [m], [o], and [p] are fixed numbers.
- Suppose that [eq1] is [n = m].
We must show that [[n; o] = [n; p] -> [n; o] = [m; p]].
- Suppose that [eq2] is [[n; o] = [n; p]].
We must show that [[n; o] = [m; p]].
- According to [eq1], [n] is the same as [m], so we can replace [m]
in the goal with [n]. The goal is now [[n; o] = [n; p]].
- By [eq2] ... (I don't know what to fill in here) ... we've proven that
[[n; o] = [n; p] -> [n; o] = [m; p]].
- Since we've shown that [[n; o] = [n; p] -> [n; o] = [m; p]], we've shown
that [n = m -> [n; o] = [n; p] -> [n; o] = [m; p]].
- Since we've shown that the theorem holds for an arbitrary [n], [m], [o], [p],
we've shown that it holds for all [n], [m], [o], and [p]s.
*)
(** The [apply] tactic also works with _conditional_ hypotheses
and lemmas: if the statement being applied is an implication, then
the premises of this implication will be added to the list of
subgoals needing to be proved. *)
Theorem silly2 : forall (n m o p : nat),
n = m ->
(forall (q r : nat), q = r -> [q;o] = [r;p]) ->
[n;o] = [m;p].
Proof.
intros n m o p eq1 eq2. (* Suppose [n], [m], [o], and [p] are each a fixed number.
Suppose also [n = m] and [forall (q r : nat), q = r -> [q;o] = [r;p]]
so we can prove the goal [n;o] = [m;p]. *)
apply eq2. (* [eq2] has the form [q = r -> [q; o] = [r; p]]. Coq can match the consequent of
this with the goal, by unifying the variables: [q] becomes [n] and [r] becomes [n].
That changes the goal to [q = r], except with the variables renamed,
so it's [n = m]. Our task now is to prove [n = m]. *)
apply eq1. (* The assumption [eq1] is the same as the goal, so we can call this mysterious
[apply eq1] to solve this. *)
Qed.
(** Typically, when we use [apply H], the statement [H] will
begin with a [forall] that binds some _universal variables_. When
Coq matches the current goal against the conclusion of [H], it
will try to find appropriate values for these variables. For
example, when we do [apply eq2] in the following proof, the
universal variable [q] in [eq2] gets instantiated with [n] and [r]
gets instantiated with [m]. *)
Theorem silly2a : forall (n m : nat),
(n,n) = (m,m) ->
(forall (q r : nat), (q,q) = (r,r) -> [q] = [r]) ->
[n] = [m].
Proof.
intros n m eq1 eq2.
apply eq2. apply eq1. Qed.
(** **** Exercise: 2 stars, optional (silly_ex) *)
(** Complete the following proof without using [simpl]. *)
Theorem silly_ex :
(forall n, evenb n = true -> oddb (S n) = true) ->
evenb 3 = true ->
oddb 4 = true.
Proof.
intros eq1 eq2. (* Suppose [eq1] is [forall n, evenb = true -> oddb (S n) = true], and
suppose [eq2] is [evenb 3 = true]. *)
(* We must show that [oddb 4 = true]. *)
apply eq1. (* The goal matches the consequent of [eq1]. So let's try to prove the antecedent.
We have to match the goal and the consequent. The consequent is [oddb (S n) = true],
and the goal is [oddb 4 = true], so the unification is [n = 3].
Our new goal is now [evenb 3 = true]. *)
apply eq2. (* The goal is the same as [eq2], so we can apply the mysterious [apply] to solve this. *)
Qed.
(** [] *)
(** To use the [apply] tactic, the (conclusion of the) fact
being applied must match the goal exactly -- for example, [apply]
will not work if the left and right sides of the equality are
swapped. *)
Theorem silly3_firsttry : forall (n : nat),
true = beq_nat n 5 ->
beq_nat (S (S n)) 7 = true.
Proof.
intros n H.
(** Here we cannot use [apply] directly, but we can use the [symmetry]
tactic, which switches the left and right sides of an equality in
the goal. *)
symmetry. (* This swaps the sides of the equation in the goal. *)
simpl. (* (This [simpl] is optional, since [apply] will perform
simplification first, if needed.) *)
Print beq_nat.
(* But, it's useful to think through it. [simpl] will apply the constructors/cases in
[beq_nat] to the goal. So it will see [beq_nat (S (S n)) 7] as [beq_nat (S (S n)) (S 6)],
and reduce it to [beq_nat (S n) (S 5)]. Then it will reduce that to [beq_nat n 5]. *)
apply H. (* Now the goal matches [H], so we can use the mysterious [apply] to solve the goal. *)
Qed.
(** **** Exercise: 3 stars (apply_exercise1) *)
(** (_Hint_: You can use [apply] with previously defined lemmas, not
just hypotheses in the context. Remember that [Search] is
your friend.) *)
Theorem rev_exercise1 : forall (l l' : list nat),
l = rev l' ->
l' = rev l.
Proof.
(* FILL IN HERE *) Admitted.
(** [] *)
(** **** Exercise: 1 star, optional (apply_rewrite) *)
(** Briefly explain the difference between the tactics [apply] and
[rewrite]. What are the situations where both can usefully be
applied? *)
(* Rewrite matches a term with an equation, and replaces the term
with the other side of the equal sign.
Apply will do this too on a non-conditional sentence, apparently.
However, apply can also be used for conditionals. In that case,
apply will try to match the consequent, by findingi a unification.
If it does find one, it will change the proof goal to the antecedent,
and rename it with the unification. *)
(** [] *)
(* ################################################################# *)
(** * The [apply ... with ...] Tactic *)
(** The following silly example uses two rewrites in a row to
get from [[a,b]] to [[e,f]]. *)
Example trans_eq_example : forall (a b c d e f : nat),
[a;b] = [c;d] ->
[c;d] = [e;f] ->
[a;b] = [e;f].
Proof.
intros a b c d e f eq1 eq2. (* Suppose [a b c d e f] are each a fixed number, and
suppose [eq1] is the first antecedent and [eq2] is the second.
Now we must prove [[a;b] = [e;f]]. *)
rewrite -> eq1. (* [eq1] says [[a;b][ and [[c;d]] are the same. So let's replace the former with
the latter. That rewrites the goal as [[c;d] = [e;f]]. *)
rewrite -> eq2. (* [eq2] says [[c;d]] and [[e;f]] are the same, so let's replace [[c;d]] in the
goal with [[e;f]]. *)
reflexivity. (* Now both sides of the equation are the same. *)
Qed.
(** Since this is a common pattern, we might like to pull it out
as a lemma recording, once and for all, the fact that equality is
transitive. *)
Theorem trans_eq : forall (X:Type) (n m o : X),
n = m -> m = o -> n = o.
Proof.
intros X n m o eq1 eq2. rewrite -> eq1. rewrite -> eq2.
reflexivity. Qed.
(** Now, we should be able to use [trans_eq] to prove the above
example. However, to do this we need a slight refinement of the
[apply] tactic. *)
Example trans_eq_example' : forall (a b c d e f : nat),
[a;b] = [c;d] ->
[c;d] = [e;f] ->
[a;b] = [e;f].
Proof.
intros a b c d e f eq1 eq2.
(** If we simply tell Coq [apply trans_eq] at this point, it can
tell (by matching the goal against the conclusion of the lemma)
that it should instantiate [X] with [[nat]], [n] with [[a,b]], and
[o] with [[e,f]]. However, the matching process doesn't determine
an instantiation for [m]: we have to supply one explicitly by
adding [with (m:=[c,d])] to the invocation of [apply]. *)
apply trans_eq with (m:=[c;d]). (* What does applying [trans_eq] actually do here? It does the
same thing that applying any implication does. It cehcks the
conclusion of the goal against the theorem [trans_eq]. It unifies,
and rewrites (it needs [m:=[c;d]] to help it do that). Then it
makes the new goal the antecedent, which in this case is
[[a;b] = [c;d]].
However, applying [trans_eq] generates two goals. Why? Well,
if you apply an implication, it will generate a separate goal
for each one of the antecedents in the implication. In this
case, the theorem [trans_eq] has two antecedents, because it
has the form [A -> B -> C]. So to prove [B -> C], we prove [A].
Then to prove [B -> C] we prove [B]. So we get two goals:
prove [A], then prove [B]. In this case [A] is [[a;b] = [c;d]],
and [B] is [[c;d] = [e;f]]. *)
apply eq1. (* [eq1] is a perfect match with our goal, so we can use the mysterious [apply eq1]
to solve goal 1. *)
apply eq2. (* [eq2] is a perfect match with goal 2, so we can use the mysterious [apply eq2]
here as well. *)
Qed.
(** Actually, we usually don't have to include the name [m] in
the [with] clause; Coq is often smart enough to figure out which
instantiation we're giving. We could instead write: [apply
trans_eq with [c;d]]. *)
(** **** Exercise: 3 stars, optional (apply_with_exercise) *)
Example trans_eq_exercise : forall (n m o p : nat),
m = (minustwo o) ->
(n + p) = m ->
(n + p) = (minustwo o).
Proof.
intros n m o p.
intros eq1 eq2.
(* apply trans_eq. *) (* Try to run this first. Coq says it can't find an instance for variable [m].
So we know that we need to provide an [m]. *)
apply trans_eq with (m:=m). (* In this case, the middle term is just [m]. So, when we apply
[trans_eq], which has the form [A -> B -> C], we get two new goals,
namely prove [A], and prove [B].
Goal 1 is to prove [n + p = m]. Goal 2 is [m = minustwo o]. *)
- rewrite -> eq2. (* [eq2] says [n + p] is the same as [m], so replace the former with the latter
in the goal. That yields [m = m]. *)
reflexivity. (* Both sides of the equation are the same. *)
- apply eq1. (* [eq1] is an exact match, so we can use the mysterious [apply eq1]. *)
Qed.
(** [] *)
(* ################################################################# *)
(** * The [inversion] Tactic *)
(** Recall the definition of natural numbers:
Inductive nat : Type :=
| O : nat
| S : nat -> nat.
It is obvious from this definition that every number has one of
two forms: either it is the constructor [O] or it is built by
applying the constructor [S] to another number. But there is more
here than meets the eye: implicit in the definition (and in our
informal understanding of how datatype declarations work in other
programming languages) are two more facts:
- The constructor [S] is _injective_. That is, if [S n = S m], it
must be the case that [n = m].
- The constructors [O] and [S] are _disjoint_. That is, [O] is not
equal to [S n] for any [n].
Similar principles apply to all inductively defined types: all
constructors are injective, and the values built from distinct
constructors are never equal. For lists, the [cons] constructor
is injective and [nil] is different from every non-empty list.
For booleans, [true] and [false] are different. (Since neither
[true] nor [false] take any arguments, their injectivity is not
interesting.) And so on. *)
(** Coq provides a tactic called [inversion] that allows us to
exploit these principles in proofs. To see how to use it, let's
show explicitly that the [S] constructor is injective: *)
Theorem S_injective : forall (n m : nat),
S n = S m ->
n = m.
Proof.
intros n m H. (* Suppose that [n] and [m] are fixed numbers. Suppose also the antecedent [H]. *)
(** By writing [inversion H] at this point, we are asking Coq to
generate all equations that it can infer from [H] as additional
hypotheses, replacing variables in the goal as it goes. In the
present example, this amounts to adding a new hypothesis [H1 : n =
m] and replacing [n] by [m] in the goal. *)
inversion H.
reflexivity.
Qed.
(** Here's a more interesting example that shows how multiple
equations can be derived at once. *)
Theorem inversion_ex1 : forall (n m o : nat),
[n; m] = [o; o] ->
[n] = [m].
Proof.
intros n m o H.
inversion H. (* This should figure out that [n = o] and [m = o]. It does not figure out that
[n = m] though. I'm not sure I can see why that it is.
In any case, it also rewrites both [n] and [m] in the goal with [o]. *)
reflexivity. (* So now both sides of the equation are the same. *)
Qed.
(** We can name the equations that [inversion] generates with an
[as ...] clause: *)
Theorem inversion_ex2 : forall (n m : nat),
[n] = [m] ->
n = m.
Proof.
intros n m H. inversion H as [Hnm]. reflexivity. Qed.
(** **** Exercise: 1 star (inversion_ex3) *)
Example inversion_ex3 : forall (X : Type) (x y z : X) (l j : list X),
x :: y :: l = z :: j ->
y :: l = x :: j ->
x = y.
Proof.
(* Suppose [X] is a fixed type. *)
intros X.
(* Suppose [x y z] are fixed elements of type [X]. *)
intros x y z.
(* Suppose [l] and [j] are fixed lists of type [X]. *)
intros l j.
(* Assume the antecedents, and call them [H1] and [H2]. *)
intros H1 H2.
(* Our goal is now to prove [x = y]. *)
(* [inversion] on [H1] should figure out these:
- [x = z]
- [y :: l = j]
*)
inversion H1.
(* [inversion] on [H2] should figure out these:
- [y = x]
- [l = j]
*)
inversion H2.
(* [H0] tells us that [x] is the same as [z], so let's replace [z] with [x] in the goal. *)
rewrite <- H0.
(* Now both sides of the equation are the same. *)
reflexivity.
Qed.
(** [] *)
(** When used on a hypothesis involving an equality between
_different_ constructors (e.g., [S n = O]), [inversion] solves the
goal immediately. Consider the following proof: *)
Theorem beq_nat_0_l : forall n,
beq_nat 0 n = true -> n = 0.
Proof.
(* Suppose [n] is a fixed number. *)
intros n.
(** We can proceed by case analysis on [n]. The first case is
trivial. *)
destruct n as [| n'].
- (* n = 0 *)
intros H.
reflexivity.
(** However, the second one doesn't look so simple: assuming
[beq_nat 0 (S n') = true], we must show [S n' = 0], but the latter
clearly contradictory! The way forward lies in the assumption.
After simplifying the goal state, we see that [beq_nat 0 (S n') =
true] has become [false = true]: *)
- (* n = S n' *)
simpl.
(** If we use [inversion] on this hypothesis, Coq notices that
the subgoal we are working on is impossible, and therefore removes
it from further consideration. *)
intros H.
inversion H. (* Does [inversion H] realize that the hypothesis is impossible,
or the goal? If the latter, why does it care about the goal? *)
Qed.
(** This is an instance of a logical principle known as the _principle
of explosion_, which asserts that a contradictory hypothesis
entails anything, even false things! *)
Theorem inversion_ex4 : forall (n : nat),
S n = O ->
2 + 2 = 5.
Proof.
intros n contra. inversion contra. Qed.
Theorem inversion_ex5 : forall (n m : nat),
false = true ->
[n] = [m].
Proof.
intros n m contra. inversion contra. Qed.
(** If you find the principle of explosion confusing, remember
that these proofs are not actually showing that the conclusion of
the statement holds. Rather, they are arguing that, if the
nonsensical situation described by the premise did somehow arise,
then the nonsensical conclusion would follow. We'll explore the
principle of explosion of more detail in the next chapter. *)
(** **** Exercise: 1 star (inversion_ex6) *)
Example inversion_ex6 : forall (X : Type)
(x y z : X) (l j : list X),
x :: y :: l = [] ->
y :: l = z :: j ->
x = z.
Proof.
intros X x y z l j H1 H2.
inversion H1. (* [H1] says that three [cons]es -- [x :: y :: l] -- are the same as the
empty list [[]]. That's by definition impossible. *)
Qed.
(** [] *)
(** To summarize this discussion, suppose [H] is a hypothesis in the
context or a previously proven lemma of the form
c a1 a2 ... an = d b1 b2 ... bm
for some constructors [c] and [d] and arguments [a1 ... an] and
[b1 ... bm]. Then [inversion H] has the following effect:
- If [c] and [d] are the same constructor, then, by the
injectivity of this constructor, we know that [a1 = b1], [a2 =
b2], etc. The [inversion H] adds these facts to the context and
tries to use them to rewrite the goal.
- If [c] and [d] are different constructors, then the hypothesis
[H] is contradictory, and the current goal doesn't have to be
considered at all. In this case, [inversion H] marks the
current goal as completed and pops it off the goal stack. *)
(** The injectivity of constructors allows us to reason that
[forall (n m : nat), S n = S m -> n = m]. The converse of this
implication is an instance of a more general fact about both
constructors and functions, which we will find convenient in a few
places below: *)
Theorem f_equal : forall (A B : Type) (f: A -> B) (x y: A),
x = y -> f x = f y.
Proof. intros A B f x y eq. rewrite eq. reflexivity. Qed.
(* ################################################################# *)
(** * Using Tactics on Hypotheses *)
(** By default, most tactics work on the goal formula and leave
the context unchanged. However, most tactics also have a variant
that performs a similar operation on a statement in the context.
For example, the tactic [simpl in H] performs simplification in
the hypothesis named [H] in the context. *)
Theorem S_inj : forall (n m : nat) (b : bool),
beq_nat (S n) (S m) = b ->
beq_nat n m = b.
Proof.
intros n m b H. simpl in H. apply H. Qed.
(** Similarly, [apply L in H] matches some conditional statement
[L] (of the form [L1 -> L2], say) against a hypothesis [H] in the
context. However, unlike ordinary [apply] (which rewrites a goal
matching [L2] into a subgoal [L1]), [apply L in H] matches [H]
against [L1] and, if successful, replaces it with [L2].
In other words, [apply L in H] gives us a form of "forward
reasoning": from [L1 -> L2] and a hypothesis matching [L1], it
produces a hypothesis matching [L2]. By contrast, [apply L] is
"backward reasoning": it says that if we know [L1->L2] and we are
trying to prove [L2], it suffices to prove [L1].
Here is a variant of a proof from above, using forward reasoning
throughout instead of backward reasoning. *)
Theorem silly3' : forall (n : nat),
(beq_nat n 5 = true -> beq_nat (S (S n)) 7 = true) ->
true = beq_nat n 5 ->
true = beq_nat (S (S n)) 7.
Proof.
intros n eq H.
symmetry in H. apply eq in H. symmetry in H.
apply H. Qed.
(** Forward reasoning starts from what is _given_ (premises,
previously proven theorems) and iteratively draws conclusions from
them until the goal is reached. Backward reasoning starts from
the _goal_, and iteratively reasons about what would imply the
goal, until premises or previously proven theorems are reached.
If you've seen informal proofs before (for example, in a math or
computer science class), they probably used forward reasoning. In
general, idiomatic use of Coq tends to favor backward reasoning,
but in some situations the forward style can be easier to think
about. *)
(** **** Exercise: 3 stars, recommended (plus_n_n_injective) *)
(** Practice using "in" variants in this proof. (Hint: use
[plus_n_Sm].) *)
Theorem plus_n_n_injective : forall n m,
n + n = m + m ->
n = m.
Proof.
intros n.
induction n as [| n'].
(* FILL IN HERE *) Admitted.
(** [] *)
(* ################################################################# *)
(** * Varying the Induction Hypothesis *)
(** Sometimes it is important to control the exact form of the
induction hypothesis when carrying out inductive proofs in Coq.
In particular, we need to be careful about which of the
assumptions we move (using [intros]) from the goal to the context
before invoking the [induction] tactic. For example, suppose
we want to show that the [double] function is injective -- i.e.,
that it maps different arguments to different results:
Theorem double_injective: forall n m,
double n = double m -> n = m.
The way we _start_ this proof is a bit delicate: if we begin with
intros n. induction n.
all is well. But if we begin it with
intros n m. induction n.
we get stuck in the middle of the inductive case... *)
Theorem double_injective_FAILED : forall n m,
double n = double m ->
n = m.
Proof.
intros n m. induction n as [| n'].
- (* n = O *) simpl. intros eq. destruct m as [| m'].
+ (* m = O *) reflexivity.
+ (* m = S m' *) inversion eq.
- (* n = S n' *) intros eq. destruct m as [| m'].
+ (* m = O *) inversion eq.
+ (* m = S m' *) apply f_equal.
(** At this point, the induction hypothesis, [IHn'], does _not_ give us
[n' = m'] -- there is an extra [S] in the way -- so the goal is
not provable. *)
Abort.
(** What went wrong? *)
(** The problem is that, at the point we invoke the induction
hypothesis, we have already introduced [m] into the context --
intuitively, we have told Coq, "Let's consider some particular [n]
and [m]..." and we now have to prove that, if [double n = double
m] for _these particular_ [n] and [m], then [n = m].
The next tactic, [induction n] says to Coq: We are going to show
the goal by induction on [n]. That is, we are going to prove, for
_all_ [n], that the proposition
- [P n] = "if [double n = double m], then [n = m]"
holds, by showing
- [P O]
(i.e., "if [double O = double m] then [O = m]") and
- [P n -> P (S n)]
(i.e., "if [double n = double m] then [n = m]" implies "if
[double (S n) = double m] then [S n = m]").
If we look closely at the second statement, it is saying something
rather strange: it says that, for a _particular_ [m], if we know
- "if [double n = double m] then [n = m]"
then we can prove
- "if [double (S n) = double m] then [S n = m]".
To see why this is strange, let's think of a particular [m] --
say, [5]. The statement is then saying that, if we know
- [Q] = "if [double n = 10] then [n = 5]"
then we can prove
- [R] = "if [double (S n) = 10] then [S n = 5]".
But knowing [Q] doesn't give us any help at all with proving
[R]! (If we tried to prove [R] from [Q], we would start with
something like "Suppose [double (S n) = 10]..." but then we'd be
stuck: knowing that [double (S n)] is [10] tells us nothing about
whether [double n] is [10], so [Q] is useless.) *)
(** Trying to carry out this proof by induction on [n] when [m] is
already in the context doesn't work because we are then trying to
prove a relation involving _every_ [n] but just a _single_ [m]. *)
(** The successful proof of [double_injective] leaves [m] in the goal
statement at the point where the [induction] tactic is invoked on
[n]: *)
Theorem double_injective : forall n m,
double n = double m ->
n = m.
Proof.
intros n. induction n as [| n'].
- (* n = O *) simpl. intros m eq. destruct m as [| m'].
+ (* m = O *) reflexivity.
+ (* m = S m' *) inversion eq.
- (* n = S n' *) simpl.
(** Notice that both the goal and the induction hypothesis are
different this time: the goal asks us to prove something more
general (i.e., to prove the statement for _every_ [m]), but the IH
is correspondingly more flexible, allowing us to choose any [m] we
like when we apply the IH. *)
intros m eq.
(** Now we've chosen a particular [m] and introduced the assumption
that [double n = double m]. Since we are doing a case analysis on
[n], we also need a case analysis on [m] to keep the two "in sync." *)
destruct m as [| m'].
+ (* m = O *) simpl.
(** The 0 case is trivial: *)
inversion eq.
+ (* m = S m' *)
Print f_equal.
apply f_equal.
(** At this point, since we are in the second branch of the [destruct
m], the [m'] mentioned in the context is the predecessor of the
[m] we started out talking about. Since we are also in the [S]
branch of the induction, this is perfect: if we instantiate the
generic [m] in the IH with the current [m'] (this instantiation is
performed automatically by the [apply] in the next step), then
[IHn'] gives us exactly what we need to finish the proof. *)
apply IHn'. inversion eq. reflexivity. Qed.
(** What you should take away from all this is that we need to be
careful about using induction to try to prove something too
specific: To prove a property of [n] and [m] by induction on [n],
it is sometimes important to leave [m] generic. *)
(** The following exercise requires the same pattern. *)
(** **** Exercise: 2 stars (beq_nat_true) *)
Theorem beq_nat_true : forall n m,
beq_nat n m = true -> n = m.
Proof.
(* Suppose [n] is some fixed number. *)
intros n.
(* Let's proceed by induction on [n]. *)
induction n as [| n' IHn'].
- (* Case: [n = 0]. *)
(* We must show that [forall m : nat, beq_nat 0 m = true -> n = m]. *)
(* Suppose now that [m] is a fixed number. *)
intros m.
(* Let's proceed by induction on [m]. *)
induction m as [| m' IHm'].
+ (* Case: [m = 0]. *)
(* We must show that [beq_nat 0 0 = true -> n = m]. *)
(* We can use the definition of [beq_nat 0] to simplify the left hand side
of the equation to [true], which yields [true = true -> n = m]. *)
simpl.
(* [reflexivity] can solve the rest (somehow). *)
reflexivity.
+ (* Case: [m = S m']. *)
(* We must show that [beq_nat 0 S m' = true -> n = S m'], with the induction hypothesis
that [beq_nat 0 m' = true -> n = m']. *)
(* Suppose that the antecedent is true, i.e., suppose that [H]: [beq_nat 0 S m' = true]. *)
intros H.
(* From the definition of [beq_nat 0], we can see that [S m' = 0].
But this is impossible, so we can solve this goal. *)
inversion H.
- (* Case: [n = S n']. *)
(* We must show that [forall m : nat, beq_nat S n' m = true -> S n' = m], with the
induction hypothesis that [forall m : nat, beq_nat n' m = true -> n' = m]. *)
(* Suppose [m] is a fixed number. *)
intros m.
(* Let's proceed by induction on [m]. *)
induction m as [| m' IHm'].
+ (* Case: [m = 0]. *)
(* We must show that [beq_nat S n' 0 = true -> S n' = 0]. *)
(* What's the definition of [beq_nat] again for [beq_nat S n' 0]? *)
Print beq_nat.
(* The definition of [beq_nat S n'] says that if the second argument [m] is [0],
then [beq_nat] evaluates to [false]. So we can simplify to [false = true -> S n' = 0]. *)
simpl.
(* Suppose the antecedent [false = true]. *)
intros H.
(* From that, anything follows. *)
inversion H.
+ (* Case: [m = S m']. *)
(* We must show that [beq_nat S n' S m' = true -> S n' = S m'], with the induction hypothesis
that [beq_nat S n' m' = true -> S n' = m']. *)
(* What's the definition of [beq_nat] for [beq_nat S n' S m']+ *)
Print beq_nat.
(* The definition says that [beq_nat S n' S m'] is the same as [beq_nat n' m'].
So we can simplify the goal to [beq_nat n' m' = true -> S n' = S m']. *)
simpl.
(* Suppose the antecedent [beq_nat n' m' = true] is true. Call it [H]. *)
intros H.
(* The goal is now [S n' = S m']. Does [f_equal] help? *)
Print f_equal.
(* It says that [f x = f y -> x = y]. In this case, [f] = [S], [x] = [n'], and [y] = [m'].
So our goal matches the conclusion of [f_equal]. Let's apply it. *)
apply f_equal.
(* Our goal is now to prove that [n' = m']. *)
(* Well, that matches the conclusion of the induction hypothesis [IHn']. So let's apply it. *)
apply IHn'.
(* Our goal is now to prove the antecedent of [IHn'], namely that [beq_nat n' m' = true]. *)
(* But that is precisely what [H] says. *)
apply H.
Qed.
(** [] *)
(** **** Exercise: 2 stars, advanced (beq_nat_true_informal) *)
(** Give a careful informal proof of [beq_nat_true], being as explicit
as possible about quantifiers. *)
(* Do not modify the following line: *)
Definition manual_grade_for_informal_proof : option (prod nat string) := None.
(* Informal proof:
Theorem: [forall n m : nat, beq_nat n m = true -> n = m].
Proof: by induction on [n].
- Suppose [n] is a fixed number.
- Let's proceed by induction on [n].
- First, suppose [n = 0]. We must show that [forall m : nat, beq_nat 0 m = true -> 0 = m].
- Suppose that [m] is a fixed number.
- Let's proceed by induction on [m].
- First, suppose [m = 0]. We must show that [beq_nat 0 0 = true -> 0 = 0].
- This follows by the definition of [beq_nat 0 0].
- Second, suppose [m = S m']. We must show that
[beq_nat 0 S m' = true -> 0 = S m'],
assuming (an induction hypothesis) that:
[beq_nat 0 m' = true -> 0 = m'].
- Suppose the antecedent [beq_nat 0 S m'] were true.
- We would then have to prove is [0 = S m'], which is impossible.
- We've shown that the theorem holds for all possible shapes that [m] can take,
when [n = 0]. So we've shown that the theorem holds when [n = 0].
- Second, suppose [n = S n']. We must show that
[forall m : nat, beq_nat S n' m = true -> S n' = m]
given (an induction hypothesis) that:
[forall m : nat, beq_nat n' m = true -> n' = m].
- Suppose that [m] is a fixed number.
- Let's proceed by induction on [m].
- First, suppose [m = 0]. We must show that [beq_nat S n' 0 = true -> S n' = 0].
- By definition, [beq_nat S n' 0] is [false], so we are trying to prove
[false = true -> S n' = 0].
- Suppose the antecedent [false = true] were true. Then [S n' = 0] follows ex falso.
- Second, suppose [m = S m']. We must show that
[beq_nat S n' S m' = true -> S n' = S m'],
given (an induction hypothesis) that
[beq_nat S n' m' = true -> S n' = m'].
- By definition, [beq_nat S n' S m'] is the same as [beq_nat n' m'].
So we must show that:
[beq_nat n' m' = true -> S n' = S m'].
- Suppose the hypothesis [beq_nat n' m'] were true. Call it [H].
Now we must show that:
[S n' = S m'].
- [f_equal] says that [x = y -> f x = f y]. In this case, [f] = [S], [x] = [n'], and
[y] = [m']. So we must prove the antecedent:
[n' = m'].
- If we let [m'] be [m], then this matches the consequent of the induction hypothesis
[forall m : nat, beq_nat n' m = true -> n' = m]. So now we must show that:
[beq_nat n' m' = true].
- And this is exactly [H].
- We have shown that the theorem holds for all shapes that [m] can take when [n = S n'].
So we have shown that theorem holds for [n = S n'].
- We have shown that the theorem holds for all the shapes that [n] can take too,
so we have shown that the theorem holds for [n].
- Since we have shown that the theorem holds for an arbitrary [n], we have shown that
it holds for all [n]s. []
*)
(** [] *)
(** The strategy of doing fewer [intros] before an [induction] to
obtain a more general IH doesn't always work by itself; sometimes
some _rearrangement_ of quantified variables is needed. Suppose,
for example, that we wanted to prove [double_injective] by
induction on [m] instead of [n]. *)
Theorem double_injective_take2_FAILED : forall n m,
double n = double m ->
n = m.
Proof.
intros n m. induction m as [| m'].
- (* m = O *) simpl. intros eq. destruct n as [| n'].
+ (* n = O *) reflexivity.
+ (* n = S n' *) inversion eq.
- (* m = S m' *) intros eq. destruct n as [| n'].
+ (* n = O *) inversion eq.
+ (* n = S n' *) apply f_equal.
(* Stuck again here, just like before. *)
Abort.
(** The problem is that, to do induction on [m], we must first
introduce [n]. (If we simply say [induction m] without
introducing anything first, Coq will automatically introduce [n]
for us!) *)
(** What can we do about this? One possibility is to rewrite the
statement of the lemma so that [m] is quantified before [n]. This
works, but it's not nice: We don't want to have to twist the
statements of lemmas to fit the needs of a particular strategy for
proving them! Rather we want to state them in the clearest and
most natural way. *)
(** What we can do instead is to first introduce all the quantified
variables and then _re-generalize_ one or more of them,
selectively taking variables out of the context and putting them
back at the beginning of the goal. The [generalize dependent]
tactic does this. *)
Theorem double_injective_take2 : forall n m,
double n = double m ->
n = m.
Proof.
intros n m.
(* [n] and [m] are both in the context *)
generalize dependent n.
(* Now [n] is back in the goal and we can do induction on
[m] and get a sufficiently general IH. *)
induction m as [| m'].
- (* m = O *)
(* We must show that [forall n : nat, double n = double 0 -> n = 0]. *)
(* By the definition of [double 0], we can rewrite that to [0].
The goal is now [double n = 0 -> n = 0]. *)
simpl.
(* Suppose [n] is a fixed number, and that the antecedent [double n = 0] is true. Call it [eq]. *)
intros n eq.
(* Let's consider the two cases [n] can take. It can be [0], or the successor [S] of some [n']. *)
destruct n as [| n'].
+ (* n = O *)
(* We must show that [0 = 0], given the assumption [eq] that [double 0 = 0]. *)
(* Both sides of the equation are the same. *)
reflexivity.
+ (* n = S n' *)
(* We must show that [S n' = 0], given the assumption [eq] that [double S n' = 0 -> S n' = 0]. *)
(* What's the definition of [double S n']? *)
Print double.
(* [double S n'] is the same as [S (S (double n'))]. So, we could rewrite [eq] to be
[S (S (double n')) = 0]. But that's impossible. So we can solve this goal ex falso. *)
inversion eq.
- (* m = S m' *)
(* We must show that [forall n : nat, double n = double (S m') -> n = S m'], with an
induction hypothesis that [forall n : nat, double n = double m' -> n = m']. *)
(* Suppose that [n] is a fixed number, and suppose the antecedent [double n = double (S m')]
is true (call it [eq]). *)
intros n eq.
(* Now we must show that [n = S m']. *)
(* Let's consider the two shapes that [n] can take. It can be [0], or [S n']. *)
destruct n as [| n'].
+ (* n = O *)
(* We must show that [0 = S m'], given the assumption [eq] that [double 0 = double (S m')]. *)
(* The definition of [double] shows that [eq] is impossible, so we can solve this
goal with ex falso. *)
inversion eq.
+ (* n = S n' *)
(* Now we must show that [S n' = S m'], given the assumption [eq] that
[double S n' = double S m']. *)
Print f_equal.
(* [f_equal] says that [x = y -> f x = f y]. In our case, the consequent is [S n' = S m'],
so we can apply this. *)
apply f_equal.
(* Now we must show that [n' = m']. *)
(* The induction hypothesis [IHm'] says that [forall n : nat, double n = double m' -> n = m'].
We can unify the consequent with our goal if we let [n] be [n']. *)
apply IHm'.
(* So our job now is to show that [double n' = double m']. *)
(* What follows from [eq], which is [double S n' = double S m']? *)
Print double.
(* [double] says that [double S n'] is the same as [S (S (double n')].
So, from [eq], we can infer [S (S (double n')) = S (S (double m'))]. *)
inversion eq.
(* But somehow, [inversion eq] derives this: [double n' = double m'].
I don't think I see how it did that. *)
(* We can rewrite [double n'] to [double m']. *)
rewrite -> H0.
(* And now both sides of the equation are the same. *)
reflexivity.
Qed.
(** Let's look at an informal proof of this theorem. Note that
the proposition we prove by induction leaves [n] quantified,
corresponding to the use of generalize dependent in our formal
proof.
_Theorem_: For any nats [n] and [m], if [double n = double m], then
[n = m].
_Proof_: Let [m] be a [nat]. We prove by induction on [m] that, for
any [n], if [double n = double m] then [n = m].
- First, suppose [m = 0], and suppose [n] is a number such
that [double n = double m]. We must show that [n = 0].
Since [m = 0], by the definition of [double] we have [double n =
0]. There are two cases to consider for [n]. If [n = 0] we are
done, since [m = 0 = n], as required. Otherwise, if [n = S n']
for some [n'], we derive a contradiction: by the definition of
[double], we can calculate [double n = S (S (double n'))], but
this contradicts the assumption that [double n = 0].
- Second, suppose [m = S m'] and that [n] is again a number such
that [double n = double m]. We must show that [n = S m'], with
the induction hypothesis that for every number [s], if [double s =
double m'] then [s = m'].
By the fact that [m = S m'] and the definition of [double], we
have [double n = S (S (double m'))]. There are two cases to
consider for [n].
If [n = 0], then by definition [double n = 0], a contradiction.
Thus, we may assume that [n = S n'] for some [n'], and again by
the definition of [double] we have [S (S (double n')) =
S (S (double m'))], which implies by inversion that [double n' =
double m']. Instantiating the induction hypothesis with [n'] thus
allows us to conclude that [n' = m'], and it follows immediately
that [S n' = S m']. Since [S n' = n] and [S m' = m], this is just
what we wanted to show. [] *)
(** Before we close this section and move on to some exercises,
let's digress briefly and use [beq_nat_true] to prove a similar
property of identifiers that we'll need in later chapters: *)
Theorem beq_id_true : forall x y,
beq_id x y = true -> x = y.
Proof.
(* What's [beq_id]? *)
Print beq_id.
(* [beq_id] matches identifiers (i.e., objects constructed with [Id n], where [n] is a [nat]. *)
(* Suppose that [x] is a fixed number [m] and [y] is a fixed number [n]. *)
intros [m] [n].
(* We must show that [beq_id (Id m) (Id n) = true -> Id m = Id n]. *)
(* By the definition of [beq_id], [beq_id (Id m) (Id n)] is the same as [beq_nat m n].
So we can rewrite our goal: [beq_nat m n = true -> Id m = Id n]. *)
simpl.
(* Suppose the antecedent [beq_nat m n = true], call it [H]. *)
intros H.
(* Now we must show that [Id m = Id n]. *)
(* Let's prove an auxiliary lemma: [H'], namely that [m = n]. *)
assert (H' : m = n).
{
(* We must show that [m = n]. *)
(* What's [beq_nat_true]? *)
Print beq_nat_true.
(* It says: if [beq_nat n m = true -> n = m]. We can apply that here. *)
apply beq_nat_true.
(* Our new goal is thus to prove the antecedent: [beq_nat n m = true].
And that's exactly our hypothesis [H]. *)
apply H.
}
(* Now we return to proving our goal [Id m = Id n], except we have [H': m = n].
[H'] says that [m] is the same as [n], so we can replace [m] in our goal with [n]. *)
rewrite H'.
(* That yields [Id n = Id n], and both sides of the equation are the same. *)
reflexivity.
Qed.
(** **** Exercise: 3 stars, recommended (gen_dep_practice) *)
(** Prove this by induction on [l]. *)
Theorem nth_error_after_last: forall (n : nat) (X : Type) (l : list X),
length l = n ->
nth_error l n = None.
Proof.
(* FILL IN HERE *) Admitted.
(** [] *)
(* ################################################################# *)
(** * Unfolding Definitions *)
(** It sometimes happens that we need to manually unfold a Definition
so that we can manipulate its right-hand side. For example, if we
define... *)
Definition square n := n * n.
(** ... and try to prove a simple fact about [square]... *)
Lemma square_mult : forall n m, square (n * m) = square n * square m.
Proof.
(* Suppose that [n] and [m] are fixed numbers. *)
intros n m.
(* Now we must show that [square (n * m) = square n * square m]. *)
(* [simpl] shouldn't be able to unfold this any, because there is
no real constructor to match/unfold. *)
simpl.
(** ... we get stuck: [simpl] doesn't simplify anything at this point,
and since we haven't proved any other facts about [square], there
is nothing we can [apply] or [rewrite] with.
To make progress, we can manually [unfold] the definition of
[square]: *)
unfold square. (* This replaces [square x] with [x * x]. *)
(** Now we have plenty to work with: both sides of the equality are
expressions involving multiplication, and we have lots of facts
about multiplication at our disposal. In particular, we know that
it is commutative and associative, and from these facts it is not
hard to finish the proof. *)
Print mult_assoc. (* [forall n m p : nat, n * (m * p) = n * m * p], as expected. *)
(* The goal has the form [a * b * (a * b) = a * a * (b * b)]. Coq can parse the left side
of the equation as [A * B * C], if it lets [C] be [(a * b)]. As for the right side, it
sees this as [A * A * B] (where [A] is [a] and [B] is [(b * b)].
It can't match [mult_assoc] to the right side. But it can match the left side.
So it will move the parentheses from around [C] (which is [(a * b)])
to around [A * B] (which is [n * m]). That is, it will yield:
[(n * m) * n * m = n * n * (m * m)]. *)
rewrite mult_assoc.
(* Let's prove a lemma. *)
assert (H : n * m * n = n * n * m).
{ (* Our goal is to prove n * m * n = n * n * m. *)
Print mult_comm.
(* Coq will see [n * m * n] on the left side as [(n * m) * n]. In other words, it will see
[A * B], where [A] is [(n * m)] and [B] is [n]. When we apply [mult_comm], it will
flip the order. So we should get [B * A], i.e., [n * (n * m)].
Now, on the right side of the equation, I would think we have [(n * n) * m],
i.e., [C * D], where [C] is [(n * n)] and [D] is [m]. When we apply [mult_comm],
I would think that it should switch this too, to get [D * C], i.e., [m * (n * n)].
But it doesn't do anything to the right side of the equation.
I don't understand why. *)
rewrite mult_comm.
(* Now we only have to switch the parentheses to get the result we want. *)
apply mult_assoc.
}
(* Now we return our goal: [n * m * n * m = n * n * (m * m)], but with [H] in the context. *)
(* [H] says that if we have [n * m * n], we can replace it with [n * n * m]. We do have that
pattern on the left side of the goal, so let's do the replacement. *)
rewrite H.
(* The goal is now [(n * n) * m * m = n * n * (m * m)].
If we apply [mult_assoc], Coq flips the parentheses on the right side of the equation.
I don't see how it's matching this. Does it see [A * B * C], where [C] is [(m * m)]? *)
rewrite mult_assoc.
(* Both sides of the equation are the same now. *)
reflexivity.
Qed.
(** At this point, a deeper discussion of unfolding and simplification
is in order.
You may already have observed that tactics like [simpl],
[reflexivity], and [apply] will often unfold the definitions of
functions automatically when this allows them to make progress. For
example, if we define [foo m] to be the constant [5]... *)
Definition foo (x: nat) := 5.
(** then the [simpl] in the following proof (or the [reflexivity], if
we omit the [simpl]) will unfold [foo m] to [(fun x => 5) m] and
then further simplify this expression to just [5]. *)
Fact silly_fact_1 : forall m, foo m + 1 = foo (m + 1) + 1.
Proof.
intros m.
simpl.
reflexivity.
Qed.
(** However, this automatic unfolding is rather conservative. For
example, if we define a slightly more complicated function
involving a pattern match... *)
Definition bar x :=
match x with
| O => 5
| S _ => 5
end.
(** ...then the analogous proof will get stuck: *)
Fact silly_fact_2_FAILED : forall m, bar m + 1 = bar (m + 1) + 1.
Proof.
intros m.
simpl. (* Does nothing! *)
Abort.
(** The reason that [simpl] doesn't make progress here is that it
notices that, after tentatively unfolding [bar m], it is left with
a match whose scrutinee, [m], is a variable, so the [match] cannot
be simplified further. (It is not smart enough to notice that the
two branches of the [match] are identical.) So it gives up on
unfolding [bar m] and leaves it alone. Similarly, tentatively
unfolding [bar (m+1)] leaves a [match] whose scrutinee is a
function application (that, itself, cannot be simplified, even
after unfolding the definition of [+]), so [simpl] leaves it
alone. *)
(* The above doesn't work because [m] doesn't have the shape of [0] or [S m'].
It's just an unevaluated variable, and there's no match for that in [bar].
We need to, say, destruct [m] to consider it with the shape [0] or [S m'].
Then [simpl] can match _those_ shapes to the definitions in [bar].
For example, consider the following:
Proof.
intros m.
destruct m as [| m'].
- (* Case: [m = 0]. *)
(* We must show that [bar 0 + 1 = bar (0 + 1) + 1]. *)
(* [simpl] can unfold [bar 0] and see that it rewrites to [5]. *)
simpl.
reflexivity.
- (* Case: [m = S m']. *)
(* We must show that [bar S m' + 1 = bar (S m' + 1) + 1]. *)
(* [simpl] can unfold [bar S m'] and see that it rewrites to [5]. *)
simpl.
reflexivity.
Qed.
*)
(** At this point, there are two ways to make progress. One is to use
[destruct m] to break the proof into two cases, each focusing on a
more concrete choice of [m] ([O] vs [S _]). In each case, the
[match] inside of [bar] can now make progress, and the proof is
easy to complete. *)
Fact silly_fact_2 : forall m, bar m + 1 = bar (m + 1) + 1.
Proof.
intros m.
destruct m.
- simpl. reflexivity.
- simpl. reflexivity.
Qed.
(** This approach works, but it depends on our recognizing that the
[match] hidden inside [bar] is what was preventing us from making
progress. *)
(** A more straightforward way to make progress is to explicitly tell
Coq to unfold [bar]. *)
Fact silly_fact_2' : forall m, bar m + 1 = bar (m + 1) + 1.
Proof.
intros m.
unfold bar.
(** Now it is apparent that we are stuck on the [match] expressions on
both sides of the [=], and we can use [destruct] to finish the
proof without thinking too hard. *)
destruct m.
- reflexivity.
- reflexivity.
Qed.
(* ################################################################# *)
(** * Using [destruct] on Compound Expressions *)
(** We have seen many examples where [destruct] is used to
perform case analysis of the value of some variable. But
sometimes we need to reason by cases on the result of some
_expression_. We can also do this with [destruct].
Here are some examples: *)
Definition sillyfun (n : nat) : bool :=
if beq_nat n 3 then false
else if beq_nat n 5 then false
else false.
Theorem sillyfun_false : forall (n : nat),
sillyfun n = false.
Proof.
(* Suppose [n] is a fixed number. *)
intros n.
(* Unfold the definition, inline. *)
unfold sillyfun.
(* Consider the shapes that [beq_nat n 3] can take, and generate a new goal
for each of those cases. [beq_nat n 3] can take two shapes: one where it's [true],
and one where it's [false]. *)
destruct (beq_nat n 3).
- (* Case: [beq_nat n 3 = true] *)
(* Notice that [destruct] has simplified the left side of the equation. *)
reflexivity.
- (* Case: [beq_nat n 3 = false] *)
(* Notice that [destruct] has simplified the left side again. And it's removed
the first option [if beq_nat n 3], leaving only the second two. *)
(* So now we need to consider the two possible shapes that [beq_nat n 5] can take.
Again, we have the case where it's [true], and the case where it's [false]. *)
destruct (beq_nat n 5).
+ (* beq_nat n 5 = true *) reflexivity.
+ (* beq_nat n 5 = false *) reflexivity.
Qed.
(** After unfolding [sillyfun] in the above proof, we find that
we are stuck on [if (beq_nat n 3) then ... else ...]. But either
[n] is equal to [3] or it isn't, so we can use [destruct (beq_nat
n 3)] to let us reason about the two cases.
In general, the [destruct] tactic can be used to perform case
analysis of the results of arbitrary computations. If [e] is an
expression whose type is some inductively defined type [T], then,
for each constructor [c] of [T], [destruct e] generates a subgoal
in which all occurrences of [e] (in the goal and in the context)
are replaced by [c]. *)
(** **** Exercise: 3 stars, optional (combine_split) *)
(** Here is an implementation of the [split] function mentioned in
chapter [Poly]: *)
Fixpoint split {X Y : Type} (l : list (X*Y))
: (list X) * (list Y) :=
match l with
| [] => ([], [])
| (x, y) :: t =>
match split t with
| (lx, ly) => (x :: lx, y :: ly)
end
end.
(** Prove that [split] and [combine] are inverses in the following
sense: *)
Theorem combine_split : forall X Y (l : list (X * Y)) l1 l2,
split l = (l1, l2) ->
combine l1 l2 = l.
Proof.
(* FILL IN HERE *) Admitted.
(** [] *)
(** However, [destruct]ing compound expressions requires a bit of
care, as such [destruct]s can sometimes erase information we need
to complete a proof. *)
(** For example, suppose we define a function [sillyfun1] like
this: *)
Definition sillyfun1 (n : nat) : bool :=
if beq_nat n 3 then true
else if beq_nat n 5 then true
else false.
(** Now suppose that we want to convince Coq of the (rather
obvious) fact that [sillyfun1 n] yields [true] only when [n] is
odd. By analogy with the proofs we did with [sillyfun] above, it
is natural to start the proof like this: *)
Theorem sillyfun1_odd_FAILED : forall (n : nat),
sillyfun1 n = true ->
oddb n = true.
Proof.
(* Suppose [n] is a fixed number, and suppose the antecedent is true (call it [eq]). *)
intros n eq.
(* The goal is now to prove [oddb n = true], given the antecedent [sillyfun n = true]. *)
(* We can unfold the definition of [sillyfun] in [eq]. *)
unfold sillyfun1 in eq.
(* Now we can consider the two shapes [beq_nat n 3] can take. *)
destruct (beq_nat n 3).
(* stuck... *)
Abort.
(** We get stuck at this point because the context does not
contain enough information to prove the goal! The problem is that
the substitution performed by [destruct] is too brutal -- it threw
away every occurrence of [beq_nat n 3], but we need to keep some
memory of this expression and how it was destructed, because we
need to be able to reason that, since [beq_nat n 3 = true] in this
branch of the case analysis, it must be that [n = 3], from which
it follows that [n] is odd.
What we would really like is to substitute away all existing
occurences of [beq_nat n 3], but at the same time add an equation
to the context that records which case we are in. The [eqn:]
qualifier allows us to introduce such an equation, giving it a
name that we choose. *)
Theorem sillyfun1_odd : forall (n : nat),
sillyfun1 n = true ->
oddb n = true.
Proof.
(* Suppose [n] is a fixed number, and suppose the antecedent is control (call it [eq]). *)
intros n eq.
(* Replace [sillyfun1 n] in [eq] with its definition. *)
unfold sillyfun1 in eq.
(* Consider the two different shapes [beq_nat n 3] can take, but save each case
as [Heqe3] (i.e., in the first case, save [beq_nat n 3 = true] as [Heqe3], then
in the second case, save [beq_nat n 3 = false] as [Heqe3]. *)
destruct (beq_nat n 3) eqn:Heqe3.
(* Now we have the same state as at the point where we got
stuck above, except that the context contains an extra
equality assumption, which is exactly what we need to
make progress. *)
- (* e3 = true *)
Print beq_nat_true.
(* [beq_nat_true] will check if [beq_nat x y = true], and if so, it will conclude [x = y].
In this case, we have [beq_nat n 3 = true] in [Heqe3], so [beq_nat_true] can replace
that with [n = 3]. *)
apply beq_nat_true in Heqe3.
(* Now we can use [Heqe3] to replace [n] with [3] in the goal. *)
rewrite -> Heqe3.
(* [reflexivity] can solve this. *)
reflexivity.
- (* e3 = false *)
(* When we come to the second equality test in the body
of the function we are reasoning about, we can use
[eqn:] again in the same way, allow us to finish the
proof. *)
destruct (beq_nat n 5) eqn:Heqe5.
+ (* e5 = true *)
apply beq_nat_true in Heqe5.
rewrite -> Heqe5. reflexivity.
+ (* e5 = false *) inversion eq. Qed.
(** **** Exercise: 2 stars (destruct_eqn_practice) *)
Theorem bool_fn_applied_thrice :
forall (f : bool -> bool) (b : bool),
f (f (f b)) = f b.
Proof.
(* FILL IN HERE *) Admitted.
(** [] *)
(* ################################################################# *)
(** * Review *)
(** We've now seen many of Coq's most fundamental tactics. We'll
introduce a few more in the coming chapters, and later on we'll
see some more powerful _automation_ tactics that make Coq help us
with low-level details. But basically we've got what we need to
get work done.
Here are the ones we've seen:
- [intros]: move hypotheses/variables from goal to context
- [reflexivity]: finish the proof (when the goal looks like [e =
e])
- [apply]: prove goal using a hypothesis, lemma, or constructor
- [apply... in H]: apply a hypothesis, lemma, or constructor to
a hypothesis in the context (forward reasoning)
- [apply... with...]: explicitly specify values for variables
that cannot be determined by pattern matching
- [simpl]: simplify computations in the goal
- [simpl in H]: ... or a hypothesis
- [rewrite]: use an equality hypothesis (or lemma) to rewrite
the goal
- [rewrite ... in H]: ... or a hypothesis
- [symmetry]: changes a goal of the form [t=u] into [u=t]
- [symmetry in H]: changes a hypothesis of the form [t=u] into
[u=t]
- [unfold]: replace a defined constant by its right-hand side in
the goal
- [unfold... in H]: ... or a hypothesis
- [destruct... as...]: case analysis on values of inductively
defined types
- [destruct... eqn:...]: specify the name of an equation to be
added to the context, recording the result of the case
analysis
- [induction... as...]: induction on values of inductively
defined types
- [inversion]: reason by injectivity and distinctness of
constructors
- [assert (H: e)] (or [assert (e) as H]): introduce a "local
lemma" [e] and call it [H]
- [generalize dependent x]: move the variable [x] (and anything
else that depends on it) from the context back to an explicit
hypothesis in the goal formula *)
(* ################################################################# *)
(** * Additional Exercises *)
(** **** Exercise: 3 stars (beq_nat_sym) *)
Theorem beq_nat_sym : forall (n m : nat),
beq_nat n m = beq_nat m n.
Proof.
(* FILL IN HERE *) Admitted.
(** [] *)
(** **** Exercise: 3 stars, advanced, optional (beq_nat_sym_informal) *)
(** Give an informal proof of this lemma that corresponds to your
formal proof above:
Theorem: For any [nat]s [n] [m], [beq_nat n m = beq_nat m n].
Proof: *)
(* FILL IN HERE *)
(** [] *)
(** **** Exercise: 3 stars, optional (beq_nat_trans) *)
Theorem beq_nat_trans : forall n m p,
beq_nat n m = true ->
beq_nat m p = true ->
beq_nat n p = true.
Proof.
(* FILL IN HERE *) Admitted.
(** [] *)
(** **** Exercise: 3 stars, advanced (split_combine) *)
(** We proved, in an exercise above, that for all lists of pairs,
[combine] is the inverse of [split]. How would you formalize the
statement that [split] is the inverse of [combine]? When is this
property true?
Complete the definition of [split_combine_statement] below with a
property that states that [split] is the inverse of
[combine]. Then, prove that the property holds. (Be sure to leave
your induction hypothesis general by not doing [intros] on more
things than necessary. Hint: what property do you need of [l1]
and [l2] for [split] [combine l1 l2 = (l1,l2)] to be true?) *)
Definition split_combine_statement : Prop
(* ("[: Prop]" means that we are giving a name to a
logical proposition here.) *)
(* REPLACE THIS LINE WITH ":= _your_definition_ ." *). Admitted.
Theorem split_combine : split_combine_statement.
Proof.
(* FILL IN HERE *) Admitted.
(* Do not modify the following line: *)
Definition manual_grade_for_split_combine : option (prod nat string) := None.
(** [] *)
(** **** Exercise: 3 stars, advanced (filter_exercise) *)
(** This one is a bit challenging. Pay attention to the form of your
induction hypothesis. *)
Theorem filter_exercise : forall (X : Type) (test : X -> bool)
(x : X) (l lf : list X),
filter test l = x :: lf ->
test x = true.
Proof.
(* FILL IN HERE *) Admitted.
(** [] *)
(** **** Exercise: 4 stars, advanced, recommended (forall_exists_challenge) *)
(** Define two recursive [Fixpoints], [forallb] and [existsb]. The
first checks whether every element in a list satisfies a given
predicate:
forallb oddb [1;3;5;7;9] = true
forallb negb [false;false] = true
forallb evenb [0;2;4;5] = false
forallb (beq_nat 5) [] = true
The second checks whether there exists an element in the list that
satisfies a given predicate:
existsb (beq_nat 5) [0;2;3;6] = false
existsb (andb true) [true;true;false] = true
existsb oddb [1;0;0;0;0;3] = true
existsb evenb [] = false
Next, define a _nonrecursive_ version of [existsb] -- call it
[existsb'] -- using [forallb] and [negb].
Finally, prove a theorem [existsb_existsb'] stating that
[existsb'] and [existsb] have the same behavior. *)
(* FILL IN HERE *)
(* Do not modify the following line: *)
Definition manual_grade_for_forall_exists_challenge : option (prod nat string) := None.
(** [] *)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment