How to exhaust the match with in coq using something like default or or clause? - coq

How can i write a switch state similar to this one (in rust), in coq?
In particular I'm curios how to merge branches in coq to produce same output, and exhaust the remaining branches via some default implementation.
type Voltages = u32; // in coq is similar to Definition Voltages := R.
type Timestamp = u32; // in coq is similar to Definition Timestamp := R.
const TD: Timestamp = 2; // dummy value cuz rust, in coq would be Variable TD : Timestamp.
enum Pin {
Ground(bool),
VoltageIn(bool),
Threshold,
Discharge,
Output,
Trigger,
Reset,
CtrlVoltage
}
impl Pin {
fn evaluate() -> bool { // dummy for some other functions and predicates
true
}
}
fn is_high(p: Pin) -> bool {
match p {
Pin::Ground(value) | Pin::VoltageIn(value) => value, // how to grab 2 options in one match in coq?
_ => Pin.evaluate() // how to exhaust the options in coq?
}
}

In coq you can separate several branches that bind the same variables by a pipe and use only one right-hand side value.
You can also use the underscore as a wildcard to catch all remaining cases.
Inductive t :=
| A (x : nat)
| B (x : nat) (y : bool)
| C (x : unit).
Definition foo (c : t) :=
match c with
| A x | B x _ => x
| _ => 0
end.

Related

multiplication of two binary numbers

I need to do the function that multiplicates two binary numbers represented by a list of booleans.
Here what I wrote :
Fixpoint brmul_r (x y res: list bool): list bool :=
match x,y,res with
|x,y,res-> if value x >0 then res else if (value x) mod 2 = 0 then brmul_r ((value x/2) (value y*2) (badd res y))
else brmul_r (x y*2 res)
end.
but it doesn't work.. what should I do?
Thank you in advance!
There are many problems with that code:
Syntax error: you want to use => instead of -> inside the match.
Actually, you are not taking advantage of the patter matching, so you can remove it entirely and start your definition with if ....
Then Coq complains that _ > _ has type Prop. You need to use the boolean version _ <? _ instead, and the same for the equality later: _ =? _ instead of _ = _.
In brmul_r ((value x/2) (value y*2) (badd res y)), the outer brackets are not supposed to be there; brmul_r is supposed to receive three arguments, not one argument, and similarly for brmul_r (x y*2 res)
What do you mean by value x/2? Is it value (x / 2) or (value x) / 2? The former does not type-check unless you redefined the _ / _ notation to work over lists of booleans. But the latter has type nat, and brmul_r expects something of type list bool, so it doesn't work either. A similar observation holds for value y*2.
This is not something Coq complains about yet (the problem in 5 would have to be solved first), but it will not be clear for Coq that your definition terminates, since you are using brmul_r to define brmul_r and feeding it non-structurally decreasing arguments. In fact, you even feed it increasing arguments in the final branch (I'm talking about brmul_r x y*2 res).
So what should one do? Convincing Coq that the function terminates is the real issue here, the rest is just confusion over syntax. Since this is a function on lists, it should recurse on the list structure, so it should have the following basic shape (I am assuming the context of Require Import List. Import ListNotations.):
Fixpoint brmul_r (xs ys : list bool) : list bool :=
match xs with
| [] => (* TODO *)
| hd :: tl => (* TODO *)
end.
Assuming the first element of the list is the least significant bit, it will be useful to match on it as well, so the structure becomes:
Fixpoint brmul_r (xs ys : list bool) : list bool :=
match xs with
| [] => (* TODO *)
| false :: tl => (* TODO *)
| true :: tl => (* TODO *)
end.
Now the goal is to express the product of false :: tl with ys when we already know the product of tl with ys. Translating to numbers (for intuition's sake), we want to find (2 * (value tl)) * (value ys) when we already know how to compute (value tl) * (value ys). Putting it like this, it becomes clear that we just need to duplicate the result of the latter. Going back to our list representation, we observe that duplicating corresponds to preppending false, so we can update our definition as follows:
Fixpoint brmul_r (xs ys : list bool) : list bool :=
match xs with
| [] => (* TODO *)
| false :: tl => false :: brmul_r tl ys
| true :: tl => (* TODO *)
end.
Now you can use the same reasoning to complete the function.
For the future:
Please include the necessary context. In this case it would be the modules you imported and the custom defined functions such as value.
It might be useful to follow a Coq tutorial to help with all the syntax issues and with the intuitions behind recursive and functional programming. Software Foundations is very good. There are also others.
There is now a dedicated Stack Exchange site for Proof Assistant-related questions.

Retrieving constraints from GADT to ensure exhaustion of pattern matching in Coq

Let's define two helper types:
Inductive AB : Set := A | B.
Inductive XY : Set := X | Y.
Then two other types that depend on XY and AB
Inductive Wrapped : AB -> XY -> Set :=
| W : forall (ab : AB) (xy : XY), Wrapped ab xy
| WW : forall (ab : AB), Wrapped ab (match ab with A => X | B => Y end)
.
Inductive Wrapper : XY -> Set :=
WrapW : forall (xy : XY), Wrapped A xy -> Wrapper xy.
Note the WW constructor – it can only be value of types Wrapped A X and Wrapped B Y.
Now I would like to pattern match on Wrapper Y:
Definition test (wr : Wrapper Y): nat :=
match wr with
| WrapW Y w =>
match w with
| W A Y => 27
end
end.
but I get error
Error: Non exhaustive pattern-matching: no clause found for pattern WW _
Why does it happen? Wrapper forces contained Wrapped to be A version, the type signature forces Y and WW constructor forbids being A and Y simultaneously. I don't understand why this case is being even considered, while I am forced to check it which seems to be impossible.
How to workaround this situation?
Let's simplify:
Inductive MyTy : Set -> Type :=
MkMyTy : forall (A : Set), A -> MyTy A.
Definition extract (m : MyTy nat) : nat :=
match m with MkMyTy _ x => S x end.
This fails:
The term "x" has type "S" while it is expected to have type "nat".
wat.
This is because I said
Inductive MyTy : Set -> Type
This made the first argument to MyTy an index of MyTy, as opposed to a parameter. An inductive type with a parameter may look like this:
Inductive list (A : Type) : Type :=
| nil : list A
| cons : A -> list A -> list A.
Parameters are named on the left of the :, and are not forall-d in the definition of each constructor. (They are still present in the constructors' types outside of the definition: cons : forall (A : Type), A -> list A -> list A.) If I make the Set a parameter of MyTy, then extract can be defined:
Inductive MyTy (A : Set) : Type :=
MkMyTy : A -> MyTy A.
Definition extract (m : MyTy nat) : nat :=
match m with MkMyTy _ x => S x end.
The reason for this is that, on the inside, a match ignores anything you know about the indices of the scrutinee from the outside. (Or, rather, the underlying match expression in Gallina ignores the indices. When you write a match in the source code, Coq tries to convert it into the primitive form while incorporating information from the indices, but it often fails.) The fact that m : MyTy nat in the first version of extract simply did not matter. Instead, the match gave me S : Set (the name was automatically chosen by Coq) and x : S, as per the constructor MkMyTy, with no mention of nat. Meanwhile, because MyTy has a parameter in the second version, I actually get x : nat. The _ is really a placeholder this time; it is mandatory to write it as _, because there's nothing to match, and you can Set Asymmetric Patterns to make it disappear.
The reason we distinguish between parameters and indices is because parameters have a lot of restrictions—most notably, if I is an inductive type with parameters, then the parameters must appear as variables in the return type of each constructor:
Inductive F (A : Set) : Set := MkF : list A -> F (list A).
(* ^--------^ BAD: must appear as F A *)
In your problem, we should make parameters where we can. E.g. the match wr with Wrap Y w => _ end bit is wrong, because the XY argument to Wrapper is an index, so the fact that wr : Wrapper Y is ignored; you would need to handle the Wrap X w case too. Coq hasn't gotten around to telling you that.
Inductive Wrapped (ab : AB) : XY -> Set :=
| W : forall (xy : XY), Wrapped ab xy
| WW : Wrapped ab (match ab with A => X | B => Y end).
Inductive Wrapper (xy : XY) : Set := WrapW : Wrapped A xy -> Wrapper xy.
And now your test compiles (almost):
Definition test (wr : Wrapper Y): nat :=
match wr with
| WrapW _ w => (* mandatory _ *)
match w with
| W _ Y => 27 (* mandatory _ *)
end
end.
because having the parameters gives Coq enough information for its match-elaboration to use information from Wrapped's index. If you issue Print test., you can see that there's a bit of hoop-jumping to pass information about the index Y through the primitive matchs which would otherwise ignore it. See the reference manual for more information.
The solution turned out to be simple but tricky:
Definition test (wr : Wrapper Y): nat.
refine (match wr with
| WrapW Y w =>
match w in Wrapped ab xy return ab = A -> xy = Y -> nat with
| W A Y => fun _ _ => 27
| _ => fun _ _ => _
end eq_refl eq_refl
end);
[ | |destruct a]; congruence.
Defined.
The issue was that Coq didn't infer some necessary invariants to realize that WW case is ridiculous. I had to explicitly give it a proof for it.
In this solution I changed match to return a function that takes two proofs and brings them to the context of our actual result:
ab is apparently A
xy is apparently Y
I have covered real cases ignoring these assumptions, and I deferred "bad" cases to be proven false later which turned to be trivial. I was forced to pass the eq_refls manually, but it worked and does not look that bad.

How can I match on a specific value in Coq?

I'm trying to implement a function that simply counts the number of occurrences of some nat in a bag (just a synonym for a list).
This is what I want to do, but it doesn't work:
Require Import Coq.Lists.List.
Import ListNotations.
Definition bag := list nat.
Fixpoint count (v:nat) (s:bag) : nat :=
match s with
| nil => O
| v :: t => S (count v t)
| _ :: t => count v t
end.
Coq says that the final clause is redundant, i.e., it just treats v as a name for the head instead of the specific v that is passed to the call of count. Is there any way to pattern match on values passed as function arguments? If not, how should I instead write the function?
I got this to work:
Fixpoint count (v:nat) (s:bag) : nat :=
match s with
| nil => O
| h :: t => if (beq_nat v h) then S (count v t) else count v t
end.
But I don't like it. I'd rather pattern match if possible.
Pattern matching is a different construction from equality, meant to discriminate data encoded in form of "inductives", as standard in functional programming.
In particular, pattern matching falls short in many cases, such as when you need potentially infinite patterns.
That being said, a more sensible type for count is the one available in the math-comp library:
count : forall T : Type, pred T -> seq T -> nat
Fixpoint count s := if s is x :: s' then a x + count s' else 0.
You can then build your function as count (pred1 x) where pred1 : forall T : eqType, T -> pred T , that is to say, the unary equality predicate for a fixed element of a type with decidable (computable) equality; pred1 x y <-> x = y.
I found in another exercise that it's OK to open up a match clause on the output of a function. In that case, it was "evenb" from "Basics". In this case, try "eqb".
Well, as v doesn't work in the match, I thought that maybe I could ask whether the head of the list was equal to v. And yes, it worked. This is the code:
Fixpoint count (v : nat) (s : bag) : nat :=
match s with
| nil => 0
| x :: t =>
match x =? v with
| true => S ( count v t )
| false => count v t
end
end.

How do I check for convertibility in a tactic producing terms?

Suppose I have the following tactic to check if a term is the literal zero:
Ltac isZero x :=
match x with
| O => constr:true
| _ => constr:false
end.
Goal Set.
let isz := isZero O in pose isz.
(* adds true to the context *)
Now imagine that I want the tactic to accept a bit more; maybe any term that is convertible with zero. If this was a tactic acting on the goal, I would do
Ltac isZero x :=
match x with
| ?v => unify v 0; constr:true
| _ => constr:false
end.
but this fails for a tactic producing terms:
Error: Value is a term. Expected a tactic.
How can I check for convertibility in a tactic producing terms? In this specific example reducing x or computing it (let xx := eval compute in x) may work, but in more complex example the cost of computing could be prohibitive, especially as I would need to reduce the two terms of the comparison.
PS: For reference, the unsimplified issue is that I'm trying to efficiently lookup a key probably matching a value in an FMap built by sequences of calls to add, and the tactic looks like
Ltac find_key value :=
match fmap with
| add ?k value _ => constr:(Some k)
| add _ _ ?m => find_key value m
| _ => constr:None
end
With this implementation, if instead of value the map contains a term convertible to value but not syntactically equal to it, the tactic will incorrectly return None.
You can try to construct a term that triggers the conversion check; for instance:
Goal 2 + 2 = 4.
match goal with
| |- ?a = ?b =>
let e := constr:(eq_refl a : a = b) in
idtac "equal"
| |- _ => idtac "not equal"
end.
Normally, this prints "equal". However, if you replace 4 by, say, 3 in the goal above, the inner branch fails, printing "not equal".

Indicator function and semirings in COQ

I'm quite new with Coq, and I'm trying to define a "generic" indicator function, like this :
Function indicator (x : nat) : bool :=
match x with
| O => false
| _ => true
end.
This one works well.
My problem is that I want an indicator function that returns false for the identity element of any semiring (for which I have a personal definition), not just for the natural number zero, like this :
Function indicator `(S : Semiring) (x : K) : bool :=
match x with
| ident => false
| _ => true
end.
where K is defined in the semiring S as the set and ident is defined in the semiring Sas the identity element.
This one doesn't work. I got the error:
This clause is redundant
with the last line of the match underlined. However, I don't think the error really comes from here. I read that it may come from the line
| ident => false
because ident is a variable, but I don't have more clues.
nat is an inductive type, created from two constructors:
Inductive nat: Set :=
| O : nat
| S : nat -> nat
.
This means that any inhabitant of the nat type is always built by a combination of these 2 constructors.
You can "inspect" this construction by pattern matching, like you did in the first indicator definition.
In the second case, your type K is a type variable (you don't want to have a fix type like nat), so you didn't explain how to build elements of K. Then, when you pattern match, the ident your wrote is just a binder, any name would have had the same effect (and _ too). It has no link to the indent of your semiring. Coq said that the clause is redundant because ident already captured any element of type K, so the _ case is never called.
If you want to write such a function for any type K, you will have to provide a way to compare elements of K (something of the type K -> K -> bool) and use it in your indicator function. I'm not sure about the syntax but you'll have something link:
Record SemiRing : Type := mkSemiRing {
K: Type;
ident : K;
compare : K -> K -> bool;
(* you might need the property that:
forall x y, compare x y = true -> x = y
*)
op1 : K -> K -> K;
op2 : K -> K -> K
(* and all the laws of semiring... *)
}.
Definition indicator (ring: SemiRing) (x: K ring) : bool :=
if compare ring x (ident ring) then true else false.