How do I use value of variable in Maple - maple

How do I get Maple to give the value of a variable in the RHS of an expression, rather than treat it as a variable in an expression. In the following code I want a list of three functions of x which are quadratics with different offsets, but it's not what I get:
ix := [-1,0,1]:
b := []:
for a in ix
do
b := [op(b),x->(x-a)^2];
end do;
and the output is
while I would like it to be (for the last line)
b := [ x -> (x+1)^2, x -> x^2, x -> (x-1)^2 ]

Your problem is that you are trying to use values for a in the construction of the body of a procedure, and not the "RHS of an expression" as you stated.
Try not to use the term "function" in this context, as it just muddles the distinction between expression and procedure.
Here is a way to get the values from ix as replacements for a in a generated list of procedures with (x-a)^2 in the body.
restart;
ix := [-1,0,1]:
b := []:
for a in ix do
b := [op(b), unapply((x-a)^2,x)];
end do:
b;
[x -> (x+1)^2, x -> x^2, x -> (x-1)^2]
It is inefficient to construct lists in this way, by repeatedly concatenating them. Since that practice scales badly in performance you really ought to drop it as a practice.
You can construct the whole list with one call to seq.
Flist := [ seq( unapply((x-a)^2,x), a in ix ) ]:
Flist;
[x -> (x+1)^2, x -> x^2, x -> (x-1)^2]
Here, Flist is a list of procedures, each of which can be evaluated at a value by calling it with an argument.
Flist[1];
x -> (x+1)^2
Flist[3](3.4);
5.76
#plot(Flist, -2..2);
Note: Procedures which display with the arrow notation x -> ... are called operators.
For fun, here are equivalents, using expressions,
Elist := [ seq( (x-a)^2, a in ix ) ]:
Elist;
[ 2 2 2]
[(x + 1) , x , (x - 1) ]
Elist[1];
2
(x + 1)
eval(Elist[3], x=3.4);
5.76
#plot(Elist, x=-2..2);
There are other ways to generate the procedures, with values of a in the body being specified programmatically. The unapply command is not the only possible mechanism, although it is the easiest for your example.
Another way is to substitute, for example,
generic := x -> (x-_dummy)^2:
Hlist := [ seq( subs(_dummy=a, eval(generic)), a in ix ) ]:
Hlist;
[x -> (x+1)^2, x -> x^2, x -> (x-1)^2]

Related

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.

How do I the calculate the sqrt of a natural or rational number in coq?

I'm learning coq and I'm trying to make my own Point and Line data types. I'd like to make a function that returns the length of a line, but I can't seem to find the sqrt function that will return a calculation. I tried used Coq.Reals.R_sqrt, but apparently that's only used for abstract math, so it won't run the calculation.
So then I tried importing Coq.Numbers.Natural.Abstract.NSqrt and Coq.Numbers.NatInt.NZSqrt. but neither put sqrt function into the environment.
This is what I have so far...
Require Import Coq.QArith.QArith_base.
Require Import Coq.Numbers.NatInt.NZSqrt.
Require Import Coq.Numbers.Natural.Abstract.NSqrt.
Require Import Coq.ZArith.BinInt.
Inductive Point : Type :=
point : Q -> Q -> Point.
Inductive Line : Type :=
line : Point -> Point -> Line.
Definition line_fst (l:Line) :=
match l with
| line x y => x
end.
Definition line_snd (l:Line) :=
match l with
| line x y => y
end.
Definition point_fst (p:Point) :=
match p with
| point x y => x
end.
Definition point_snd (p:Point) :=
match p with
| point x y => y
end.
(* The reference sqrt was not found in the current environment. *)
Definition line_length (l:Line) :=
sqrt(
(minus (point_snd(line_fst l)) (point_fst(line_fst l)))^2
+
(minus (point_snd(line_snd l)) (point_fst(line_snd l)))^2
).
Example line_example : (
line_length (line (point 0 0) (point 0 2)) = 2
).
If you want your square root to compute, there are two things you can do.
Use the CoRN library. Then you will get real number functions that actually compute. However, those real numbers will just be functions that you can ask for approximations to a certain precision, so might not be what you are looking for. Also, I think CoRN is not terribly well maintained nowadays.
Use the natural number square root from the standard library that you already mentioned, and use that to calculate the square roots that you want to a certain precision yourself. This function you get by importingBinNat:
Coq < Require Import BinNat.
[Loading ML file z_syntax_plugin.cmxs ... done]
Coq < Eval compute in N.sqrt 1000.
= 31%N
: N

Fail to use let-destruct for tuple in Coq

I'm a new user for Coq. I have defined some functions:
Definition p (a : nat) := (a + 1, a + 2, a + 3).
Definition q :=
let (s, r, t) := p 1 in
s + r + t.
Definition q' :=
match p 1 with
| (s, r, t) => s + r + t
end.
I'm trying to destruct the result of p into a tuple representation. However coqc complains on q:
Error: Destructing let on this type expects 2 variables.
while q' can pass the compilation. If I change p to return a pair(a + 1, a + 2), the corresponding q and q' both work fine.
Why let-destruct only allows pair? Or have I made any error in syntax? I've checked with Coq manual but found no clue.
Thank you!
What is a bit confusing in Coq is that there are two different forms of destructing let. The one you are looking for needs a quote before the pattern:
Definition p (a : nat) := (a + 1, a + 2, a + 3).
Definition q :=
let '(s, r, t) := p 1 in
s + r + t.
Prefixing the pattern with a quote allows you to use nested patterns and use user-defined notations in them. The form without the quote only works with one-level patterns, and doesn't allow you to use notations, or refer to constructor names in your patterns.

Coq - use Prop (True | False) in if ... then ... else

I'm kind of new to Coq.
I'm trying to implement a generic version of insertion sort. I'm implementing is as a module that takes a Comparator as a parameter. This Comparator implements comparison operators (such as is_eq, is_le, is_neq, etc.).
In insertion sort, in order to insert, I must compare two elements in the input list, and based on the result of the comparison, insert the element into the correct location.
My problem is that the implementations of the comparison operators are type -> type -> prop (i need them to be like this for implementation of other types/proofs). I'd rather not create type -> type -> bool versions of the operators if it can be avoided.
Is there any way to convert a True | False prop to a bool for use in a if ... then ... else clause?
The comparator module type:
Module Type ComparatorSig.
Parameter X: Set.
Parameter is_eq : X -> X -> Prop.
Parameter is_le : X -> X -> Prop.
Parameter is_neq : X -> X -> Prop.
Infix "=" := is_eq (at level 70).
Infix "<>" := (~ is_eq) (at level 70).
Infix "<=" := is_le (at level 70).
Parameter eqDec : forall x y : X, { x = y } + { x <> y }.
Axiom is_le_trans : forall (x y z:X), is_le x y -> is_le y z -> is_le x z.
End ComparatorSig.
An implementation for natural numbers:
Module IntComparator <: Comparator.ComparatorSig.
Definition X := nat.
Definition is_le x y := x <= y.
Definition is_eq x y := eq_nat x y.
Definition is_neq x y:= ~ is_eq x y.
Definition eqDec := eq_nat_dec.
Definition is_le_trans := le_trans.
End IntComparator.
The insertion part of insertion sort:
Fixpoint insert (x : IntComparator .X) (l : list IntComparator .X) :=
match l with
| nil => x :: nil
| h :: tl => if IntComparator.is_le x h then x :: h :: tl else h :: (insert x tl)
end.
(obviously, the insert fixpoint doesn't work, since is_le is returns Prop and not bool).
Any help is appreciated.
You seem to be a bit confused about Prop.
is_le x y is of type Prop, and is the statement x is less or equal to y. It is not a proof that this statement is correct. A proof that this statement is correct would be p : is_le x y, an inhabitant of that type (i.e. a witness of that statement's truth).
This is why it does not make much sense to pattern match on IntComparator.is_le x h.
A better interface would be the following:
Module Type ComparatorSig.
Parameter X: Set.
Parameter is_le : X -> X -> Prop.
Parameter is_le_dec : forall x y, { is_le x y } + { ~ is_le x y }.
In particular, the type of is_le_dec is that of a decision procedure for the property is_le, that is, it returns either a proof that x <= y, or a proof that ~ (x <= y). Since this is a type with two constructors, you can leverage the if sugar:
... (if IntComparator.is_le_dec x h then ... else ...) ...
This is, in some sense, an enhanced bool, which returns a witness for what it is trying to decide. The type in question is called sumbool and you can learn about it here:
http://coq.inria.fr/library/Coq.Init.Specif.html#sumbool
In general, it does not make sense to talk about True or False in executing code.
First, because these live in Prop, which means that they cannot be computationally relevant as they will be erased.
Second, because they are not the only inhabitants of Prop. While true and false are the only values of type bool, which implies you can pattern-match, the type Prop contains an infinite number of elements (all the statements you can imagine), thus it makes no sense to try and pattern-match on a element of type Prop.