How to overload the "+" notation in Coq? - coq

I'm trying to overload the notation for +. The following doesn't work:
Definition my_add (n m :nat):= n + m.
Fail Notation "x + y":= (my_add x y) (at level 50, y at next level).
Fails with the message Notation "_ + _" is already defined at level 50 with arguments constr at level 50, constr at next level while it is now required to be at level 50 with arguments constr at next level, constr at next level.
Which suggests that I need to bind x at level 50.
Definition my_add (n m :nat):= n + m.
Fail Notation "x + y":= (my_add x y) (at level 50, x at level 50, y at next level).
Fail with The level of the leftmost non-terminal cannot be changed..
I'm sure I have defined this notation before, so perhaps this is a recent change to Coq, or am I forgetting something obvious?

Symbols in notations must have unique precedences and associativity. So for a preexisting notation, no annotation is necessary since it's already set:
Notation "x + y":= (my_add x y).
For some reason you can set associativity alone. You can also set both level and associativity. In any case, they have to match the preexisting values, if any.
Notation "x + y":= (my_add x y) (left associativity).
Notation "x + y":= (my_add x y) (at level 50, left associativity).
You can also use notation scopes in order to use the same symbol with different meanings, with various bells and whistles to control how they are set. See the manual.

Related

Overloading operators in Coq via typeclasses and notation scopes: Is there anything special about the '+' and '*' symbols?

I would like to create infix notations for (overloaded) operations. I apply the - to my knowledge - standard two-step approach in Coq:
Typeclass used for actual operator overloading (e.g. overload add
operation)
Notation scope used for definition of operator symbol
(e.g. infix notation '+')
This approach seems to work fine. E.g. overloading of the '-' symbol (which is used at least once in the predefined notation scope nat_scope) poses no problems. However, the '+' and '*' symbols (also used in the predefined notation scope nat_scope) lead to erros in certain circumstances. Is there anything special about the '+' and '*' symbols in Coq that has to be considered when adding them to a new notation scope?
Example
Let's model classical sets as predicates, i.e. as functions of type A->Prop:
Definition pred1 (a:nat) := a=1. (* pred1 corresponds to {1} *)
Definition pred2 (a:nat) := a=1 \/ a=2. (* pred2 corresponds to {1,2} *)
Union (addition) is modelled as the overloaded operation pred_add via the typeclass PredAdd and corresponding typeclass instances. For the sake of simplicity only the typeclass instance add_elem (addition of elements to sets) is provided:
Class PredAdd (X Y Z: Type) := {pred_add: X->Y->Z->Prop}.
Instance add_elem {A:Type}: PredAdd (A->Prop) (A) (A) := {
pred_add (P:A->Prop) (a:A) (x:A) := P x \/ x=a
}.
The infix notation '+' is used for the operation pred_add:
Declare Scope mypred_scope.
Notation "x + y" := (pred_add x y) (at level 50, left associativity): mypred_scope.
Open Scope mypred_scope.
Now, let's use the test case {1} + 2 = {1,2} to see what works and what does not work.
Operator overloading and infix notation '+' seem to work fine (at first glance):
Example ex1: (pred_add pred1 2) 1. unfold pred_add, pred1; simpl; auto. Qed.
Example ex2: forall (p1 p2:nat->Prop) (x:nat),
p1 = pred1 + 2 -> p2 = pred2 -> p1 x=p2 x.
unfold pred_add, pred1, pred2; intros; subst; auto.
Qed.
However, the application of notation '+' fails in certain cases.
E.g. in the following case:
Fail Example ex2: (pred1 + 2) 2.
we get the error message:
The command has indeed failed with message: The term "pred1" has type
"nat -> Prop" while it is expected to have type "Type".
Interestingly, the outcome seems to depend on the particular choice of the notation symbol.
The same example works fine with e.g. the symbol '-':
Notation "x - y" := (pred_add x y) (at level 50, left associativity): mypred_scope.
Example ex3: (pred1 - 2) 2. unfold pred_add, pred1; simpl; auto. Qed.
but fails with the notation symbol '*':
Notation "x * y" := (pred_add x y) (at level 40, left associativity): mypred_scope.
Fail Example ex4: (pred1 * 2) 2.
The command has indeed failed with message: The term "pred1" has type
"nat -> Prop" while it is expected to have type "Type".
(The symbols '-' and '*' may be a confusing choice for an add operation. But this lets us keep the example short and simple.)
Platform
Tested on Coq version: 8.15.2
+ and * are also overloaded as sum and product types in type_scope, which is automatically open on the right of :, taking precedence over the open mypred_scope. This is why the error messages say that a Type is expected. Hence on the right of : you have to reopen mypred_scope.
Delimit Scope mypred_scope with mypred.
Example ex2: (pred1 + 2)%mypred 2.

Define a function based on a relation in Coq

I'm working on a theory in which there is a relation C defined as
Parameter Entity: Set.
Parameter C : Entity -> Entity -> Entity -> Prop.
The relation C is a relation of composition of some entities. Instead of C z x y, I want to be able to write x o y = z. So I have two questions:
I think I should define a "function" (the word is perhaps not the right one) named fC that takes x and y and returns z. This way, I could use it in the Notation. But I don't know how to define this "function". Is it possible?
I find that I can use the command Notation to define an operator. Something like Notation "x o y" := fC x y.. Is this the good way to do it?
I tried Notation "x o y" := exists u, C u x y. but it didn't work. Is there a way to do what I want to do?
Unless your relation C has the property that, given x and y, there is a unique z such that C z x y, you cannot view it as representing a full-fledged function the way you suggest. This is why the notion of a relation is needed in that case.
As for defining a notation for the relation property, you can use:
Notation "x 'o y" := (exists u, C u x y) (at level 10).
Note the ' before the o to help the parser handle the notation and the parentheses after the := sign. The level can be changed to suit your parsing preferences.
If you define x 'o y as a proposition, you will lose the intuition of o being a binary operation on Entity (i.e x o y should have type Entity).
You may write some variation like
Notation "x 'o y '= z" := (unique (fun t => C t x y)) (at level 10).
Otherwise, If your relation satisfies:
Hypothesis C_fun: forall x y, {z : Entity | unique (fun t => C t x y) z}.
then you may define:
Notation "x 'o y" := (proj1_sig (C_fun x y)) (at level 10).
Check fun a b: Entity => a 'o b.
Otherwise (if you have only have a weaker version of C_fun, with existsinstead of sig) and accept to use classical logic and axioms), you may use the Epsilon operator
https://coq.inria.fr/distrib/current/stdlib/Coq.Logic.ClassicalEpsilon.html

Coq: About "%" and "mod" as a notation symbol

I'm trying to define a notation for modulo equivalence relation:
Inductive mod_equiv : nat -> nat -> nat -> Prop :=
| mod_intro_same : forall m n, mod_equiv m n n
| mod_intro_plus_l : forall m n1 n2, mod_equiv m n1 n2 -> mod_equiv m (m + n1) n2
| mod_intro_plus_r : forall m n1 n2, mod_equiv m n1 n2 -> mod_equiv m n1 (m + n2).
(* 1 *) Notation "x == y 'mod' z" := (mod_equiv z x y) (at level 70).
(* 2 *) Notation "x == y % z" := (mod_equiv z x y) (at level 70).
(* 3 *) Notation "x == y %% z" := (mod_equiv z x y) (at level 70).
All three notations are accepted by Coq. However, I can't use the notation to state a theorem in some cases:
(* 1 *)
Theorem mod_equiv_sym : forall (m n p : nat), n == p mod m -> p == n mod m.
(* Works fine as-is, but gives error if `Arith` is imported before:
Syntax error: 'mod' expected after [constr:operconstr level 200] (in [constr:operconstr]).
*)
(*************************************)
(* 2 *)
Theorem mod_equiv_sym : forall (m n p : nat), n == p % m -> p == n % m.
(* Gives the following error:
Syntax error: '%' expected after [constr:operconstr level 200] (in [constr:operconstr]).
*)
(*************************************)
(* 3 *)
Theorem mod_equiv_sym : forall (m n p : nat), n == p %% m -> p == n %% m.
(* Works just fine. *)
The notation mod is defined under both Coq.Init.Nat and Coq.Arith.PeanoNat at top level. Why is the new notation x == y 'mod' z fine in one environment but not in the other?
The notation % seems to conflict with the built-in % notation, yet the Coq parser gives almost the same error message as the mod case, and the message isn't very helpful in either case. Is this intended behavior? IMO, if the parser can't understand a notation inside such a trivial context, the notation shouldn't have been accepted in the first place.
Your first question has an easy answer. The initial state of Coq is (in part) determined by Coq.Init.Prelude, which (as of this answer) contains the line
Require Coq.Init.Nat.
This is to say, Coq.Init.Prelude isn't imported, only made available with Require. Notations are only active if the module containing them is imported. If the notation is declared local (Local Notation ...) then even importing the module doesn't activate the notation.
The second question is trickier and delves into how Coq parses notations. Let's start with an example that works. In Coq.Init.Notations (which is actually imported in Coq.Init.Prelude), the notation "x <= y < z" is reserved.
Reserved Notation "x <= y < z" (at level 70, y at next level).
In Coq.Init.Peano (which is also imported), a meaning is given to the notation. We won't really worry about that part, since we're mostly concerned with parsing.
To see what effect reserving a notation has, you can use the vernacular command Print Grammar constr.. This will display a long list of everything that goes into parsing a constr (a basic unit of Coq's grammar). The entry for this notation is found a ways down the list.
| "70" RIGHTA
[ SELF; "?="; NEXT
[...]
| SELF; "<="; NEXT; "<"; NEXT
[...]
| SELF; "="; NEXT ]
We see that the notation is right associative (RIGHTA)1 and lives at level 70. We also see that the three variables in the notation, x, y and z are parsed at level 70 (SELF), level 71 (NEXT) and level 71 (NEXT) respectively.2
During parsing, Coq starts at level 0 and looks at the next token. Until there's a token that should be parsed at the current level, the level is increased. So notations with lower levels take precedence over those with higher level. (This is conceptually how it works - it's probably optimized a bit).
When a complex notation is found, such as after "5 <= ", the parser remembers the grammar of that notation3: SELF; "<="; NEXT; "<"; NEXT. After "5 <=", we parse y at level 71, meaning that if nothing works at less than level 71, we stop trying to parse y and move on.
After that, the next token has to be "<", then we parse z at level 71 if it is.
The great thing about levels is that it allows interaction with other notations without needing parentheses. For example, in the code 1 * 2 < 3 + 4 <= 5 * 6, we don't need parentheses because * and + are declared at lower levels (40 and 50 respectively). So when we're parsing y (at level 71), we're able to parse all of 3 + 4 before moving on to <= z. Additionally, when we parse z, we can capture 5 * 6 because * parses at a lower level than the parsing level for z.
Alright, now that we understand that, we can figure out what's going on in your case.
When Arith (or Nat) are imported, mod becomes a notation. Specifically we have a left associative notation at level 40 whose grammar is SELF; "mod"; NEXT (use Print Grammar constr. to check). When you define your mod notation, the entry is right associative at level 70 with grammar SELF; "=="; constr:operconstr LEVEL "200"; "mod"; NEXT. The middle section just means that y is parsed at level 200 (as a constr - just like everything else we've talked about).
Thus, when parsing n == p mod m, we parse n == fine, then start parsing y at level 200. Since Arith's mod is only at level 40, that's how we'll parse p mod m. But then our x == y mod z notation is left hanging. We're at the end of the statement and mod z still hasn't been parsed.
Syntax error: 'mod' expected after [constr:operconstr level 200] (in [constr:operconstr]).
(does the error make more sense now?)
If you really want to use your mod notation while still using Arith's mod notation, you'll need to parse y at a lower level. Since x mod y is at level 40, we could make y be level 39 with
Notation "x == y 'mod' z" := (mod_equiv z x y) (at level 70, y at level 39).
Since arithmetic operations are at levels 40 and above, that means that we'd need to write 5 == (3 * 4) mod 7 using parentheses.
For your "%" notation, it's going to be difficult. "%" is normally used for scope delimitation (e.g. (x + y)%nat) and binds very tightly at level 1. You could make y parse at level 0, but that means that no notations at all can be used for y without parentheses. If that's acceptable, go ahead.
Since "%%" doesn't clash with anything (in the standard library), you're free to use it here at whatever level is convenient. You may want to make y parse at a lower level (y at next level is pretty standard), but it's not necessary.
Right associativity is the default. Apparently Coq's parser doesn't have a "no associativity" option, so even if you explicitly say "no associativity", it's still registered as right associative. This doesn't often cause trouble in practice.
This is why the notation is reserved with "y at the next level". By default, variables in the middle of the notation are parsed at level 200, which can be seen by reserving a similar notation like Reserved Notation "x ^ y ^ z" (at level 70). and using Print Grammar constr. to see the parsing levels. As we'll see, this is what happens with x == y mod z.
What happens if more than one notation starts with "5 <="? The one with the lower level will obviously be taken, but if they have the same level, it tries both and backtracks if it doesn't parse. However, if one notation finishes, it doesn't backtrack even if that choice causes trouble later. I'm not sure of the exact rules, but I suspect it depends on which notation is declared first.

rewrite works for integer but not for rationals for Coq aac_tactics

I was testing Coq rewrite tactics modulo associativity and commutativity (aac_tactics). The following example works for integer (Z), but generates an error when integers are replaced by rationals (Q).
Require Import ZArith.
Import Instances.Z.
Goal (forall x:Z, x + (-x) = 0)
-> forall a b c:Z, a + b + c + (-(c+a)) = b.
intros H ? ? ?.
aac_rewrite H.
When replacing Require Import ZArith. with Require Import QArith. etc., there is an error:
Error: Tactic failure: No matching occurence modulo AC found.
at aac_rewrite H.
There was a similar inconsistency issue between Z and Q, which turned out to be related to whether the Z/Q scope is open.
But I don't understand why aac rewrite didn't work here. What's the cause of the inconsistency, and how can one make it behave the same for Z and Q?
The AAC_tactics library needs theorems which express associativity, commutativity and so forth. Let's take Qplus_assoc which expresses the associativity law for the rational numbers.
Qplus_assoc
: forall x y z : Q, x + (y + z) == x + y + z
As you can see Qplus_assoc doesn't use =, it uses == to express the connection between the left-hand side and the right-hand side. Rationals are defined in the standard library as pairs of integers and positive numbers:
Record Q : Set := Qmake {Qnum : Z; Qden : positive}.
Since, e.g. 1/2 = 2/4, we need some other way of comparing the rationals for equality (other than = which is the notation for eq). For this reason the stdlib defines Qeq:
Definition Qeq (p q : Q) := (Qnum p * QDen q)%Z = (Qnum q * QDen p)%Z.
with notation
Infix "==" := Qeq (at level 70, no associativity) : Q_scope.
So, in case of rational numbers you might want to rewrite your example to something like this:
Require Import Coq.QArith.QArith.
Require Import AAC_tactics.AAC.
Require AAC_tactics.Instances.
Import AAC_tactics.Instances.Q.
Open Scope Q_scope.
Goal (forall x, x + (-x) == 0) ->
forall a b c, a + b + c + (-(c+a)) == b.
intros H ? ? ?.
aac_rewrite H.
Search (0 + ?x == ?x).
apply Qplus_0_l.
Qed.

coq: A left-recursive notation must have an explicit level

I have seen a Coq notation definition for "evaluates to" as follows:
Notation "e '||' n" := (aevalR e n) : type_scope.
I am trying to change the symbol '||' to something else as || is often times used for logical or. However, I always get an error
A left-recursive notation must have an explicit level
For example, this happens when I change '||' to:
'\|/', '\||/', '|_|', '|.|', '|v|', or '|_'.
Is there something special about || here? and how should I fix it to make these other notations work (if possible)?
If I am right, if you overload a notation, Coq uses the properties of the first definition. The notation _ '||' _ has already a level, so Coq uses this level for your definition.
But with new symbols, Coq cannot do that, and you have to specify the level:
Notation "e '|.|' n" := (aevalR e n) (at level 50) : type_scope.
For already defined notations, this is even stronger than what I wrote above. You cannot redefine the level of a notation. Try for example:
Notation "e '||' n" := (aevalR e n) (at level 20) : type_scope.