Exhaustiveness matching in proof objects for induction in Coq - coq

In Software Foundations, they discuss how to build you own proof objects for induction:
https://softwarefoundations.cis.upenn.edu/lf-current/IndPrinciples.html#nat_ind2
Definition nat_ind2 :
∀ (P : nat → Prop),
P 0 →
P 1 →
(∀ n : nat, P n → P (S(S n))) →
∀ n : nat , P n :=
fun P ⇒ fun P0 ⇒ fun P1 ⇒ fun PSS ⇒
fix f (n:nat) := match n with
0 ⇒ P0
| 1 ⇒ P1
| S (S n') ⇒ PSS n' (f n')
end.
I experimented with this definition by commenting out "| 1 ⇒ P1". Coq then gives an error: "Non exhaustive pattern-matching: no clause found for pattern 1." I was expecting an error, of course. But I don't know how Coq figures out there is an error.
I would like to know how Coq does the exhaustiveness matching to know that 1 needs to be checked, since 1 isn't part of the constructor for nat. Roughly what algorithm is Coq following?

I'm not sure it answers fully your question, but you may look at the way "extended" matching are dealt with (see for instance https://coq.inria.fr/distrib/current/refman/language/extensions/match.html#mult-match ).
Let's look at a simple example.
Definition f (n: nat): nat :=
match n with
2 => 2
| 1 => 23
| _ => S n
end.
With the following command, I can see how f is expressed through simple pattern matchings.
Unset Printing Matching.
Print f.
(*
f =
fun n : nat =>
match n with
| 0 => S n
| S n0 =>
match n0 with
| 0 => 23
| S n1 => match n1 with
| 0 => 2
| S _ => S n
end
end
end
: nat -> nat
*)
If you remove the clause for 1 from your example, it seems impossible to
convert your match into nested simple 0 | S _ matchings `.

Related

Definition by minimization in Coq

Assume P: nat -> T -> Prop is a proposition that for any given t: T,
either there exists a k: nat such that P holds for all numbers greater than or equal to k and no number less than k.
or P k t is false for all k : nat.
I want to define min_k : T -> nat + undef to be the minimum number k such that P k t holds, and undef otherwise.
Is that even possible? I tried to define something like
Definition halts (t : T) := exists k : nat, P k t.
Or maybe
Definition halts (t : T) := exists! k : nat, (~ P k t /\ P (S k) t).
and then use it like
Definition min_k (t : T) := match halts T with
| True => ??
| False => undef
end.
but I don't know how to go further from there.
Any ideas would be appreciated.
You can't match on a Prop. If you want to do case analysis then you need something in Type, typically bool or something like sumbool or sumor. In other words, you can do what you want as long as you have a pretty strong hypothesis.
Variable T : Type.
Variable P : nat -> T -> Prop.
Hypothesis PProperty : forall (t : T),
{k : nat | forall n, (k <= n -> P n t) /\ (n < k -> ~ P n t)}
+
{forall k, ~ P k t}.
Definition min_k (t : T) : option nat :=
match PProperty t with
| inleft kH => Some (proj1_sig kH)
| inright _ => None
end.
Crucially, this wouldn't have worked if PProperty was a Prop disjunction, i.e., if it was of the form _ \/ _ instead of the form _ + { _ }.
By the way, the idiomatic way of describing foo + undef in Coq is to use option foo, which is what I did above, but you can adapt it as you wish.
In addition to Ana's excellent answer, I think it is worth pointing out that option nat is essentially the same thing as {k : nat | ...} + {forall k, ~ P k t} if you erase the proofs of the latter type: in the first case (Some or inleft), you get a natural number out; in the second (None or inright) you get nothing at all.

Coq: Recursive definition of fibonacci is ill-formed

I am trying to define Fibonacci numbers using coq. This is my code:
Fixpoint fibonacci (n:nat) : nat :=
match n with
| O => 1
| S O => 1
| S (S n') => fibonacci (S n') + fibonacci n
end.
I met the error message:
Recursive definition of fibonacci is ill-formed. In environment
fibonacci : nat -> nat n : nat n0 : nat n' : nat Recursive call to
fibonacci has principal argument equal to "S n'" instead of one of
the following variables: "n0" "n'". Recursive definition is: "fun n :
nat => match n with | S (S n') => fibonacci (S n') + fibonacci n |
_ => 1 end".
I am wondering why this is wrong. Parenthetically, in the third clause of the match, I did not define the property of n' (e.g. n': nat), what would be the default of the property of n'?
Thanks in advance!
All arguments of a recursive call must be structurally decreasing, that is you must strip away one constructor symbol in the match. In your case the (S n') argument is in fact structurally decreasing, but Coq doesn't detect that (which is a bit silly) because you add another constructor S, which is not allowed. The second argument is wrong and should probably be n'. Besides one usually defines this such that fibonacci 0 = 0.
To get around the issue of (S n') one gives it a separate name with as as in:
Require Import List.
Fixpoint fibonacci (n:nat) : nat :=
match n with
| O => 0
| S O => 1
| S (S O) => 1
| S ((S n'') as n')=> fibonacci n' + fibonacci n''
end.
Eval cbv in map fibonacci (seq 0 10).

Can I avoid using Option A when I know that head cannot fail?

I am quite new in the world of the ATP, but definitely very motivated.
I am starting to deal with dependent types. I am involved in a project where I have defined the type for (finite and infinite) sequences.
Inductive sequence {X : Type} : Type :=
| FinSeq (x : list X)
| InfSeq (f : nat -> X).
Now I want to define the head of a non-empty sequence.
Lemma aux_hd : forall {A : Type} (l : list A),
0 < Datatypes.length l -> #hd_error A l = None -> False.
Proof. destruct l.
+ simpl. lia.
+ simpl. intros S. discriminate.
Qed.
Definition Hd {A : Type} (l : list A) : 0 < Datatypes.length l -> A :=
match (hd_error l) with
| Some a => (fun _ => a)
| None => fun pf => match (aux_hd l pf ??) with end
end.
Definition Head {A : Type} (s :sequence) (H : 0 << length s),
match s with
| FinSeq x => Hd x H
| InfSeq f => f 0 end.
My problem is in the definition of Hd: I don't know how to prove #hd_error A l = None, since we are already in such a match branch. I believe it should be really easy.
I have a similar problem in the last definition because I don't know how to transform H, for the particular case of the first match branch, where I know that length s = Datatypes.length x and, thus, 0 << length s -> 0 < Datatypes.length x.
Finally, I have omitted the details about << and length sequence, because I dont think it is relevant for the question but basically I have uplifted nat with an Inf to represent the length of the infinite sequences and << is the < for nat and num.
I have followed the course Software Foundations and I am currently studying more using "Certified Programming with Dependent Types" which is also really good.
Thanks in advance,
Miguel
When you match on something, all extra evidence must be passed as arguments to the match (this is the "convoy pattern" described in CPDT).
In Hd you want to remember that hd_error l = None, pass it as an argument. It's a little tricky because you have to explicitly annotate the match with a return clause (which in simpler cases was inferred for you):
Definition Hd {A : Type} (l : list A) : 0 < Datatypes.length l -> A :=
match (hd_error l) as X return hd_error l = X -> 0 < Datatypes.length l -> A with
| Some a => (fun _ _ => a)
| None => fun pf1 pf2 => match (aux_hd l pf2 pf1) with end
end eq_refl.
Similarly in Head, after pattern-matching on s you want to simplify 0 << length s; pass it as an argument:
Definition Head {A : Type} (s :sequence) (H : 0 << length s) :=
match s return (0 << length s) -> _ with
| FinSeq x => fun H => Hd x H
| InfSeq f => fun _ => f 0
end H.

Fixpoint with Prop inhabitant as argument

Consider the definition of find in the standard library, which as the type find: forall A : Type, (A -> bool) -> list A -> option A.
Of course, find has to return an option A and not an A because we don't know wether there is a "valid" element in the list.
Now, say I find this definition of find painful, because we have to deal with the option, even when we are sure that such an element exists in the list.
Hence, I'd like to define myFind which additionnaly takes a proof that there is such an element in the list. It would be something like:
Variable A: Type.
Fixpoint myFind
(f: A -> bool)
(l: list A)
(H: exists a, In a l /\ f a = true): A :=
...
If I am not mistaken, such a signature informally says: "Give me a function, a list, and a proof that you have a "valid" element in the list".
My question is: how can I use the hypothesis provided and define my fixpoint ?
What I have in mind is something like:
match l with
| nil => (* Use H to prove this case is not possible *)
| hd :: tl =>
if f hd
then hd
else
(* Use H and the fact that f hd = false
to prove H': exists a, In a tl /\ f a = true *)
myFind f tl H'
end.
An bonus point would be to know whether I can embbed a property about the result directly within the type, for instance in our case, a proof that the return value r is indeed such that f r = true.
We can implement this myFind function by structural recursion over the input list. In the case of empty list the False_rect inductive principle is our friend because it lets us switch from the logical world to the world of computations. In general we cannot destruct proofs of propositions if the type of the term under construction lives in Type, but if we have an inconsistency the system lets us.
We can handle the case of the non-empty input list by using the convoy pattern (there is a number of great answers on Stackoverflow explaining this pattern) and an auxiliary lemma find_not_head.
It might be useful to add that I use the convoy pattern twice in the implementation below: the one on the top level is used to let Coq know the input list is empty in the first match-branch -- observe that the type of H is different in both branches.
From Coq Require Import List.
Import ListNotations.
Set Implicit Arguments.
(* so we can write `f a` instead of `f a = true` *)
Coercion is_true : bool >-> Sortclass.
Section Find.
Variables (A : Type) (f : A -> bool).
(* auxiliary lemma *)
Fact find_not_head h l : f h = false ->
(exists a, In a (h :: l) /\ f a) ->
exists a, In a l /\ f a.
Proof. intros E [a [[contra | H] fa_true]]; [congruence | now exists a]. Qed.
Fixpoint myFind (l : list A) (H : exists a : A, In a l /\ f a) : {r : A | f r} :=
match l with
| [] => fun H : exists a : A, In a [] /\ f a =>
False_rect {r : A | f r}
match H with
| ex_intro _ _ (conj contra _) =>
match contra with end
end
| h :: l => fun H : exists a : A, In a (h :: l) /\ f a =>
(if f h as b return (f h = b -> {r : A | f r})
then fun Efh => exist _ h Efh
else fun Efh => myFind l (find_not_head Efh H)) eq_refl
end H.
End Find.
Here is a simplistic test:
From Coq Require Import Arith.
Section FindTest.
Notation l := [1; 2; 0; 9].
Notation f := (fun n => n =? 0).
Fact H : exists a, In a l /\ f a.
Proof. exists 0; intuition. Qed.
Compute myFind f l H.
(*
= exist (fun r : nat => f r) 0 eq_refl
: {r : nat | f r}
*)
End FindTest.
You can also use Program to help you construct the proof arguments interactively. You fill in as much as you can in the program body and leave _ blanks that you get to fill in later with proof tactics.
Require Import List Program.
Section Find.
Variable A : Type.
Variable test : A -> bool.
Program Fixpoint FIND l (H:exists a, test a = true /\ In a l) : {r | test r = true} :=
match l with
| [] => match (_:False) with end
| a::l' => if dec (test a) then a else FIND l' _
end.
Next Obligation.
firstorder; congruence.
Defined.
End Find.
Program is a little better at not forgetting information when you do case analysis (it knows the convoy pattern) but it is not perfect, hence the use of dec in the if statement.
(Notice how Coq was able to handle the first obligation, to construct a term of type False, all by itself!)

Dependent pattern matching in coq

The following code (which is of course not a complete proof) tries to do pattern matching on a dependent product:
Record fail : Set :=
mkFail {
i : nat ;
f : forall x, x < i -> nat
}.
Definition failomat : forall (m : nat) (f : forall x, x < m -> nat), nat.
Proof.
intros.
apply 0.
Qed.
Function fail_hard_omat fl : nat := failomat (i fl) (f fl).
Definition failhard fl : fail_hard_omat fl = 0.
refine ((fun fl =>
match fl with
| mkFail 0 _ => _
| mkFail (S n) _ => _
end) fl).
The error I get when trying to execute this is
Toplevel input, characters 0-125:
Error: Illegal application (Type Error):
The term "mkFail" of type
"forall i : nat, (forall x : nat, x < i -> nat) -> fail"
cannot be applied to the terms
"i" : "nat"
"f0" : "forall x : nat, x < i0 -> nat"
The 2nd term has type "forall x : nat, x < i0 -> nat"
which should be coercible to "forall x : nat, x < i -> nat".
It seems that the substitution somehow does not reach the inner type parameters.
After playing with the Program command I managed to build a refine that might suites you, but I don't understand everything I did. The main idea is to help Coq with the substitution by introducing intermediate equalities that will serve as brige within the substitution
refine ((fun fl =>
match fl as fl0 return (fl0 = fl -> fail_hard_omat fl0 = 0) with
| mkFail n bar =>
match n as n0 return (forall foo: (forall x:nat, x < n0 -> nat),
mkFail n0 foo = fl -> fail_hard_omat (mkFail n0 foo) = 0) with
| O => _
| S p => _
end bar
end (eq_refl fl) ) fl).
Anyway, I don't know what your purpose here is, but I advise never write dependent match "by hand" and rely on Coq's tactics. In your case, if you define your Definition failomat with Defined. instead of Qed, you will be able to unfold it and you won't need dependent matching.
Hope it helps,
V.
Note: both occurences of bar can be replaced by an underscore.
Another, slightly less involved, alternative is to use nat and fail's induction combinators.
Print nat_rect.
Print fail_rect.
Definition failhard : forall fl, fail_hard_omat fl = 0.
Proof.
refine (fail_rect _ _). (* Performs induction (projection) on fl. *)
refine (nat_rect _ _ _). (* Performs induction on fl's first component. *)
Show Proof.