is coq match statement exhaustive? - coq

If i have a snippet similar to this one:
Inductive Q : Set :=
| NULL : Q
| CELL : nat -> Q -> Q -> Q
.
Definition someFunc (q: Q) :=
match q with
| NULL => True
| CELL 0 -> q1 -> q2 => True
| CELL z -> q1 -> q2 => (someFunc q1) || (someFunc q2)
end.
Will the case where q is 0 -> Q -> Q -> Q exhaust the match and finish the function execution, or will it drop down the next branch and destructure 0 as z?

The title of you question is not representative of the mistakes you made in your original question. You think you have a problem with exhaustive pattern-matching (you don't), while you have a mere problem of syntax and basic typing.
You managed to define an type of trees (called Q) with two constructors. That part is good.
You attempted to define a function, which by the look of it, is a recursive function. When defining a recursive function, you should use the keyword Fixpoint.
When writing a pattern in a pattern match construct, you have to respect the syntax for function application. So what you wrote Cell 0 -> q1 -> q2 should probably be written Cell 0 q1 q2.
The values returned in different branches of the pattern-match construct are in different type: True has type Prop, while an expression of the form (someFunc q1) || (someFunc q2) has type bool. These are two different types. There are two different notions of or connectives for these two types. One is written || the other one (which you should have used) is written \/.
So here is an example of code that is similar to yours, but does not suffer with syntax or typing problems.
Inductive Q : Set :=
| NULL : Q
| CELL : nat -> Q -> Q -> Q
.
Fixpoint someFunc (q: Q) :=
match q with
| NULL => True
| CELL 0 q1 q2 => True
| CELL z q1 q2 => (someFunc q1) \/ (someFunc q2)
end.
Maybe reading a few more examples of existing Coq code would help you get a better feeling of the syntax. The supplementary material of the Coq'Art book provides a few of these examples (in particular, you can look at the material for chapter 1 and chapter 6).

Related

Good way of testing a class in Coq

Is there a good way to test the implementation of a class in Coq ?
For example, if I have the following very simple Class:
Theorem chekc_modulo (c: nat): {c mod 2 = 0} + {c mod 2 <> 0} .
Admitted.
Definition update(n: nat):= add n one.
Class test :={
f: R -> nat;
g: R -> nat;
counting: nat;
init: counting = zero /\ f 0 = 0 /\ g 0 = 0;
output: forall t, t >= 0 ->
match chekc_modulo counting with
|left _ => f t = 1 /\ g t = 0 /\ update counting
|right _ => g t = 1 /\ g t = 0 /\ update counting
end
}.
I would like to find a way to test this class, so basically to check that f and g have the required values after processing the output.
What I did so far: I manually implemented f and g by giving them the values I expect they will have at a given t, after processing in output. And now I try to create an instance of the Class test to see what happens with the output.
I am a bit stuck because i do not see how to get the actual output and therefore how to check that the implementation is actually correct.
Does anyone have a tip ? In general, is there a better way to test code in Coq, especially Classes ?
EDIT:
In my testing strategy, I have defined the expected behavior of f and g:
Definition f': nat -> nat :=
fun t =>
match chekc_modulo t with
|left _ => 1
|right _ => 0
end.
Definition g': nat -> nat :=
fun t =>
match chekc_modulo t with
|left _ => 0
|right _ => 1
end.
So the next step, would be to check that this behavior is indeed the same as what happens after output is processed.
For testing Coq code, you might find the QuickChick plugin useful. It allows you to write properties that your definitions should satisfy, and generates random test cases to check if they hold. In principle, it should work fine with type classes as well.
However, given your code snippet, I have the impression that there is some misunderstanding about what classes in Coq are. For instance, the assertion counting = counting + 1 suggests that you are trying to update the value of counting somehow. In Coq, it is not possible to update the value of a variable: the assertion counting = counting + 1 means that the number counting equals its successor, which is impossible.
I don't know if this helps, but classes in Coq are closer to type classes in Haskell than to classes in object-oriented languages such as Java, and an "instance" of a class is more similar to a class that implements a Java interface than an object that is an instance of a class.
Perhaps we could provide more help if you gave us more context about what you are trying to do.

How does one do an else statement in Coq's functional programming language?

I am trying to count the # of occurrences of an element v in a natlist/bag in Coq. I tried:
Fixpoint count (v:nat) (s:bag) : nat :=
match s with
| nil => 0
| h :: tl => match h with
| v => 1 + (count v tl)
end
end.
however my proof doesn't work:
Example test_count1: count 1 [1;2;3;1;4;1] = 3.
Proof. simpl. reflexivity. Qed.
Why doesn't the first piece of code work? What is it doing when v isn't matched?
I also tried:
Fixpoint count (v:nat) (s:bag) : nat :=
match s with
| nil => 0
| h :: tl => match h with
| v => 1 + (count v tl)
| _ => count v tl
end
end.
but that also gives an error in Coq and I can't even run it.
Functional programming is sort of new to me so I don't know how to actually express this in Coq. I really just want to say if h matches v then do a +1 and recurse else only recurse (i.e. add zero I guess).
Is there a simple way to express this in Coq's functional programming language?
The reason that I ask is because it feels to me that the match thing is very similar to an if else statement in "normal" Python programming. So either I am missing the point of functional programming or something. That is the main issue I am concerned I guess, implicitly.
(this is similar to Daniel's answer, but I had already written most of it)
Your problem is that in this code:
match h with
| v => 1 + (count v tl)
end
matching with v binds a new variable v. To test if h is equal to v, you'll have to use some decision procedure for testing equality of natural numbers.
For example, you could use Nat.eqb, which takes two natural numbers and returns a bool indicating whether they're equal.
Require Import Nat.
Fixpoint count (v:nat) (s:bag) : nat :=
match s with
| nil => 0
| h :: tl => if (eqb h v) then (1 + count v t1) else (count v t1)
end.
Why can't we simply match on the term we want? Pattern matching always matches on constructors of the type. In this piece of code, the outer match statement matches with nil and h :: t1 (which is a notation for cons h t1 or something similar, depending on the precise definition of bag). In a match statement like
match n with
| 0 => (* something *)
| S n => (* something else *)
end.
we match on the constructors for nat: 0 and S _.
In your original code, you try to match on v, which isn't a constructor, so Coq simply binds a new variable and calls it v.
The match statement you tried to write actually just shadows the v variable with a new variable also called v which contains just a copy of h.
In order to test whether two natural numbers are equal, you can use Nat.eqb which returns a bool value which you can then match against:
Require Import Arith.
Fixpoint count (v:nat) (s:bag) : nat :=
match s with
| nil => 0
| h :: tl => match Nat.eqb v h with
| true => 1 + (count v tl)
| false => count v tl
end
end.
As it happens, for matching of bool values with true or false, Coq also provides syntactic sugar in the form of a functional if/else construct (which is much like the ternary ?: operator from C or C++ if you're familiar with either of those):
Require Import Arith.
Fixpoint count (v:nat) (s:bag) : nat :=
match s with
| nil => 0
| h :: tl => if Nat.eqb v h then
1 + (count v tl)
else
count v tl
end.
(Actually, it happens that if works with any inductive type with exactly two constructors: then the first constructor goes to the if branch and the second constructor goes to the else branch. However, the list type has nil as its first constructor and cons as its second constructor: so even though you could technically write an if statement taking in a list to test for emptiness or nonemptiness, it would end up reversed from the way you would probably expect it to work.)
In general, however, for a generic type there won't necessarily be a way to decide whether two members of that type are equal or not, as there was Nat.eqb in the case of nat. Therefore, if you wanted to write a generalization of count which could work for more general types, you would have to take in an argument specifying the equality decision procedure.

Using polymorphic functions in definitions

Following my question here, I have several functions with different types of arguments which I defined the Inductive type formula on them. Is there anyway to use Inductive formula in compute_formula. I am doing this to make proving easier by decreasing the number of constructors that I have to handle in proofs. Thank you.
Fixpoint add (n:type1) (m:type2): type3 :=
match n with
(*body for add*)
end.
Fixpoint mul (n:type1) (m:type4): type5 :=
match n with
(*body for mul*)
end.
Inductive formula : Type :=
| Formula {A B}: type1-> A -> (type1->A->B) -> formula.
(* How should I write this *)
Definition compute_formula {A B} (f: formula) (extraArg:A) : B :=
match f with
|Formula {A B} part1 part2 part3=>
if (A isof type2 && B isof type3) then add part1 part2+extraArg
if (A isof type4 && B isof type5) then mul part1 part2+extraArg
end.
What do you want the output type of compute_formula to be? The way the signature is written, the function would have to be able to compute an element of B no matter what B is. Since this is obviously impossible (what if B is Empty?), I'll show you a different approach.
The idea is to use the formula to get the output type.
Definition output_type (f: formula) :=
match f with
| #Formula _ B _ _ _ => B
end.
Then we can define compute_formula as
Definition compute_formula (f: formula): output_type f :=
match f with
| #Formula _ _ t a func => func t a
end.
A few other things. I'm not sure what you mean with the extraArg part. If you're more specific about what that means I might be able to help you. Also, there isn't (at least outside of tactics) a way to do what you want with A isof type2.

Coq: How to refer to the types generated by a specific constructor?

For example, if I define a function from nat to nat, it would be
Definition plusfive(a:nat): nat := a + 5.
However, I would like to define a function whose arguments are nats constructed using the "S" constructor (i.e. nonzero) is that possible to directly specify as a type? something like
Definition plusfive(a: nat.S): nat := a + 5.
(I know that for this case I could also add an argument with a proof that a is nonzero, but I am wondering if it is possible to directly name the type based on the 'S' constructor).
Functions have to be complete, so you will have to use some subtype instead of nat, or add an argument that reduces input space, for instance (H: a<>0)
Definition plusfive(a:nat) (H:a<>0) :=
match a as e return a=e -> _ with
| S _ => fun _ => a + 5
| _ => fun H0 => match (H H0) with end
end eq_refl.
However, these kinds of tricks have been discovered to be very cumbersome to work with in large developments, and often one instead uses complete functions on the base type that return dummy values for bad input values, and prove that the function is called with correct arguments separately from the function definition. See for example how division is defined in the standard library.
Require Import Nat.
Print div.
div =
fun x y : nat => match y with
| 0 => y
| S y' => fst (divmod x y' 0 y')
end
: nat -> nat -> nat
So Compute (div 1 0). gives you 0.
The nice thing is that you can use div in expressions directly, without having to interleave proofs that the denominator is non-zero. Proving that an expression is correct is then done after it has been defined, not at the same time.

How does the discriminate tactic work?

I was curious about how the discriminate tactic works behind the curtain. Therefore I did some experiments.
First a simple Inductive definition:
Inductive AB:=A|B.
Then a simple lemma which can be proved by the discriminate tactic:
Lemma l1: A=B -> False.
intro.
discriminate.
Defined.
Let's see what the proof looks like:
Print l1.
l1 =
fun H : A = B =>
(fun H0 : False => False_ind False H0)
(eq_ind A
(fun e : AB => match e with
| A => True
| B => False
end) I B H)
: A = B -> False
This looks rather complicated and I do not understand what is happening here. Therefore I tried to prove the same lemma more explicitly:
Lemma l2: A=B -> False.
apply (fun e:(A=B) => match e with end).
Defined.
Let's again see what Coq has made with this:
Print l2.
l2 =
fun e : A = B =>
match
e as e0 in (_ = a)
return
(match a as x return (A = x -> Type) with
| A => fun _ : A = A => IDProp
| B => fun _ : A = B => False
end e0)
with
| eq_refl => idProp
end
: A = B -> False
Now I am totally confused. This is still more complicated.
Can anyone explain what is going on here?
Let's go over this l1 term and describe every part of it.
l1 : A = B -> False
l1 is an implication, hence by Curry-Howard correspondence it's an abstraction (function):
fun H : A = B =>
Now we need to construct the body of our abstraction, which must have type False. The discriminate tactic chooses to implement the body as an application f x, where f = fun H0 : False => False_ind False H0 and it's just a wrapper around the induction principle for False, which says that if you have a proof of False, you can get a proof of any proposition you want (False_ind : forall P : Prop, False -> P):
(fun H0 : False => False_ind False H0)
(eq_ind A
(fun e : AB => match e with
| A => True
| B => False
end) I B H)
If we perform one step of beta-reduction, we'll simplify the above into
False_ind False
(eq_ind A
(fun e : AB => match e with
| A => True
| B => False
end) I B H)
The first argument to False_ind is the type of the term we are building. If you were to prove A = B -> True, it would have been False_ind True (eq_ind A ...).
By the way, it's easy to see that we can simplify our body further - for False_ind to work it needs to be provided with a proof of False, but that's exactly what we are trying to construct here! Thus, we can get rid of False_ind completely, getting the following:
eq_ind A
(fun e : AB => match e with
| A => True
| B => False
end) I B H
eq_ind is the induction principle for equality, saying that equals can be substituted for equals:
eq_ind : forall (A : Type) (x : A) (P : A -> Prop),
P x -> forall y : A, x = y -> P y
In other words, if one has a proof of P x, then for all y equal to x, P y holds.
Now, let's create step-by-step a proof of False using eq_ind (in the end we should obtain the eq_ind A (fun e : AB ...) term).
We start, of course, with eq_ind, then we apply it to some x - let's use A for that purpose. Next, we need the predicate P. One important thing to keep in mind while writing P down is that we must be able to prove P x. This goal is easy to achieve - we are going to use the True proposition, which has a trivial proof. Another thing to remember is the proposition we are trying to prove (False) - we should be returning it if the input parameter is not A.
With all the above the predicate almost writes itself:
fun x : AB => match x with
| A => True
| B => False
end
We have the first two arguments for eq_ind and we need three more: the proof for the branch where x is A, which is the proof of True, i.e. I. Some y, which will lead us to the proposition we want to get proof of, i.e. B, and a proof that A = B, which is called H at the very beginning of this answer. Stacking these upon each other we get
eq_ind A
(fun x : AB => match x with
| A => True
| B => False
end)
I
B
H
And this is exactly what discriminate gave us (modulo some wrapping).
Another answer focuses on the discriminate part, I will focus on the manual proof. You tried:
Lemma l2: A=B -> False.
apply (fun e:(A=B) => match e with end).
Defined.
What should be noted and makes me often uncomfortable using Coq is that Coq accepts ill-defined definitions that it internally rewrites into well-typed terms. This allows to be less verbose, since Coq adds itself some parts. But on the other hand, Coq manipulates a different term than the one we entered.
This is the case for your proof. Naturally, the pattern-matching on e should involve the constructor eq_refl which is the single constructor of the eq type. Here, Coq detects that the equality is not inhabited and thus understands how to modify your code, but what you entered is not a proper pattern-matching.
Two ingredients can help understand what is going on here:
the definition of eq
the full pattern-matching syntax, with as, in and return terms
First, we can look at the definition of eq.
Inductive eq {A : Type} (x : A) : A -> Prop := eq_refl : x = x.
Note that this definition is different from the one that seems more natural (in any case, more symmetric).
Inductive eq {A : Type} : A -> A -> Prop := eq_refl : forall (x:A), x = x.
This is really important that eq is defined with the first definition and not the second. In particular, for our problem, what is important is that, in x = y, x is a parameter while y is an index. That is to say, x is constant across all the constructors while y can be different in each constructor. You have the same difference with the type Vector.t. The type of the elements of a vector will not change if you add an element, that's why it is implemented as a parameter. Its size, however, can change, that's why it is implemented as an index.
Now, let us look at the extended pattern-matching syntax. I give here a very brief explanation of what I have understood. Do not hesitate to look at the reference manual for safer information. The return clause can help specify a return type that will be different for each branch. That clause can use the variables defined in the as and in clauses of the pattern-matching, which binds respectively the matched term and the type indices. The return clause will both be interpreted in the context of each branch, substituting the variables of as and in using this context, to type-check the branches one by one, and be used to type the match from an external point of view.
Here is a contrived example with an as clause:
Definition test n :=
match n as n0 return (match n0 with | 0 => nat | S _ => bool end) with
| 0 => 17
| _ => true
end.
Depending on the value of n, we are not returning the same type. The type of test is forall n : nat, match n with | 0 => nat | S _ => bool end. But when Coq can decide in which case of the match we are, it can simplify the type. For example:
Definition test2 n : bool := test (S n).
Here, Coq knows that, whatever is n, S n given to test will result as something of type bool.
For equality, we can do something similar, this time using the in clause.
Definition test3 (e:A=B) : False :=
match e in (_ = c) return (match c with | B => False | _ => True end) with
| eq_refl => I
end.
What's going on here ? Essentially, Coq type-checks separately the branches of the match and the match itself. In the only branch eq_refl, c is equal to A (because of the definition of eq_refl which instantiates the index with the same value as the parameter), therefore we claimed we returned some value of type True, here I. But when seen from an external point of view, c is equal to B (because e is of type A=B), and this time the return clause claims that the match returns some value of type False. We use here the capability of Coq to simplify pattern-matching in types that we have just seen with test2. Note that we used True in the other cases than B, but we don't need True in particular. We only need some inhabited type, such that we can return something in the eq_refl branch.
Going back to the strange term produced by Coq, the method used by Coq does something similar, but on this example, certainly more complicated. In particular, Coq often uses types IDProp inhabited by idProp when it needs useless types and terms. They correspond to True and I used just above.
Finally, I give the link of a discussion on coq-club that really helped me understand how extended pattern-matching is typed in Coq.