multiplication of two binary numbers - coq

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.

Related

Add ltac expression as hint to autorewrite?

I am trying to rewrite an environment using autorewrite. For simplicity we can assume it is a list (but in reality the type is more complex, has multiple cons constructors, and rewrite rules use equivalence rather than equality).
The normal form I want to get to is a concatenation of variables or singleton lists, i.e. x1 :: x2 :: xs ++ y :: ys to [x1] ++ [x2] ++ xs ++ [y] ++ ys. So far I had success rewriting other stuff by defining hints for autorewrite. However, the hint forall x xs, xs :: x = xs ++ [x] does not work, since [x] = x : [] which then can be rewritten to [x] ++ [] which gives an endless loop.
I don't have too much experience with writing custom Ltac expressions, but it seems like I would be able to define something like:
Ltac norm_cons :=
match goal with
| H: ?X : [] => idtac
| H: ?X : ?XS => (* actual rewrite *)
end.
This way we catch the [] in the first pattern and skip rewriting, and otherwise perform the rewrite. Maybe this needs a falltrough case, but this is not the point: how do I give (something like) this as a hint to autorewrite? I have tried to define the above as a separate tactic (where maybe I can define normalize as (norm_cons; autorewrite with blablabla).) but it then complains about none of the branches in the match matching to my goal. Does this do a recursive search? Or do I have to add this myself (i.e. matching ?XS ++ ?YS and recursively rewriting the lhs and rhs?)
It seems like you only want to rewrite lists with at least two elements. Perhaps you could rewrite with
forall x y xs, x :: y :: xs = [x] ++ y::xs

How to write boolean comparsion function in Coq

I'm trying to remove all integers that are greater than 7 from a list as follows
filter (fun n => n > 7).
However I get the following error
The term "n > 7" has type "Prop" while it is expected to have type "bool".
I am new to Coq, how can I fix it?
The problem is that #List.filter nat expects a function of type nat -> bool but you supplied a function of type nat -> Prop. Here, #List.filter nat is List.filter applied to the type argument nat. One difference between bool and Prop is that bool is decidable while Prop is not: there are propositions P such that neither P nor ~P are known; one can always determine whether something is true or false.
In order to resolve this situation, you need to write a function of type nat -> bool that returns true when applied to an argument greater than 7 and false otherwise. You can take advantage of the fact that the standard library defines boolean comparison functions over the natural numbers. I would also suggest reading the first volume of Software Foundations to familiarize yourself with Coq. It is more accessible and easy-going than some other prominent introductions (it was used in a program verification course at my university that presupposed little functional programming experience).
Here is a minimal example using only the builtin list type and notations:
Require Import Coq.Lists.List.
Import ListNotations.
Fixpoint filterb {A : Type} (f : A -> bool) (xs : list A) : list A :=
match xs with
| [] => []
| x :: xs => if f x then x :: filterb f xs else filterb f xs
end.
Fixpoint ltb (n m : nat) : bool :=
match n, m with
| n , 0 => false
| 0 , S m => true
| S n, S m => ltb n m
end.
Eval compute in (filterb (fun n => ltb 7 n) [5;6;7;8;9]).
(* = [8;9] *)

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.

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 to raise exception in Coq?(in match ... end)

I need to define recursive definitions, but I don't no yet how to do it correctly().
So I want to have partially defined function which will say when it need additional level of recursion to be written.
Context (qsigT: forall (A : Type) (P : forall a : A, Type), Type).
Context (qpr1: forall (A : Type) (P : forall a : A, Type), (#qsigT A P) -> A ).
Record Category :={
ty:>Type
}.
Context (uc:Category).
Context (mO mS: uc -> Type).
Definition ur0:= (#qsigT uc (fun x => mO (x) ) ).
Definition ur1:= (#qsigT ur0 (fun x => mS (qpr1 _ _ x) ) ).
Definition ur2:= (#qsigT ur1 (fun x => mS (qpr1 _ _ (qpr1 _ _ x)) ) ).
Definition ur3:= (#qsigT ur2 (fun x => mS (qpr1 _ _ (qpr1 _ _ (qpr1 _ _ x))) ) ).
(*and so on ...*)
Definition ur (n: nat) := (match n with
|0 => ur0
|1 => ur1
|2 => ur2
|_ => ur3
(*|_ => error*)
end).
1)Is it possibly to create exception on all natural numbers greater than 3? (during the pattern matching)
2)Is there a low level instrument which will not coerce me to use monades?
3)Is it possibly to define my function 'ur' on all natural numbers in Coq?
4)Is there some kind of combinator that will apply function 'pr1' n times?
5)Shall I create 5 different question (with one on the meta :-) ) or it is right way to ask?
1) Is it possibly to create exception on all natural numbers greater
than 3? (during the pattern matching)
No. Coq is a total language. The standard pattern for this is to make your function to return option T for type T, so you work in a partiality monad. Example:
Definition ur (n: nat) := (match n with
| 0 => Some ur0
| 1 => Some ur1
| 2 => Some ur2
| 3 => Some ur3
| _ => None
end).
2) Is there a low level instrument which will not coerce me to use monads?
See above. Whether you want to call it "monad" or not is up to you.
Another approach is to have a "default" value urF that you return when you "fail" the pattern matching. This approach is more convenient than the option type in a wide variety of situations.
3) Is it possibly to define my function 'ur' on all natural numbers in Coq?
I think so. Please provide the missing definitions and we may try.
4) Is there some kind of combinator that will apply function 'pr1' n times?
In principle yes, but it'd depend on the exact type you want for it.
5) Shall I create 5 different question (with one on the meta :-) ) or it is right way to ask?
Maybe. The biggest problem of this question is that the code is not
self-contained.