(** A library of positive multivariate polynomials *)
(** * Representation of polynomials:  - [pow] is the type of a variable identifier and its exponent.  - [mon] is the type of a monomial, consisting of a coefficient and a list of variable identifiers with their exponents.  - [pol] is the type of a polynomial, consisting of the number of variables and a list of monomials. *)
Definition pow : Type := (nat*nat)%type.
Definition mon : Type := (nat * list pow)%type.
Definition pol : Type := (nat * list mon)%type.
(** * Evaluation of polynomials  - [peval p [v0, v1,...]] is the evaluation of the polynomial [p] with variables [0], [1]... respectively instantiated with the values [v0], [v1]... If a variable is not assigned a value, then it is assumed to be [0]. Values that do not correspond to a variable are ignored. *)
Definition peval_pow (xn:pow)(l:list nat) : nat :=
power (nth (fst xn) l 0) (snd xn).
Definition peval_mon (m:mon)(l:list nat) : nat :=
(fst m) * multl (map (fun x => peval_pow x l) (snd m)).
Definition peval (p:pol)(l:list nat) :=
plusl (map (fun m => peval_mon m l) (snd p)).
Notation parity := (@fst nat (list mon)).
(** * Well-formedness of polynomials *)
Definition pWF_pow (ar:nat)(xn:pow) : Prop :=
fst xn < ar.
Definition pWF_mon (ar:nat)(m:mon) : Prop :=
andl (pWF_pow ar) (snd m).
Definition pWF' (ar:nat)(ml:list mon) : Prop :=
andl (pWF_mon ar) ml.
Definition pWF (p:pol) : Prop :=
pWF' (fst p) (snd p).
(** * Basic polynomials *)
(** ** Constant polynomial  - [pcst ar a] is the constant polynomial with [ar] variables and equal to the constant [a]. *)
Definition pcst (ar a:nat) : pol :=
(ar, [(a,nil)]).
(** ** Sum of polynomials  - [pplus p1 p2] is the sum of the polynomials [p1] and [p2].  - [pplusl pl] is the sum of the polynomials in the list [pl]. *)
Definition pplus (p1 p2:pol) : pol :=
(max (fst p1) (fst p2), snd p1 ++ snd p2).
Definition pplusl (pl:list pol) : pol :=
fold_right pplus (pcst 0 0) pl.
Definition pWF_pplusl : forall pl,
andl pWF pl -> pWF (pplusl pl).
(** ** Multiplication of polynomials  - [pmult p1 p2] is the multiplication of the polynomials [p1] and [p2].  - [pmultl pl] is the multiplication of the polynomials in the list [pl]. *)
Definition pmult_mon (m12:mon*mon) : mon :=
(fst (fst m12) * fst (snd m12), snd (fst m12) ++  snd (snd m12)).
Definition pmult (p1 p2:pol) : pol :=
(max (fst p1) (fst p2), map pmult_mon (list_prod (snd p1) (snd p2))).
Definition pmultl (pl:list pol) : pol :=
fold_right pmult (pcst 0 1) pl.

Lemma parity_pmultl pl :
parity (pmultl pl) = maxl (map parity pl).