(*  Title:      HOL/Decision_Procs/Polynomial_List.thy
    Author:     Amine Chaieb
*)

section \<open>Univariate Polynomials as lists\<close>

theory Polynomial_List
imports Complex_Main
begin

text \<open>Application of polynomial as a function.\<close>

primrec (in semiring_0) poly :: "'a list \<Rightarrow> 'a \<Rightarrow> 'a"
where
  poly_Nil: "poly [] x = 0"
| poly_Cons: "poly (h # t) x = h + x * poly t x"

subsection \<open>Arithmetic Operations on Polynomials\<close>

text \<open>Addition\<close>
primrec (in semiring_0) padd :: "'a list \<Rightarrow> 'a list \<Rightarrow> 'a list"  (infixl \<open>+++\<close> 65)
where
  padd_Nil: "[] +++ l2 = l2"
| padd_Cons: "(h # t) +++ l2 = (if l2 = [] then h # t else (h + hd l2) # (t +++ tl l2))"

text \<open>Multiplication by a constant\<close>
primrec (in semiring_0) cmult :: "'a \<Rightarrow> 'a list \<Rightarrow> 'a list"  (infixl \<open>%*\<close> 70) where
  cmult_Nil: "c %* [] = []"
| cmult_Cons: "c %* (h#t) = (c * h)#(c %* t)"

text \<open>Multiplication by a polynomial\<close>
primrec (in semiring_0) pmult :: "'a list \<Rightarrow> 'a list \<Rightarrow> 'a list"  (infixl \<open>***\<close> 70)
where
  pmult_Nil: "[] *** l2 = []"
| pmult_Cons: "(h # t) *** l2 = (if t = [] then h %* l2 else (h %* l2) +++ (0 # (t *** l2)))"

text \<open>Repeated multiplication by a polynomial\<close>
primrec (in semiring_0) mulexp :: "nat \<Rightarrow> 'a list \<Rightarrow> 'a  list \<Rightarrow> 'a list"
where
  mulexp_zero: "mulexp 0 p q = q"
| mulexp_Suc: "mulexp (Suc n) p q = p *** mulexp n p q"

text \<open>Exponential\<close>
primrec (in semiring_1) pexp :: "'a list \<Rightarrow> nat \<Rightarrow> 'a list"  (infixl \<open>%^\<close> 80)
where
  pexp_0: "p %^ 0 = [1]"
| pexp_Suc: "p %^ (Suc n) = p *** (p %^ n)"

text \<open>Quotient related value of dividing a polynomial by x + a.
  Useful for divisor properties in inductive proofs.\<close>
primrec (in field) "pquot" :: "'a list \<Rightarrow> 'a \<Rightarrow> 'a list"
where
  pquot_Nil: "pquot [] a = []"
| pquot_Cons: "pquot (h # t) a =
    (if t = [] then [h] else (inverse a * (h - hd( pquot t a))) # pquot t a)"

text \<open>Normalization of polynomials (remove extra 0 coeff).\<close>
primrec (in semiring_0) pnormalize :: "'a list \<Rightarrow> 'a list"
where
  pnormalize_Nil: "pnormalize [] = []"
| pnormalize_Cons: "pnormalize (h # p) =
    (if pnormalize p = [] then (if h = 0 then [] else [h]) else h # pnormalize p)"

definition (in semiring_0) "pnormal p \<longleftrightarrow> pnormalize p = p \<and> p \<noteq> []"
definition (in semiring_0) "nonconstant p \<longleftrightarrow> pnormal p \<and> (\<forall>x. p \<noteq> [x])"

text \<open>Other definitions.\<close>

definition (in ring_1) poly_minus :: "'a list \<Rightarrow> 'a list" (\<open>-- _\<close> [80] 80)
  where "-- p = (- 1) %* p"

definition (in semiring_0) divides :: "'a list \<Rightarrow> 'a list \<Rightarrow> bool"  (infixl \<open>divides\<close> 70)
  where "p1 divides p2 \<longleftrightarrow> (\<exists>q. poly p2 = poly(p1 *** q))"

lemma (in semiring_0) dividesI: "poly p2 = poly (p1 *** q) \<Longrightarrow> p1 divides p2"
  by (auto simp add: divides_def)

lemma (in semiring_0) dividesE:
  assumes "p1 divides p2"
  obtains q where "poly p2 = poly (p1 *** q)"
  using assms by (auto simp add: divides_def)

\<comment> \<open>order of a polynomial\<close>
definition (in ring_1) order :: "'a \<Rightarrow> 'a list \<Rightarrow> nat"
  where "order a p = (SOME n. ([-a, 1] %^ n) divides p \<and> \<not> (([-a, 1] %^ (Suc n)) divides p))"

\<comment> \<open>degree of a polynomial\<close>
definition (in semiring_0) degree :: "'a list \<Rightarrow> nat"
  where "degree p = length (pnormalize p) - 1"

\<comment> \<open>squarefree polynomials --- NB with respect to real roots only\<close>
definition (in ring_1) rsquarefree :: "'a list \<Rightarrow> bool"
  where "rsquarefree p \<longleftrightarrow> poly p \<noteq> poly [] \<and> (\<forall>a. order a p = 0 \<or> order a p = 1)"

context semiring_0
begin

lemma padd_Nil2[simp]: "p +++ [] = p"
  by (induct p) auto

lemma padd_Cons_Cons: "(h1 # p1) +++ (h2 # p2) = (h1 + h2) # (p1 +++ p2)"
  by auto

lemma pminus_Nil: "-- [] = []"
  by (simp add: poly_minus_def)

lemma pmult_singleton: "[h1] *** p1 = h1 %* p1" by simp

end

lemma (in semiring_1) poly_ident_mult[simp]: "1 %* t = t"
  by (induct t) auto

lemma (in semiring_0) poly_simple_add_Cons[simp]: "[a] +++ (0 # t) = a # t"
  by simp

text \<open>Handy general properties.\<close>

lemma (in comm_semiring_0) padd_commut: "b +++ a = a +++ b"
proof (induct b arbitrary: a)
  case Nil
  then show ?case
    by auto
next
  case (Cons b bs a)
  then show ?case
    by (cases a) (simp_all add: add.commute)
qed

lemma (in comm_semiring_0) padd_assoc: "(a +++ b) +++ c = a +++ (b +++ c)"
proof (induct a arbitrary: b c)
  case Nil
  then show ?case
    by simp
next
  case Cons
  then show ?case
    by (cases b) (simp_all add: ac_simps)
qed

lemma (in semiring_0) poly_cmult_distr: "a %* (p +++ q) = a %* p +++ a %* q"
proof (induct p arbitrary: q)
  case Nil
  then show ?case
    by simp
next
  case Cons
  then show ?case
    by (cases q) (simp_all add: distrib_left)
qed

lemma (in ring_1) pmult_by_x[simp]: "[0, 1] *** t = 0 # t"
proof (induct t)
  case Nil
  then show ?case
    by simp
next
  case (Cons a t)
  then show ?case
    by (cases t) (auto simp add: padd_commut)
qed

text \<open>Properties of evaluation of polynomials.\<close>

lemma (in semiring_0) poly_add: "poly (p1 +++ p2) x = poly p1 x + poly p2 x"
proof (induct p1 arbitrary: p2)
  case Nil
  then show ?case
    by simp
next
  case (Cons a as p2)
  then show ?case
    by (cases p2) (simp_all add: ac_simps distrib_left)
qed

lemma (in comm_semiring_0) poly_cmult: "poly (c %* p) x = c * poly p x"
proof (induct p)
  case Nil
  then show ?case
    by simp
next
  case Cons
  then show ?case
    by (cases "x = zero") (auto simp add: distrib_left ac_simps)
qed

lemma (in comm_semiring_0) poly_cmult_map: "poly (map ((*) c) p) x = c * poly p x"
  by (induct p) (auto simp add: distrib_left ac_simps)

lemma (in comm_ring_1) poly_minus: "poly (-- p) x = - (poly p x)"
  by (simp add: poly_minus_def) (auto simp add: poly_cmult)

lemma (in comm_semiring_0) poly_mult: "poly (p1 *** p2) x = poly p1 x * poly p2 x"
proof (induct p1 arbitrary: p2)
  case Nil
  then show ?case
    by simp
next
  case (Cons a as)
  then show ?case
    by (cases as) (simp_all add: poly_cmult poly_add distrib_right distrib_left ac_simps)
qed

class idom_char_0 = idom + ring_char_0

subclass (in field_char_0) idom_char_0 ..

lemma (in comm_ring_1) poly_exp: "poly (p %^ n) x = (poly p x) ^ n"
  by (induct n) (auto simp add: poly_cmult poly_mult)

text \<open>More Polynomial Evaluation lemmas.\<close>

lemma (in semiring_0) poly_add_rzero[simp]: "poly (a +++ []) x = poly a x"
  by simp

lemma (in comm_semiring_0) poly_mult_assoc: "poly ((a *** b) *** c) x = poly (a *** (b *** c)) x"
  by (simp add: poly_mult mult.assoc)

lemma (in semiring_0) poly_mult_Nil2[simp]: "poly (p *** []) x = 0"
  by (induct p) auto

lemma (in comm_semiring_1) poly_exp_add: "poly (p %^ (n + d)) x = poly (p %^ n *** p %^ d) x"
  by (induct n) (auto simp add: poly_mult mult.assoc)

subsection \<open>Key Property: if \<^term>\<open>f a = 0\<close> then \<^term>\<open>(x - a)\<close> divides \<^term>\<open>p(x)\<close>.\<close>

lemma (in comm_ring_1) lemma_poly_linear_rem: "\<exists>q r. h#t = [r] +++ [-a, 1] *** q"
proof (induct t arbitrary: h)
  case Nil
  have "[h] = [h] +++ [- a, 1] *** []" by simp
  then show ?case by blast
next
  case (Cons  x xs)
  have "\<exists>q r. h # x # xs = [r] +++ [-a, 1] *** q"
  proof -
    from Cons obtain q r where qr: "x # xs = [r] +++ [- a, 1] *** q"
      by blast
    have "h # x # xs = [a * r + h] +++ [-a, 1] *** (r # q)"
      using qr by (cases q) (simp_all add: algebra_simps)
    then show ?thesis by blast
  qed
  then show ?case by blast
qed

lemma (in comm_ring_1) poly_linear_rem: "\<exists>q r. h#t = [r] +++ [-a, 1] *** q"
  using lemma_poly_linear_rem [where t = t and a = a] by auto

lemma (in comm_ring_1) poly_linear_divides: "poly p a = 0 \<longleftrightarrow> p = [] \<or> (\<exists>q. p = [-a, 1] *** q)"
proof (cases p)
  case Nil
  then show ?thesis by simp
next
  case (Cons x xs)
  have "poly p a = 0" if "p = [-a, 1] *** q" for q
    using that by (simp add: poly_add poly_cmult)
  moreover
  have "\<exists>q. p = [- a, 1] *** q" if p0: "poly p a = 0"
  proof -
    from poly_linear_rem[of x xs a] obtain q r where qr: "x#xs = [r] +++ [- a, 1] *** q"
      by blast
    have "r = 0"
      using p0 by (simp only: Cons qr poly_mult poly_add) simp
    with Cons qr show ?thesis
      apply -
      apply (rule exI[where x = q])
      apply auto
      apply (cases q)
      apply auto
      done
  qed
  ultimately show ?thesis using Cons by blast
qed

lemma (in semiring_0) lemma_poly_length_mult[simp]:
  "length (k %* p +++  (h # (a %* p))) = Suc (length p)"
  by (induct p arbitrary: h k a) auto

lemma (in semiring_0) lemma_poly_length_mult2[simp]:
  "length (k %* p +++  (h # p)) = Suc (length p)"
  by (induct p arbitrary: h k) auto

lemma (in ring_1) poly_length_mult[simp]: "length([-a,1] *** q) = Suc (length q)"
  by auto

subsection \<open>Polynomial length\<close>

lemma (in semiring_0) poly_cmult_length[simp]: "length (a %* p) = length p"
  by (induct p) auto

lemma (in semiring_0) poly_add_length: "length (p1 +++ p2) = max (length p1) (length p2)"
  by (induct p1 arbitrary: p2) auto

lemma (in semiring_0) poly_root_mult_length[simp]: "length ([a, b] *** p) = Suc (length p)"
  by (simp add: poly_add_length)

lemma (in idom) poly_mult_not_eq_poly_Nil[simp]:
  "poly (p *** q) x \<noteq> poly [] x \<longleftrightarrow> poly p x \<noteq> poly [] x \<and> poly q x \<noteq> poly [] x"
  by (auto simp add: poly_mult)

lemma (in idom) poly_mult_eq_zero_disj: "poly (p *** q) x = 0 \<longleftrightarrow> poly p x = 0 \<or> poly q x = 0"
  by (auto simp add: poly_mult)

text \<open>Normalisation Properties.\<close>

lemma (in semiring_0) poly_normalized_nil: "pnormalize p = [] \<longrightarrow> poly p x = 0"
  by (induct p) auto

text \<open>A nontrivial polynomial of degree n has no more than n roots.\<close>
lemma (in idom) poly_roots_index_lemma:
  assumes "poly p x \<noteq> poly [] x"
    and "length p = n"
  shows "\<exists>i. \<forall>x. poly p x = 0 \<longrightarrow> (\<exists>m\<le>n. x = i m)"
  using assms
proof (induct n arbitrary: p x)
  case 0
  then show ?case by simp
next
  case (Suc n)
  have False if C: "\<And>i. \<exists>x. poly p x = 0 \<and> (\<forall>m\<le>Suc n. x \<noteq> i m)"
  proof -
    from Suc.prems have p0: "poly p x \<noteq> 0" "p \<noteq> []"
      by auto
    from p0(1)[unfolded poly_linear_divides[of p x]]
    have "\<forall>q. p \<noteq> [- x, 1] *** q"
      by blast
    from C obtain a where a: "poly p a = 0"
      by blast
    from a[unfolded poly_linear_divides[of p a]] p0(2) obtain q where q: "p = [-a, 1] *** q"
      by blast
    have lg: "length q = n"
      using q Suc.prems(2) by simp
    from q p0 have qx: "poly q x \<noteq> poly [] x"
      by (auto simp add: poly_mult poly_add poly_cmult)
    from Suc.hyps[OF qx lg] obtain i where i: "\<And>x. poly q x = 0 \<longrightarrow> (\<exists>m\<le>n. x = i m)"
      by blast
    let ?i = "\<lambda>m. if m = Suc n then a else i m"
    from C[of ?i] obtain y where y: "poly p y = 0" "\<forall>m\<le> Suc n. y \<noteq> ?i m"
      by blast
    from y have "y = a \<or> poly q y = 0"
      by (simp only: q poly_mult_eq_zero_disj poly_add) (simp add: algebra_simps)
    with i[of y] y(1) y(2) show ?thesis
      apply auto
      apply (erule_tac x = "m" in allE)
      apply auto
      done
  qed
  then show ?case by blast
qed

lemma (in idom) poly_roots_index_length:
  "poly p x \<noteq> poly [] x \<Longrightarrow> \<exists>i. \<forall>x. poly p x = 0 \<longrightarrow> (\<exists>n. n \<le> length p \<and> x = i n)"
  by (blast intro: poly_roots_index_lemma)

lemma (in idom) poly_roots_finite_lemma1:
  "poly p x \<noteq> poly [] x \<Longrightarrow> \<exists>N i. \<forall>x. poly p x = 0 \<longrightarrow> (\<exists>n::nat. n < N \<and> x = i n)"
  apply (drule poly_roots_index_length)
  apply safe
  apply (rule_tac x = "Suc (length p)" in exI)
  apply (rule_tac x = i in exI)
  apply (simp add: less_Suc_eq_le)
  done

lemma (in idom) idom_finite_lemma:
  assumes "\<forall>x. P x \<longrightarrow> (\<exists>n. n < length j \<and> x = j!n)"
  shows "finite {x. P x}"
proof -
  from assms have "{x. P x} \<subseteq> set j"
    by auto
  then show ?thesis
    using finite_subset by auto
qed

lemma (in idom) poly_roots_finite_lemma2:
  "poly p x \<noteq> poly [] x \<Longrightarrow> \<exists>i. \<forall>x. poly p x = 0 \<longrightarrow> x \<in> set i"
  apply (drule poly_roots_index_length)
  apply safe
  apply (rule_tac x = "map (\<lambda>n. i n) [0 ..< Suc (length p)]" in exI)
  apply (auto simp add: image_iff)
  apply (erule_tac x="x" in allE)
  apply clarsimp
  apply (case_tac "n = length p")
  apply (auto simp add: order_le_less)
  done

lemma (in ring_char_0) UNIV_ring_char_0_infinte: "\<not> finite (UNIV :: 'a set)"
proof
  assume F: "finite (UNIV :: 'a set)"
  have "finite (UNIV :: nat set)"
  proof (rule finite_imageD)
    have "of_nat ` UNIV \<subseteq> UNIV"
      by simp
    then show "finite (of_nat ` UNIV :: 'a set)"
      using F by (rule finite_subset)
    show "inj (of_nat :: nat \<Rightarrow> 'a)"
      by (simp add: inj_on_def)
  qed
  with infinite_UNIV_nat show False ..
qed

lemma (in idom_char_0) poly_roots_finite: "poly p \<noteq> poly [] \<longleftrightarrow> finite {x. poly p x = 0}"
  (is "?lhs \<longleftrightarrow> ?rhs")
proof
  show ?rhs if ?lhs
    using that
    apply -
    apply (erule contrapos_np)
    apply (rule ext)
    apply (rule ccontr)
    apply (clarify dest!: poly_roots_finite_lemma2)
    using finite_subset
  proof -
    fix x i
    assume F: "\<not> finite {x. poly p x = 0}"
      and P: "\<forall>x. poly p x = 0 \<longrightarrow> x \<in> set i"
    from P have "{x. poly p x = 0} \<subseteq> set i"
      by auto
    with finite_subset F show False
      by auto
  qed
  show ?lhs if ?rhs
    using UNIV_ring_char_0_infinte that by auto
qed

text \<open>Entirety and Cancellation for polynomials\<close>

lemma (in idom_char_0) poly_entire_lemma2:
  assumes p0: "poly p \<noteq> poly []"
    and q0: "poly q \<noteq> poly []"
  shows "poly (p***q) \<noteq> poly []"
proof -
  let ?S = "\<lambda>p. {x. poly p x = 0}"
  have "?S (p *** q) = ?S p \<union> ?S q"
    by (auto simp add: poly_mult)
  with p0 q0 show ?thesis
    unfolding poly_roots_finite by auto
qed

lemma (in idom_char_0) poly_entire:
  "poly (p *** q) = poly [] \<longleftrightarrow> poly p = poly [] \<or> poly q = poly []"
  using poly_entire_lemma2[of p q]
  by (auto simp add: fun_eq_iff poly_mult)

lemma (in idom_char_0) poly_entire_neg:
  "poly (p *** q) \<noteq> poly [] \<longleftrightarrow> poly p \<noteq> poly [] \<and> poly q \<noteq> poly []"
  by (simp add: poly_entire)

lemma (in comm_ring_1) poly_add_minus_zero_iff:
  "poly (p +++ -- q) = poly [] \<longleftrightarrow> poly p = poly q"
  by (auto simp add: algebra_simps poly_add poly_minus_def fun_eq_iff poly_cmult)

lemma (in comm_ring_1) poly_add_minus_mult_eq:
  "poly (p *** q +++ --(p *** r)) = poly (p *** (q +++ -- r))"
  by (auto simp add: poly_add poly_minus_def fun_eq_iff poly_mult poly_cmult algebra_simps)

subclass (in idom_char_0) comm_ring_1 ..

lemma (in idom_char_0) poly_mult_left_cancel:
  "poly (p *** q) = poly (p *** r) \<longleftrightarrow> poly p = poly [] \<or> poly q = poly r"
proof -
  have "poly (p *** q) = poly (p *** r) \<longleftrightarrow> poly (p *** q +++ -- (p *** r)) = poly []"
    by (simp only: poly_add_minus_zero_iff)
  also have "\<dots> \<longleftrightarrow> poly p = poly [] \<or> poly q = poly r"
    by (auto intro: simp add: poly_add_minus_mult_eq poly_entire poly_add_minus_zero_iff)
  finally show ?thesis .
qed

lemma (in idom) poly_exp_eq_zero[simp]: "poly (p %^ n) = poly [] \<longleftrightarrow> poly p = poly [] \<and> n \<noteq> 0"
  apply (simp only: fun_eq_iff add: HOL.all_simps [symmetric])
  apply (rule arg_cong [where f = All])
  apply (rule ext)
  apply (induct n)
  apply (auto simp add: poly_exp poly_mult)
  done

lemma (in comm_ring_1) poly_prime_eq_zero[simp]: "poly [a, 1] \<noteq> poly []"
  apply (simp add: fun_eq_iff)
  apply (rule_tac x = "minus one a" in exI)
  apply (simp add: add.commute [of a])
  done

lemma (in idom) poly_exp_prime_eq_zero: "poly ([a, 1] %^ n) \<noteq> poly []"
  by auto

text \<open>A more constructive notion of polynomials being trivial.\<close>

lemma (in idom_char_0) poly_zero_lemma': "poly (h # t) = poly [] \<Longrightarrow> h = 0 \<and> poly t = poly []"
  apply (simp add: fun_eq_iff)
  apply (case_tac "h = zero")
  apply (drule_tac [2] x = zero in spec)
  apply auto
  apply (cases "poly t = poly []")
  apply simp
proof -
  fix x
  assume H: "\<forall>x. x = 0 \<or> poly t x = 0"
  assume pnz: "poly t \<noteq> poly []"
  let ?S = "{x. poly t x = 0}"
  from H have "\<forall>x. x \<noteq> 0 \<longrightarrow> poly t x = 0"
    by blast
  then have th: "?S \<supseteq> UNIV - {0}"
    by auto
  from poly_roots_finite pnz have th': "finite ?S"
    by blast
  from finite_subset[OF th th'] UNIV_ring_char_0_infinte show "poly t x = 0"
    by simp
qed

lemma (in idom_char_0) poly_zero: "poly p = poly [] \<longleftrightarrow> (\<forall>c \<in> set p. c = 0)"
proof (induct p)
  case Nil
  then show ?case by simp
next
  case Cons
  show ?case
    apply (rule iffI)
    apply (drule poly_zero_lemma')
    using Cons
    apply auto
    done
qed

lemma (in idom_char_0) poly_0: "\<forall>c \<in> set p. c = 0 \<Longrightarrow> poly p x = 0"
  unfolding poly_zero[symmetric] by simp

text \<open>Basics of divisibility.\<close>

lemma (in idom) poly_primes: "[a, 1] divides (p *** q) \<longleftrightarrow> [a, 1] divides p \<or> [a, 1] divides q"
  apply (auto simp add: divides_def fun_eq_iff poly_mult poly_add poly_cmult distrib_right [symmetric])
  apply (drule_tac x = "uminus a" in spec)
  apply (simp add: poly_linear_divides poly_add poly_cmult distrib_right [symmetric])
  apply (cases "p = []")
  apply (rule exI[where x="[]"])
  apply simp
  apply (cases "q = []")
  apply (erule allE[where x="[]"])
  apply simp

  apply clarsimp
  apply (cases "\<exists>q. p = a %* q +++ (0 # q)")
  apply (clarsimp simp add: poly_add poly_cmult)
  apply (rule_tac x = qa in exI)
  apply (simp add: distrib_right [symmetric])
  apply clarsimp

  apply (auto simp add: poly_linear_divides poly_add poly_cmult distrib_right [symmetric])
  apply (rule_tac x = "pmult qa q" in exI)
  apply (rule_tac [2] x = "pmult p qa" in exI)
  apply (auto simp add: poly_add poly_mult poly_cmult ac_simps)
  done

lemma (in comm_semiring_1) poly_divides_refl[simp]: "p divides p"
  apply (simp add: divides_def)
  apply (rule_tac x = "[one]" in exI)
  apply (auto simp add: poly_mult fun_eq_iff)
  done

lemma (in comm_semiring_1) poly_divides_trans: "p divides q \<Longrightarrow> q divides r \<Longrightarrow> p divides r"
  apply (simp add: divides_def)
  apply safe
  apply (rule_tac x = "pmult qa qaa" in exI)
  apply (auto simp add: poly_mult fun_eq_iff mult.assoc)
  done

lemma (in comm_semiring_1) poly_divides_exp: "m \<le> n \<Longrightarrow> (p %^ m) divides (p %^ n)"
  by (auto simp: le_iff_add divides_def poly_exp_add fun_eq_iff)

lemma (in comm_semiring_1) poly_exp_divides: "(p %^ n) divides q \<Longrightarrow> m \<le> n \<Longrightarrow> (p %^ m) divides q"
  by (blast intro: poly_divides_exp poly_divides_trans)

lemma (in comm_semiring_0) poly_divides_add: "p divides q \<Longrightarrow> p divides r \<Longrightarrow> p divides (q +++ r)"
  apply (auto simp add: divides_def)
  apply (rule_tac x = "padd qa qaa" in exI)
  apply (auto simp add: poly_add fun_eq_iff poly_mult distrib_left)
  done

lemma (in comm_ring_1) poly_divides_diff: "p divides q \<Longrightarrow> p divides (q +++ r) \<Longrightarrow> p divides r"
  apply (auto simp add: divides_def)
  apply (rule_tac x = "padd qaa (poly_minus qa)" in exI)
  apply (auto simp add: poly_add fun_eq_iff poly_mult poly_minus algebra_simps)
  done

lemma (in comm_ring_1) poly_divides_diff2: "p divides r \<Longrightarrow> p divides (q +++ r) \<Longrightarrow> p divides q"
  apply (erule poly_divides_diff)
  apply (auto simp add: poly_add fun_eq_iff poly_mult divides_def ac_simps)
  done

lemma (in semiring_0) poly_divides_zero: "poly p = poly [] \<Longrightarrow> q divides p"
  apply (simp add: divides_def)
  apply (rule exI[where x = "[]"])
  apply (auto simp add: fun_eq_iff poly_mult)
  done

lemma (in semiring_0) poly_divides_zero2 [simp]: "q divides []"
  apply (simp add: divides_def)
  apply (rule_tac x = "[]" in exI)
  apply (auto simp add: fun_eq_iff)
  done

text \<open>At last, we can consider the order of a root.\<close>

lemma (in idom_char_0) poly_order_exists_lemma:
  assumes "length p = d"
    and "poly p \<noteq> poly []"
  shows "\<exists>n q. p = mulexp n [-a, 1] q \<and> poly q a \<noteq> 0"
  using assms
proof (induct d arbitrary: p)
  case 0
  then show ?case by simp
next
  case (Suc n p)
  show ?case
  proof (cases "poly p a = 0")
    case True
    from Suc.prems have h: "length p = Suc n" "poly p \<noteq> poly []"
      by auto
    then have pN: "p \<noteq> []"
      by auto
    from True[unfolded poly_linear_divides] pN obtain q where q: "p = [-a, 1] *** q"
      by blast
    from q h True have qh: "length q = n" "poly q \<noteq> poly []"
      apply simp_all
      apply (simp only: fun_eq_iff)
      apply (rule ccontr)
      apply (simp add: fun_eq_iff poly_add poly_cmult)
      done
    from Suc.hyps[OF qh] obtain m r where mr: "q = mulexp m [-a,1] r" "poly r a \<noteq> 0"
      by blast
    from mr q have "p = mulexp (Suc m) [-a,1] r \<and> poly r a \<noteq> 0"
      by simp
    then show ?thesis by blast
  next
    case False
    then show ?thesis
      using Suc.prems
      apply simp
      apply (rule exI[where x="0::nat"])
      apply simp
      done
  qed
qed

lemma (in comm_semiring_1) poly_mulexp: "poly (mulexp n p q) x = (poly p x) ^ n * poly q x"
  by (induct n) (auto simp add: poly_mult ac_simps)

lemma (in comm_semiring_1) divides_left_mult:
  assumes "(p *** q) divides r"
  shows "p divides r \<and> q divides r"
proof-
  from assms obtain t where "poly r = poly (p *** q *** t)"
    unfolding divides_def by blast
  then have "poly r = poly (p *** (q *** t))" and "poly r = poly (q *** (p *** t))"
    by (auto simp add: fun_eq_iff poly_mult ac_simps)
  then show ?thesis
    unfolding divides_def by blast
qed

(* FIXME: Tidy up *)

lemma (in semiring_1) zero_power_iff: "0 ^ n = (if n = 0 then 1 else 0)"
  by (induct n) simp_all

lemma (in idom_char_0) poly_order_exists:
  assumes "length p = d"
    and "poly p \<noteq> poly []"
  shows "\<exists>n. [- a, 1] %^ n divides p \<and> \<not> [- a, 1] %^ Suc n divides p"
proof -
  from assms have "\<exists>n q. p = mulexp n [- a, 1] q \<and> poly q a \<noteq> 0"
    by (rule poly_order_exists_lemma)
  then obtain n q where p: "p = mulexp n [- a, 1] q" and "poly q a \<noteq> 0"
    by blast
  have "[- a, 1] %^ n divides mulexp n [- a, 1] q"
  proof (rule dividesI)
    show "poly (mulexp n [- a, 1] q) = poly ([- a, 1] %^ n *** q)"
      by (induct n) (simp_all add: poly_add poly_cmult poly_mult algebra_simps)
  qed
  moreover have "\<not> [- a, 1] %^ Suc n divides mulexp n [- a, 1] q"
  proof
    assume "[- a, 1] %^ Suc n divides mulexp n [- a, 1] q"
    then obtain m where "poly (mulexp n [- a, 1] q) = poly ([- a, 1] %^ Suc n *** m)"
      by (rule dividesE)
    moreover have "poly (mulexp n [- a, 1] q) \<noteq> poly ([- a, 1] %^ Suc n *** m)"
    proof (induct n)
      case 0
      show ?case
      proof (rule ccontr)
        assume "\<not> ?thesis"
        then have "poly q a = 0"
          by (simp add: poly_add poly_cmult)
        with \<open>poly q a \<noteq> 0\<close> show False
          by simp
      qed
    next
      case (Suc n)
      show ?case
        by (rule pexp_Suc [THEN ssubst])
          (simp add: poly_mult_left_cancel poly_mult_assoc Suc del: pmult_Cons pexp_Suc)
    qed
    ultimately show False by simp
  qed
  ultimately show ?thesis
    by (auto simp add: p)
qed

lemma (in semiring_1) poly_one_divides[simp]: "[1] divides p"
  by (auto simp add: divides_def)

lemma (in idom_char_0) poly_order:
  "poly p \<noteq> poly [] \<Longrightarrow> \<exists>!n. ([-a, 1] %^ n) divides p \<and> \<not> (([-a, 1] %^ Suc n) divides p)"
  apply (auto intro: poly_order_exists simp add: less_linear simp del: pmult_Cons pexp_Suc)
  apply (cut_tac x = y and y = n in less_linear)
  apply (drule_tac m = n in poly_exp_divides)
  apply (auto dest: Suc_le_eq [THEN iffD2, THEN [2] poly_exp_divides]
    simp del: pmult_Cons pexp_Suc)
  done

text \<open>Order\<close>

lemma some1_equalityD: "n = (SOME n. P n) \<Longrightarrow> \<exists>!n. P n \<Longrightarrow> P n"
  by (blast intro: someI2)

lemma (in idom_char_0) order:
  "([-a, 1] %^ n) divides p \<and> \<not> (([-a, 1] %^ Suc n) divides p) \<longleftrightarrow>
    n = order a p \<and> poly p \<noteq> poly []"
  unfolding order_def
  apply (rule iffI)
  apply (blast dest: poly_divides_zero intro!: some1_equality [symmetric] poly_order)
  apply (blast intro!: poly_order [THEN [2] some1_equalityD])
  done

lemma (in idom_char_0) order2:
  "poly p \<noteq> poly [] \<Longrightarrow>
    ([-a, 1] %^ (order a p)) divides p \<and> \<not> ([-a, 1] %^ Suc (order a p)) divides p"
  by (simp add: order del: pexp_Suc)

lemma (in idom_char_0) order_unique:
  "poly p \<noteq> poly [] \<Longrightarrow> ([-a, 1] %^ n) divides p \<Longrightarrow> \<not> ([-a, 1] %^ (Suc n)) divides p \<Longrightarrow>
    n = order a p"
  using order [of a n p] by auto

lemma (in idom_char_0) order_unique_lemma:
  "poly p \<noteq> poly [] \<and> ([-a, 1] %^ n) divides p \<and> \<not> ([-a, 1] %^ (Suc n)) divides p \<Longrightarrow>
    n = order a p"
  by (blast intro: order_unique)

lemma (in ring_1) order_poly: "poly p = poly q \<Longrightarrow> order a p = order a q"
  by (auto simp add: fun_eq_iff divides_def poly_mult order_def)

lemma (in semiring_1) pexp_one[simp]: "p %^ (Suc 0) = p"
  by (induct p) auto

lemma (in comm_ring_1) lemma_order_root:
  "0 < n \<and> [- a, 1] %^ n divides p \<and> \<not> [- a, 1] %^ (Suc n) divides p \<Longrightarrow> poly p a = 0"
  by (induct n arbitrary: a p) (auto simp add: divides_def poly_mult simp del: pmult_Cons)

lemma (in idom_char_0) order_root: "poly p a = 0 \<longleftrightarrow> poly p = poly [] \<or> order a p \<noteq> 0"
  apply (cases "poly p = poly []")
  apply auto
  apply (simp add: poly_linear_divides del: pmult_Cons)
  apply safe
  apply (drule_tac [!] a = a in order2)
  apply (rule ccontr)
  apply (simp add: divides_def poly_mult fun_eq_iff del: pmult_Cons)
  apply blast
  using neq0_conv apply (blast intro: lemma_order_root)
  done

lemma (in idom_char_0) order_divides:
  "([-a, 1] %^ n) divides p \<longleftrightarrow> poly p = poly [] \<or> n \<le> order a p"
  apply (cases "poly p = poly []")
  apply auto
  apply (simp add: divides_def fun_eq_iff poly_mult)
  apply (rule_tac x = "[]" in exI)
  apply (auto dest!: order2 [where a=a] intro: poly_exp_divides simp del: pexp_Suc)
  done

lemma (in idom_char_0) order_decomp:
  "poly p \<noteq> poly [] \<Longrightarrow> \<exists>q. poly p = poly (([-a, 1] %^ order a p) *** q) \<and> \<not> [-a, 1] divides q"
  unfolding divides_def
  apply (drule order2 [where a = a])
  apply (simp add: divides_def del: pexp_Suc pmult_Cons)
  apply safe
  apply (rule_tac x = q in exI)
  apply safe
  apply (drule_tac x = qa in spec)
  apply (auto simp add: poly_mult fun_eq_iff poly_exp ac_simps simp del: pmult_Cons)
  done

text \<open>Important composition properties of orders.\<close>
lemma order_mult:
  fixes a :: "'a::idom_char_0"
  shows "poly (p *** q) \<noteq> poly [] \<Longrightarrow> order a (p *** q) = order a p + order a q"
  apply (cut_tac a = a and p = "p *** q" and n = "order a p + order a q" in order)
  apply (auto simp add: poly_entire simp del: pmult_Cons)
  apply (drule_tac a = a in order2)+
  apply safe
  apply (simp add: divides_def fun_eq_iff poly_exp_add poly_mult del: pmult_Cons, safe)
  apply (rule_tac x = "qa *** qaa" in exI)
  apply (simp add: poly_mult ac_simps del: pmult_Cons)
  apply (drule_tac a = a in order_decomp)+
  apply safe
  apply (subgoal_tac "[-a, 1] divides (qa *** qaa) ")
  apply (simp add: poly_primes del: pmult_Cons)
  apply (auto simp add: divides_def simp del: pmult_Cons)
  apply (rule_tac x = qb in exI)
  apply (subgoal_tac "poly ([-a, 1] %^ (order a p) *** (qa *** qaa)) =
    poly ([-a, 1] %^ (order a p) *** ([-a, 1] *** qb))")
  apply (drule poly_mult_left_cancel [THEN iffD1])
  apply force
  apply (subgoal_tac "poly ([-a, 1] %^ (order a q) *** ([-a, 1] %^ (order a p) *** (qa *** qaa))) =
    poly ([-a, 1] %^ (order a q) *** ([-a, 1] %^ (order a p) *** ([-a, 1] *** qb))) ")
  apply (drule poly_mult_left_cancel [THEN iffD1])
  apply force
  apply (simp add: fun_eq_iff poly_exp_add poly_mult ac_simps del: pmult_Cons)
  done

lemma (in idom_char_0) order_mult:
  assumes "poly (p *** q) \<noteq> poly []"
  shows "order a (p *** q) = order a p + order a q"
  using assms
  apply (cut_tac a = a and p = "pmult p q" and n = "order a p + order a q" in order)
  apply (auto simp add: poly_entire simp del: pmult_Cons)
  apply (drule_tac a = a in order2)+
  apply safe
  apply (simp add: divides_def fun_eq_iff poly_exp_add poly_mult del: pmult_Cons)
  apply safe
  apply (rule_tac x = "pmult qa qaa" in exI)
  apply (simp add: poly_mult ac_simps del: pmult_Cons)
  apply (drule_tac a = a in order_decomp)+
  apply safe
  apply (subgoal_tac "[uminus a, one] divides pmult qa qaa")
  apply (simp add: poly_primes del: pmult_Cons)
  apply (auto simp add: divides_def simp del: pmult_Cons)
  apply (rule_tac x = qb in exI)
  apply (subgoal_tac "poly (pmult (pexp [uminus a, one] (order a p)) (pmult qa qaa)) =
    poly (pmult (pexp [uminus a, one] (order a p)) (pmult [uminus a, one] qb))")
  apply (drule poly_mult_left_cancel [THEN iffD1], force)
  apply (subgoal_tac "poly (pmult (pexp [uminus a, one] (order a q))
      (pmult (pexp [uminus a, one] (order a p)) (pmult qa qaa))) =
    poly (pmult (pexp [uminus a, one] (order a q))
      (pmult (pexp [uminus a, one] (order a p)) (pmult [uminus a, one] qb)))")
  apply (drule poly_mult_left_cancel [THEN iffD1], force)
  apply (simp add: fun_eq_iff poly_exp_add poly_mult ac_simps del: pmult_Cons)
  done

lemma (in idom_char_0) order_root2: "poly p \<noteq> poly [] \<Longrightarrow> poly p a = 0 \<longleftrightarrow> order a p \<noteq> 0"
  by (rule order_root [THEN ssubst]) auto

lemma (in semiring_1) pmult_one[simp]: "[1] *** p = p"
  by auto

lemma (in semiring_0) poly_Nil_zero: "poly [] = poly [0]"
  by (simp add: fun_eq_iff)

lemma (in idom_char_0) rsquarefree_decomp:
  "rsquarefree p \<Longrightarrow> poly p a = 0 \<Longrightarrow> \<exists>q. poly p = poly ([-a, 1] *** q) \<and> poly q a \<noteq> 0"
  apply (simp add: rsquarefree_def)
  apply safe
  apply (frule_tac a = a in order_decomp)
  apply (drule_tac x = a in spec)
  apply (drule_tac a = a in order_root2 [symmetric])
  apply (auto simp del: pmult_Cons)
  apply (rule_tac x = q in exI, safe)
  apply (simp add: poly_mult fun_eq_iff)
  apply (drule_tac p1 = q in poly_linear_divides [THEN iffD1])
  apply (simp add: divides_def del: pmult_Cons, safe)
  apply (drule_tac x = "[]" in spec)
  apply (auto simp add: fun_eq_iff)
  done

text \<open>Normalization of a polynomial.\<close>

lemma (in semiring_0) poly_normalize[simp]: "poly (pnormalize p) = poly p"
  by (induct p) (auto simp add: fun_eq_iff)

text \<open>The degree of a polynomial.\<close>

lemma (in semiring_0) lemma_degree_zero: "(\<forall>c \<in> set p. c = 0) \<longleftrightarrow> pnormalize p = []"
  by (induct p) auto

lemma (in idom_char_0) degree_zero:
  assumes "poly p = poly []"
  shows "degree p = 0"
  using assms
  by (cases "pnormalize p = []") (auto simp add: degree_def poly_zero lemma_degree_zero)

lemma (in semiring_0) pnormalize_sing: "pnormalize [x] = [x] \<longleftrightarrow> x \<noteq> 0"
  by simp

lemma (in semiring_0) pnormalize_pair: "y \<noteq> 0 \<longleftrightarrow> pnormalize [x, y] = [x, y]"
  by simp

lemma (in semiring_0) pnormal_cons: "pnormal p \<Longrightarrow> pnormal (c # p)"
  unfolding pnormal_def by simp

lemma (in semiring_0) pnormal_tail: "p \<noteq> [] \<Longrightarrow> pnormal (c # p) \<Longrightarrow> pnormal p"
  unfolding pnormal_def by (auto split: if_split_asm)

lemma (in semiring_0) pnormal_last_nonzero: "pnormal p \<Longrightarrow> last p \<noteq> 0"
  by (induct p) (simp_all add: pnormal_def split: if_split_asm)

lemma (in semiring_0) pnormal_length: "pnormal p \<Longrightarrow> 0 < length p"
  unfolding pnormal_def length_greater_0_conv by blast

lemma (in semiring_0) pnormal_last_length: "0 < length p \<Longrightarrow> last p \<noteq> 0 \<Longrightarrow> pnormal p"
  by (induct p) (auto simp: pnormal_def  split: if_split_asm)

lemma (in semiring_0) pnormal_id: "pnormal p \<longleftrightarrow> 0 < length p \<and> last p \<noteq> 0"
  using pnormal_last_length pnormal_length pnormal_last_nonzero by blast

lemma (in idom_char_0) poly_Cons_eq: "poly (c # cs) = poly (d # ds) \<longleftrightarrow> c = d \<and> poly cs = poly ds"
  (is "?lhs \<longleftrightarrow> ?rhs")
proof
  show ?rhs if ?lhs
  proof -
    from that have "poly ((c # cs) +++ -- (d # ds)) x = 0" for x
      by (simp only: poly_minus poly_add algebra_simps) (simp add: algebra_simps)
    then have "poly ((c # cs) +++ -- (d # ds)) = poly []"
      by (simp add: fun_eq_iff)
    then have "c = d" and "\<forall>x \<in> set (cs +++ -- ds). x = 0"
      unfolding poly_zero by (simp_all add: poly_minus_def algebra_simps)
    from this(2) have "poly (cs +++ -- ds) x = 0" for x
      unfolding poly_zero[symmetric] by simp
    with \<open>c = d\<close> show ?thesis
      by (simp add: poly_minus poly_add algebra_simps fun_eq_iff)
  qed
  show ?lhs if ?rhs
    using that by (simp add:fun_eq_iff)
qed

lemma (in idom_char_0) pnormalize_unique: "poly p = poly q \<Longrightarrow> pnormalize p = pnormalize q"
proof (induct q arbitrary: p)
  case Nil
  then show ?case
    by (simp only: poly_zero lemma_degree_zero) simp
next
  case (Cons c cs p)
  then show ?case
  proof (induct p)
    case Nil
    then have "poly [] = poly (c # cs)"
      by blast
    then have "poly (c#cs) = poly []"
      by simp
    then show ?case
      by (simp only: poly_zero lemma_degree_zero) simp
  next
    case (Cons d ds)
    then have eq: "poly (d # ds) = poly (c # cs)"
      by blast
    then have eq': "\<And>x. poly (d # ds) x = poly (c # cs) x"
      by simp
    then have "poly (d # ds) 0 = poly (c # cs) 0"
      by blast
    then have dc: "d = c"
      by auto
    with eq have "poly ds = poly cs"
      unfolding  poly_Cons_eq by simp
    with Cons.prems have "pnormalize ds = pnormalize cs"
      by blast
    with dc show ?case
      by simp
  qed
qed

lemma (in idom_char_0) degree_unique:
  assumes pq: "poly p = poly q"
  shows "degree p = degree q"
  using pnormalize_unique[OF pq] unfolding degree_def by simp

lemma (in semiring_0) pnormalize_length: "length (pnormalize p) \<le> length p"
  by (induct p) auto

lemma (in semiring_0) last_linear_mul_lemma:
  "last ((a %* p) +++ (x # (b %* p))) = (if p = [] then x else b * last p)"
  apply (induct p arbitrary: a x b)
  apply auto
  subgoal for a p c x b
    apply (subgoal_tac "padd (cmult c p) (times b a # cmult b p) \<noteq> []")
    apply simp
    apply (induct p)
    apply auto
    done
  done

lemma (in semiring_1) last_linear_mul:
  assumes p: "p \<noteq> []"
  shows "last ([a, 1] *** p) = last p"
proof -
  from p obtain c cs where cs: "p = c # cs"
    by (cases p) auto
  from cs have eq: "[a, 1] *** p = (a %* (c # cs)) +++ (0 # (1 %* (c # cs)))"
    by (simp add: poly_cmult_distr)
  show ?thesis
    using cs unfolding eq last_linear_mul_lemma by simp
qed

lemma (in semiring_0) pnormalize_eq: "last p \<noteq> 0 \<Longrightarrow> pnormalize p = p"
  by (induct p) (auto split: if_split_asm)

lemma (in semiring_0) last_pnormalize: "pnormalize p \<noteq> [] \<Longrightarrow> last (pnormalize p) \<noteq> 0"
  by (induct p) auto

lemma (in semiring_0) pnormal_degree: "last p \<noteq> 0 \<Longrightarrow> degree p = length p - 1"
  using pnormalize_eq[of p] unfolding degree_def by simp

lemma (in semiring_0) poly_Nil_ext: "poly [] = (\<lambda>x. 0)"
  by auto

lemma (in idom_char_0) linear_mul_degree:
  assumes p: "poly p \<noteq> poly []"
  shows "degree ([a, 1] *** p) = degree p + 1"
proof -
  from p have pnz: "pnormalize p \<noteq> []"
    unfolding poly_zero lemma_degree_zero .

  from last_linear_mul[OF pnz, of a] last_pnormalize[OF pnz]
  have l0: "last ([a, 1] *** pnormalize p) \<noteq> 0" by simp

  from last_pnormalize[OF pnz] last_linear_mul[OF pnz, of a]
    pnormal_degree[OF l0] pnormal_degree[OF last_pnormalize[OF pnz]] pnz
  have th: "degree ([a,1] *** pnormalize p) = degree (pnormalize p) + 1"
    by simp

  have eqs: "poly ([a,1] *** pnormalize p) = poly ([a,1] *** p)"
    by (rule ext) (simp add: poly_mult poly_add poly_cmult)
  from degree_unique[OF eqs] th show ?thesis
    by (simp add: degree_unique[OF poly_normalize])
qed

lemma (in idom_char_0) linear_pow_mul_degree:
  "degree([a,1] %^n *** p) = (if poly p = poly [] then 0 else degree p + n)"
proof (induct n arbitrary: a p)
  case (0 a p)
  show ?case
  proof (cases "poly p = poly []")
    case True
    then show ?thesis
      using degree_unique[OF True] by (simp add: degree_def)
  next
    case False
    then show ?thesis
      by (auto simp add: poly_Nil_ext)
  qed
next
  case (Suc n a p)
  have eq: "poly ([a, 1] %^(Suc n) *** p) = poly ([a, 1] %^ n *** ([a, 1] *** p))"
    apply (rule ext)
    apply (simp add: poly_mult poly_add poly_cmult)
    apply (simp add: ac_simps distrib_left)
    done
  note deq = degree_unique[OF eq]
  show ?case
  proof (cases "poly p = poly []")
    case True
    with eq have eq': "poly ([a, 1] %^(Suc n) *** p) = poly []"
      by (auto simp add: poly_mult poly_cmult poly_add)
    from degree_unique[OF eq'] True show ?thesis
      by (simp add: degree_def)
  next
    case False
    then have ap: "poly ([a,1] *** p) \<noteq> poly []"
      using poly_mult_not_eq_poly_Nil unfolding poly_entire by auto
    have eq: "poly ([a, 1] %^(Suc n) *** p) = poly ([a, 1]%^n *** ([a, 1] *** p))"
      by (auto simp add: poly_mult poly_add poly_exp poly_cmult algebra_simps)
    from ap have ap': "poly ([a, 1] *** p) = poly [] \<longleftrightarrow> False"
      by blast
    have th0: "degree ([a, 1]%^n *** ([a, 1] *** p)) = degree ([a, 1] *** p) + n"
      apply (simp only: Suc.hyps[of a "pmult [a,one] p"] ap')
      apply simp
      done
    from degree_unique[OF eq] ap False th0 linear_mul_degree[OF False, of a]
    show ?thesis
      by (auto simp del: poly.simps)
  qed
qed

lemma (in idom_char_0) order_degree:
  assumes p0: "poly p \<noteq> poly []"
  shows "order a p \<le> degree p"
proof -
  from order2[OF p0, unfolded divides_def]
  obtain q where q: "poly p = poly ([- a, 1]%^ (order a p) *** q)"
    by blast
  with q p0 have "poly q \<noteq> poly []"
    by (simp add: poly_mult poly_entire)
  with degree_unique[OF q, unfolded linear_pow_mul_degree] show ?thesis
    by auto
qed

text \<open>Tidier versions of finiteness of roots.\<close>
lemma (in idom_char_0) poly_roots_finite_set:
  "poly p \<noteq> poly [] \<Longrightarrow> finite {x. poly p x = 0}"
  unfolding poly_roots_finite .

text \<open>Bound for polynomial.\<close>
lemma poly_mono:
  fixes x :: "'a::linordered_idom"
  shows "\<bar>x\<bar> \<le> k \<Longrightarrow> \<bar>poly p x\<bar> \<le> poly (map abs p) k"
proof (induct p)
  case Nil
  then show ?case by simp
next
  case (Cons a p)
  then show ?case
    apply auto
    apply (rule_tac y = "\<bar>a\<bar> + \<bar>x * poly p x\<bar>" in order_trans)
    apply (rule abs_triangle_ineq)
    apply (auto intro!: mult_mono simp add: abs_mult)
    done
qed

lemma (in semiring_0) poly_Sing: "poly [c] x = c"
  by simp

end


theory Tutorial
imports Main
begin

(* Basic tactics *)

theorem prop1:
  \<open>(A\<longrightarrow>B\<longrightarrow>C)\<longrightarrow>(A\<longrightarrow>B)\<longrightarrow>A\<longrightarrow>C\<close>
  apply(rule impI)
  apply(rule impI)
  apply(rule impI)
  apply(subgoal_tac \<open>B\<longrightarrow>C\<close>)
  apply(erule mp)
  apply(erule mp)
  apply assumption
  apply(erule mp)
  apply assumption
  done

thm prop1

theorem peirce:
  \<open>((P\<longrightarrow>Q)\<longrightarrow>P)\<longrightarrow>P\<close>
  apply(subst imp_conv_disj)
  apply(subst imp_conv_disj)
  apply(subst de_Morgan_disj)
  apply(subst not_not)
  apply rule
  apply(erule disjE)
  apply(erule conjE)
  apply assumption
  apply assumption
  done

theorem
  \<open>((P\<longrightarrow>Q)\<longrightarrow>P)\<longrightarrow>P\<close>
  apply(rule impI)
  apply(drule Meson.imp_to_disjD)
  apply(erule disjE)
  apply(drule Meson.not_impD)
  apply(erule conjunct1)
  apply assumption
  done

(* Induction *)

theorem
  \<open>sum (\<lambda>x. (2::nat)^x) {x. x<n} = 2^n-1\<close>
  apply(induct n)
  apply simp
  apply(subgoal_tac \<open>{x. x<Suc n} = insert n {x. x<n}\<close>)
  by auto

primrec rev_append :: \<open>'a list \<Rightarrow> 'a list \<Rightarrow> 'a list\<close> where
  \<open>rev_append [] l2 = l2\<close> |
  \<open>rev_append (x#l1) l2 = rev_append l1 (x#l2)\<close>

theorem rev_append_correct:
  \<open>rev_append l1 l2 = rev l1 @ l2\<close>
  by (induct l1 arbitrary: l2) auto

(* Inductive types *)

datatype 'a tree = Leaf | Branch \<open>'a tree\<close> 'a \<open>'a tree\<close>

primrec inorder :: \<open>'a tree \<Rightarrow> 'a list\<close> where
  \<open>inorder Leaf = []\<close> |
  \<open>inorder (Branch left x right) = inorder left @ x # inorder right\<close>

primrec mirror :: \<open>'a tree \<Rightarrow> 'a tree\<close> where
  \<open>mirror Leaf = Leaf\<close> |
  \<open>mirror (Branch left x right) = Branch (mirror right) x (mirror left)\<close>

theorem mirror_correct:
  \<open>inorder (mirror tree) = rev (inorder tree)\<close>
  by (induct tree; simp)

(* Inductive predicates *)

inductive even_ind :: \<open>nat \<Rightarrow> bool\<close> where
  even_0: \<open>even_ind 0\<close> |
  even_SS: \<open>even_ind n \<Longrightarrow> even_ind (Suc (Suc n))\<close>

thm even_0 even_SS
thm even_ind.induct

theorem \<open>even_ind n = even n\<close>
proof
  assume \<open>even_ind n\<close>
  then show \<open>even n\<close>
    by induct auto
next
  assume \<open>even n\<close>
  then have \<open>\<exists>k. n=k+k\<close> by presburger
  then obtain k where k: \<open>n=k+k\<close> by blast
  have \<open>even_ind (k+k)\<close>
    by (induct k) (auto intro: even_ind.intros)
  then show \<open>even_ind n\<close> using k by simp
qed

theorem
  fixes list::\<open>'a::order list\<close>
  assumes assum: \<open>\<forall>i. Suc i < length list \<longrightarrow> list!i \<le> list!(Suc i)\<close>
  shows \<open>\<forall>i j. j < length list \<longrightarrow> i\<le>j \<longrightarrow> list!i \<le> list!j\<close>
proof clarify
  fix i j :: nat
  assume j_less: \<open>j < length list\<close>
  assume \<open>i\<le>j\<close>

  then obtain k where k: \<open>i+k=j\<close>
    using le_Suc_ex by blast

  from k j_less
  have \<open>list!i \<le> list!(i+k)\<close>
  proof (induct k arbitrary: j)
    (* Case 1: k=0 *)
    show \<open>list!i \<le> list!(i+0)\<close> by simp
  next
    (* Case 2: k = Suc k' *)
    fix k' j
    assume IH: \<open>\<And>j. i+k'=j \<Longrightarrow> j<length list \<Longrightarrow> list!i \<le> list!(i+k')\<close>
    assume a1: \<open>i+Suc k'=j\<close>
    assume a2: \<open>j<length list\<close>

    from a1 a2 have *: \<open>Suc (i+k') < length list\<close> by simp
    with IH have \<open>list!i \<le> list!(i+k')\<close> by simp
    also from assum[rule_format, OF *] have \<open>list!(i+k') \<le> list!Suc (i+k')\<close> .
    finally show \<open>list!i \<le> list!(i+Suc k')\<close> by simp
  qed

  with k show \<open>list!i \<le> list!j\<close> by simp
qed

end


section \<open>Challenge 1.A\<close>
theory Challenge1A
imports Main "Eval_Base.Eval_Base"
begin

text \<open>Problem definition:
\<^url>\<open>https://ethz.ch/content/dam/ethz/special-interest/infk/chair-program-method/pm/documents/Verify%20This/Challenges%202019/ghc_sort.pdf\<close>\<close>

  subsection \<open>Implementation\<close>
  text \<open>We phrase the algorithm as a functional program.
    Instead of a list of indexes for segment boundaries,
    we return a list of lists, containing the segments.\<close>

  text \<open>We start with auxiliary functions to take the longest
    increasing/decreasing sequence from the start of the list
  \<close>
  fun take_incr :: "int list \<Rightarrow> _" where
    "take_incr [] = []"
  | "take_incr [x] = [x]"
  | "take_incr (x#y#xs) = (if x<y then x#take_incr (y#xs) else [x])"

  fun take_decr :: "int list \<Rightarrow> _" where
    "take_decr [] = []"
  | "take_decr [x] = [x]"
  | "take_decr (x#y#xs) = (if x\<ge>y then x#take_decr (y#xs) else [x])"

  fun take where
    "take [] = []"
  | "take [x] = [x]"
  | "take (x#y#xs) = (if x<y then take_incr (x#y#xs) else take_decr (x#y#xs))"

  definition "take2 xs \<equiv> let l=take xs in (l,drop (length l) xs)"
    \<comment> \<open>Splits of a longest increasing/decreasing sequence from the list\<close>

  text \<open>The main algorithm then iterates until the whole input list is split\<close>
  function cuts where
    "cuts xs = (if xs=[] then [] else let (c,xs) = take2 xs in c#cuts xs)"
    by pat_completeness auto

  subsection \<open>Termination\<close>
  text \<open>First, we show termination. This will give us induction and proper unfolding lemmas.\<close>

  lemma take_non_empty:
    "take xs \<noteq> []" if "xs \<noteq> []"
    using that
    apply (cases xs)
     apply clarsimp
    subgoal for x ys
      apply (cases ys)
       apply auto
      done
    done

  termination
    apply (relation "measure length")
     apply (auto simp: take2_def Let_def)
    using take_non_empty
    apply auto
    done

  declare cuts.simps[simp del]

  subsection \<open>Correctness\<close>

  subsubsection \<open>Property 1: The Exact Sequence is Covered\<close>
  lemma tdconc: "\<exists>ys. xs = take_decr xs @ ys"
    apply2 (induction xs rule: take_decr.induct)
    apply auto
    done

  lemma ticonc: "\<exists>ys. xs = take_incr xs @ ys"
    apply2 (induction xs rule: take_incr.induct)
    apply auto
    done

  lemma take_conc: "\<exists>ys. xs = take xs@ys"
    using tdconc ticonc
    apply (cases xs rule: take.cases)
    by auto

  theorem concat_cuts: "concat (cuts xs) = xs"
    apply2 (induction xs rule: cuts.induct)
    apply (subst cuts.simps)
    apply (auto simp: take2_def Let_def)
    by (metis append_eq_conv_conj take_conc)

  subsubsection \<open>Property 2: Monotonicity\<close>
  text \<open>We define constants to specify increasing/decreasing sequences.\<close>
  fun incr where
    "incr [] \<longleftrightarrow> True"
  | "incr [_] \<longleftrightarrow> True"
  | "incr (x#y#xs) \<longleftrightarrow> x<y \<and> incr (y#xs)"

  fun decr where
    "decr [] \<longleftrightarrow> True"
  | "decr [_] \<longleftrightarrow> True"
  | "decr (x#y#xs) \<longleftrightarrow> x\<ge>y \<and> decr (y#xs)"

  lemma tki: "incr (take_incr xs)"
    apply2 (induction xs rule: take_incr.induct)
    apply auto
    apply (case_tac xs)
    apply auto
    done

  lemma tkd: "decr (take_decr xs)"
    apply2 (induction xs rule: take_decr.induct)
    apply auto
    apply (case_tac xs)
    apply auto
    done

  lemma icod: "incr (take xs) \<or> decr (take xs)"
    apply (cases xs rule: take.cases)
    apply (auto simp: tki tkd simp del: take_incr.simps take_decr.simps)
    done

  theorem cuts_incr_decr: "\<forall>c\<in>set (cuts xs). incr c \<or> decr c"
    apply2 (induction xs rule: cuts.induct)
    apply (subst cuts.simps)
    apply (auto simp: take2_def Let_def)
    using icod by blast

  subsubsection \<open>Property 3: Maximality\<close>
  text \<open>Specification of a cut that consists of maximal segments:
    The segements are non-empty, and for every two neighbouring segments,
    the first value of the last segment cannot be used to continue the first segment:
  \<close>
  fun maxi where
     "maxi [] \<longleftrightarrow> True"
   | "maxi [c] \<longleftrightarrow> c\<noteq>[]"
   | "maxi (c1#c2#cs) \<longleftrightarrow> (c1\<noteq>[] \<and> c2\<noteq>[] \<and> maxi (c2#cs) \<and> (
        incr c1 \<and> \<not>(last c1 < hd c2)
      \<or> decr c1 \<and> \<not>(last c1 \<ge> hd c2)
        ))"

  text \<open>Obviously, our specification implies that there are no
    empty segments\<close>
  lemma maxi_imp_non_empty: "maxi xs \<Longrightarrow> []\<notin>set xs"
    by (induction xs rule: maxi.induct) auto

  lemma tdconc': "xs\<noteq>[] \<Longrightarrow>
    \<exists>ys. xs = take_decr xs @ ys \<and> (ys\<noteq>[]
      \<longrightarrow> \<not>(last (take_decr xs) \<ge> hd ys))"
    apply2 (induction xs rule: take_decr.induct)
    apply auto
    apply (case_tac xs) apply (auto split: if_splits)
    done

  lemma ticonc': "xs\<noteq>[] \<Longrightarrow> \<exists>ys. xs = take_incr xs @ ys \<and> (ys\<noteq>[] \<longrightarrow> \<not>(last (take_incr xs) < hd ys))"
    apply2 (induction xs rule: take_incr.induct)
    apply auto
    apply (case_tac xs) apply (auto split: if_splits)
    done

  lemma take_conc': "xs\<noteq>[] \<Longrightarrow> \<exists>ys. xs = take xs@ys \<and> (ys\<noteq>[] \<longrightarrow> (
    take xs=take_incr xs \<and> \<not>(last (take_incr xs) < hd ys)
  \<or> take xs=take_decr xs \<and> \<not>(last (take_decr xs) \<ge> hd ys)
  ))"
    using tdconc' ticonc'
    apply (cases xs rule: take.cases)
    by auto

  lemma take_decr_non_empty:
    "take_decr xs \<noteq> []" if "xs \<noteq> []"
    using that
    apply (cases xs)
     apply auto
    subgoal for x ys
      apply (cases ys)
       apply (auto split: if_split_asm)
      done
    done

  lemma take_incr_non_empty:
    "take_incr xs \<noteq> []" if "xs \<noteq> []"
    using that
    apply (cases xs)
     apply auto
    subgoal for x ys
      apply (cases ys)
       apply (auto split: if_split_asm)
      done
    done

  lemma take_conc'': "xs\<noteq>[] \<Longrightarrow> \<exists>ys. xs = take xs@ys \<and> (ys\<noteq>[] \<longrightarrow> (
    incr (take xs) \<and> \<not>(last (take xs) < hd ys)
  \<or> decr (take xs) \<and> \<not>(last (take xs) \<ge> hd ys)
  ))"
    using tdconc' ticonc' tki tkd
    apply (cases xs rule: take.cases)
    apply auto
    apply (auto simp add: take_incr_non_empty)
    apply (simp add: take_decr_non_empty)
    apply (metis list.distinct(1) take_incr.simps(3))
    by (smt list.simps(3) take_decr.simps(3))

  lemma inv_cuts: "cuts xs = c#cs \<Longrightarrow> \<exists>ys. c=take xs \<and> xs=c@ys \<and> cs = cuts ys"
    apply (subst (asm) cuts.simps)
    apply (cases xs rule: cuts.cases)
    apply (auto split: if_splits simp: take2_def Let_def)
    by (metis append_eq_conv_conj take_conc)

  theorem maximal_cuts: "maxi (cuts xs)"
    apply2 (induction "cuts xs" arbitrary: xs rule: maxi.induct)
    subgoal by auto
    subgoal for c xs
      apply (drule sym; simp)
      apply (subst (asm) cuts.simps)
      apply (auto split: if_splits prod.splits simp: take2_def Let_def take_non_empty)
      done
    subgoal for c1 c2 cs xs
      apply (drule sym)
      apply simp
      apply (drule inv_cuts; clarsimp)
      apply auto
      subgoal by (metis cuts.simps list.distinct(1) take_non_empty)
      subgoal by (metis append.left_neutral inv_cuts not_Cons_self)
      subgoal using icod by blast
      subgoal by (metis
            Nil_is_append_conv cuts.simps hd_append2 inv_cuts list.distinct(1)
            same_append_eq take_conc'' take_non_empty)
      subgoal by (metis
            append_is_Nil_conv cuts.simps hd_append2 inv_cuts list.distinct(1)
            same_append_eq take_conc'' take_non_empty)
      done
    done

  subsubsection \<open>Equivalent Formulation Over Indexes\<close>
  text \<open>After the competition, we got the comment that a specification of
    monotonic sequences via indexes might be more readable.

    We show that our functional specification is equivalent to a
    specification over indexes.\<close>

  fun ii_induction where
    "ii_induction [] = ()"
  | "ii_induction [_] = ()"
  | "ii_induction (_#y#xs) = ii_induction (y#xs)"

  locale cnvSpec =
    fixes fP P
    assumes [simp]: "fP [] \<longleftrightarrow> True"
    assumes [simp]: "fP [x] \<longleftrightarrow> True"
    assumes [simp]: "fP (a#b#xs) \<longleftrightarrow> P a b \<and> fP (b#xs)"
  begin

    lemma idx_spec: "fP xs \<longleftrightarrow> (\<forall>i<length xs - 1. P (xs!i) (xs!Suc i))"
      apply2 (induction xs rule: ii_induction.induct)
      using less_Suc_eq_0_disj
      by auto

  end

  locale cnvSpec' =
    fixes fP P P'
    assumes [simp]: "fP [] \<longleftrightarrow> True"
    assumes [simp]: "fP [x] \<longleftrightarrow> P' x"
    assumes [simp]: "fP (a#b#xs) \<longleftrightarrow> P' a \<and> P' b \<and> P a b \<and> fP (b#xs)"
  begin

    lemma idx_spec: "fP xs \<longleftrightarrow> (\<forall>i<length xs. P' (xs!i)) \<and> (\<forall>i<length xs - 1. P (xs!i) (xs!Suc i))"
      apply2 (induction xs rule: ii_induction.induct)
      apply auto []
      apply auto []
      apply clarsimp
      by (smt less_Suc_eq_0_disj nth_Cons_0 nth_Cons_Suc)

  end

  interpretation INCR: cnvSpec incr "(<)"
    apply unfold_locales by auto

  interpretation DECR: cnvSpec decr "(\<ge>)"
    apply unfold_locales by auto

  interpretation MAXI: cnvSpec' maxi "\<lambda>c1 c2. ( (
        incr c1 \<and> \<not>(last c1 < hd c2)
      \<or> decr c1 \<and> \<not>(last c1 \<ge> hd c2)
        ))"
      "\<lambda>x. x \<noteq> []"
    apply unfold_locales by auto

  lemma incr_by_idx: "incr xs = (\<forall>i<length xs - 1. xs ! i < xs ! Suc i)"
    by (rule INCR.idx_spec)

  lemma decr_by_idx: "decr xs = (\<forall>i<length xs - 1. xs ! i \<ge> xs ! Suc i)"
    by (rule DECR.idx_spec)

  lemma maxi_by_idx: "maxi xs \<longleftrightarrow>
    (\<forall>i<length xs. xs ! i \<noteq> []) \<and>
    (\<forall>i<length xs - 1.
         incr (xs ! i) \<and> \<not> last (xs ! i) < hd (xs ! Suc i)
       \<or> decr (xs ! i) \<and> \<not> hd (xs ! Suc i) \<le> last (xs ! i)
    )"
    by (rule MAXI.idx_spec)

  theorem all_correct:
    "concat (cuts xs) = xs"
    "\<forall>c\<in>set (cuts xs). incr c \<or> decr c"
    "maxi (cuts xs)"
    "[] \<notin> set (cuts xs)"
    using cuts_incr_decr concat_cuts maximal_cuts
          maxi_imp_non_empty[OF maximal_cuts]
    by auto

end


(* Exercise 2.5.1
Define the datatype of binary trees:
datatype 'a tree = Tip | Node "'a tree" 'a "'a tree"

Define a function mirror that mirrors a binary tree by swapping subtrees recursively. Prove
lemma mirror_mirror: "mirror(mirror t) = t"

Define a function flatten that flattens a tree into a list by traversing it in
infix order. Prove
lemma "flatten(mirror t) = rev(flatten t)"
*)

theory BTree
  imports Main

begin

datatype 'a tree = Tip | Node "'a tree" 'a "'a tree"

(* datatype even_nat = Even_Zero | Even_Succ odd_nat and odd_nat = Odd_Succ even_nat
 *)

primrec mirror :: "'a tree \<Rightarrow> 'a tree" where
"mirror Tip = Tip" |
"mirror (Node leftTree val rightTree) = (Node (mirror rightTree) val (mirror leftTree))"

primrec flatten :: "'a tree \<Rightarrow> 'a list" where
"flatten Tip = []" |
"flatten (Node leftTree val rightTree) = ((flatten leftTree) @ [val] @ (flatten rightTree)) "

lemma mirror_mirror: "mirror(mirror t) = t"
  apply (induct)
   apply (auto)
  done

lemma "flatten(mirror t) = rev(flatten t)"
  apply (induct)
   apply (auto)
  done

definition "myTree = Node (Node Tip 2 Tip) (1::int) (Node Tip 3 Tip)"
value "flatten myTree"

end


theory Set_Relation
imports Main HOL.Real

begin

subsection \<open>set definition\<close>
definition Set0 :: "nat set"
  where "Set0 \<equiv> {0, 2, 4, 6}"

definition Set1 :: "nat set"
  where "Set1 \<equiv> {..<100}"

definition Set2 :: "nat set"
  where "Set2 \<equiv> {10..100}"

lemma "11 \<in> Set2" unfolding Set2_def by simp

definition Set3 :: "nat set"
  where "Set3 \<equiv> {n. n mod 2 = 0 \<and> n < 100}"

lemma "24 \<in> Set3" unfolding Set3_def by simp

definition Set4 :: "real set"
  where "Set4 \<equiv> {25.0 .. 125.0}"

lemma "25.0 \<in> Set4" unfolding Set4_def by simp

lemma "10 \<in> \<nat>" by simp
lemma "-10 \<in> \<int>" by simp
lemma "3 / 4 \<in> \<rat>" by simp

value "2 \<in> Set0"
value "5 \<in> Set0"
value "7 \<notin> Set0"
value "20 \<in> Set1"
value "101 \<in> Set1"

value "card Set0"
value "card Set1"
value "card Set2"

value "card {1::int,2,2,3}"

lemma "finite Set0"
  unfolding Set0_def by simp

lemma "finite Set1"
  unfolding Set1_def by simp

lemma "finite Set2"
  unfolding Set2_def by simp

lemma "finite Set3"
  unfolding Set3_def by simp

lemma "infinite Set4"
  unfolding Set4_def by simp

lemma "infinite S \<Longrightarrow> card S = 0"
  by simp

lemma "card {} = 0" by simp

datatype Element = a | b | c

value "a = b"
value "a = c"
value "b = c"

lemma "\<forall>x::Element. x = a \<or> x = b \<or> x = c" using Element.nchotomy by simp

lemma "a \<noteq> b \<and> a \<noteq> c \<and> b \<noteq> c" by simp

lemma lm1: "{x::Element. True} = {a, b, c}" using Element.nchotomy by auto

lemma lm2: "card {a, b, c} = 3" by auto

lemma "card {x::Element. True} = 3" using lm1 lm2 by simp

lemma "card (UNIV :: Element set) = 3" using lm1 lm2 by simp

lemma "infinite (UNIV :: int set)" using infinite_UNIV_int by simp

lemma "{} = {x. False}" by simp

lemma "UNIV = {x. True}" by simp

lemma "{0,2,4,6} = {2,4,6,0}" by auto

lemma "{0,2,4,6} = {2,4,4,6,6,0}" by auto

lemma "x\<in>A \<Longrightarrow> insert x A = A" by auto

definition Set5 :: "nat set"
  where "Set5 \<equiv> {1,2,3}"

definition Set6 :: "nat set"
  where "Set6 \<equiv> {1,2,3,4}"

lemma "Set5 \<subseteq> Set6" by (simp add: Set5_def Set6_def)

lemma "Set5 \<subseteq> Set5" by (simp add: Set5_def Set6_def)

lemma "{} \<subseteq> {}" by simp

lemma "UNIV \<subseteq> UNIV" by simp

lemma "{} \<subseteq> A" by simp

lemma "A \<subseteq> UNIV" by simp

lemma "Set5 \<subset> Set6" unfolding Set5_def Set6_def by auto

subsection \<open>set operation\<close>

abbreviation Set7 :: "nat set"
  where "Set7 \<equiv> {1,2,3,4,5}"

abbreviation Set8 :: "nat set"
  where "Set8 \<equiv> {4,5,6,7,8}"

value "Set7 \<inter> Set8"
value "Set7 \<union> Set8"
value "Set7 - Set8"
value "- Set7"

lemma "A \<times> B = {(x,y). x\<in>A \<and> y\<in>B}" by simp

abbreviation Set9 :: "nat set"
  where "Set9 \<equiv> {1,2,3}"

abbreviation Set10 :: "nat set"
  where "Set10 \<equiv> {4,5,6}"

value "Set9 \<times> Set10"
value "card (Set9 \<times> Set10)"

abbreviation Set11 :: "char list set"
  where "Set11 \<equiv> {''a'', ''b''}"

value "Set9 \<times> Set10 \<times> Set11"
value "card (Set9 \<times> Set10 \<times> Set11)"

value "Pow Set9"

subsection \<open>inductive set\<close>

inductive_set Even :: "int set"
  where zeroe: "0 \<in> Even" |
        plus2: "n \<in> Even \<Longrightarrow> n + 2 \<in> Even" |
        minus2: "n \<in> Even \<Longrightarrow> n - 2 \<in> Even"

lemma even_lm1: "x\<in>Even \<Longrightarrow> 2 dvd x"
  apply(erule Even.induct)
    apply simp
   apply (simp_all add:dvd_def)
   apply clarify
   apply (rule_tac x = "k + 1" in exI, simp)
  apply clarify
  by (rule_tac x = "k - 1" in exI, simp)

lemma "0 \<in> Even" using zeroe by simp
lemma "2 \<in> Even" using zeroe plus2 by fastforce
lemma "-2 \<in> Even" using zeroe minus2 by fastforce
lemma "1 \<notin> Even" using even_lm1 by fastforce

inductive_set string_set :: "string set"
  where nil_str: "Nil \<in> string_set" |
        cons_str: "\<lbrakk>x\<in>string_set\<rbrakk> \<Longrightarrow>chr#x\<in>string_set"

lemma "''abcd'' \<in> string_set"
  using nil_str cons_str by blast

inductive_set trancl :: "('a \<times> 'a) set \<Rightarrow> ('a \<times> 'a) set"
  for R :: "('a \<times> 'a) set"
where
  R_into_trancl: "(x, y) \<in> R \<Longrightarrow> (x, y) \<in> trancl R"
| R_trancl:      "(x, y) \<in> trancl R \<and> (y, z) \<in> R \<Longrightarrow> (x, z) \<in> trancl R"

term "trancl A"

definition "graph1 \<equiv> {(''v1'',''v2''),(''v2'',''v3''),(''v3'',''v4'')}"
lemma "trancl graph1 = graph1 \<union> {(''v1'',''v3''),(''v1'',''v4''),(''v2'',''v4'')}"
  using R_into_trancl R_trancl sorry

inductive_set even :: "nat set" and
               odd :: "nat set" where
  zero: "0 \<in> even" |
  EvenI: "n \<in> odd \<Longrightarrow> Suc n \<in> even" |
  OddI: "n \<in> even \<Longrightarrow> Suc n \<in> odd"

lemma even_lm2: "(x\<in>even \<longrightarrow> 2 dvd x) \<and> (x\<in>odd \<longrightarrow> 2 dvd (Suc x))"
  apply(rule even_odd.induct)
    apply simp
   apply (simp_all add:dvd_def)
   apply clarify
   by (rule_tac x = "Suc k" in exI, simp)

lemma "0 \<in> even" using zero by simp
lemma "2 \<in> even" using zero EvenI[of 1] OddI[of 0]
  by (metis Suc_1 numeral_1_eq_Suc_0 numerals(1))
lemma "1 \<in> odd" using zero OddI by fastforce

subsection \<open>relation\<close>

definition "Vset \<equiv> {''v1'',''v2'',''v3'',''v4''}"

value "Vset \<times> Vset"

value "graph1 \<subseteq> Vset \<times> Vset"

lemma "Domain R = {x. \<exists>y. (x,y)\<in>R}" by auto

lemma "Range R = {y. \<exists>x. (x,y)\<in>R}" by auto

value "Domain graph1"
value "Range graph1"
value "Field graph1"

lemma "Domain R = {x. \<exists>y. (x,y)\<in>R}" by auto
lemma "Range R = {y. \<exists>x. (x,y)\<in>R}" by auto

lemma "R \<subseteq> A \<times> B \<Longrightarrow> Domain R \<subseteq> A" by auto
lemma "R \<subseteq> A \<times> B \<Longrightarrow> Range R \<subseteq> B" by auto

lemma "A \<noteq> {} \<and> B \<noteq> {} \<Longrightarrow> Domain (A \<times> B) = A" by auto
lemma "A \<noteq> {} \<and> B \<noteq> {} \<Longrightarrow> Range (A \<times> B) = B" by auto

value "Id_on Vset"

value "total_on Vset graph1"

value "graph1\<inverse>"

definition "graph2 \<equiv> {(''v1'',''v1''),(''v2'',''v2''),(''v1'',''v3''),(''v2'',''v3''),(''v3'',''v4''),(''v4'',''v5'')}"

value "graph2 `` {''v1'',''v2''}"
value "graph2 `` {''v3'',''v4''}"

value "graph1"
value "graph2"
value "graph1 O graph2"

value "Id_on {''v1'',''v2'',''v3''}"

definition "ID = {(x,y). x = y}"
lemma "ID = Id"
  unfolding Id_def ID_def by auto

definition "Id_int = (Id :: (int \<times> int) set)"

definition "Id_real = (Id :: (real \<times> real) set)"

lemma "Id_on {x::int. True} = Id_int"
  unfolding ID_def Id_on_def Id_int_def by auto

lemma "R O Id = R" by auto
lemma "Id O R = R" by auto

lemma "total {(x::int,y). x < y}"
  apply(simp add: total_on_def)
  apply(rule allI)+
  apply(rule impI) by auto

lemma "total_on {1::int,2} {(1,1),(1,2)}"
  by (simp add:total_on_def)

lemma "total_on {1::int,2} {(1,1),(1,2),(2,1)}"
  by (simp add:total_on_def)

lemma "total_on {1::int,2} {(1,1),(1,2),(2,2)}"
  by (simp add:total_on_def)

lemma "total_on {1::int,2} {(1,2),(2,2)}"
  by (simp add:total_on_def)

lemma "total_on {1::int,2} ({1,2}\<times>{1,2})"
  by (simp add:total_on_def)

lemma "refl_on {1::int,2} {(1,1),(2,2)}"
  by (simp add:refl_on_def)

lemma "refl_on {1::int,2} {(1,1),(2,2),(1,2)}"
  by (simp add:refl_on_def)

value "refl_on {1::int,2} {(1,1),(2,2),(1,2)}"

lemma "refl {(x::int,y). x = y}"
  by (simp add:refl_on_def)

lemma "refl {(x::int,y). x \<le> y}"
  by (simp add:refl_on_def)

lemma "refl {(x::int,y). x < y} = False"
  by (simp add:refl_on_def)

lemma "refl Id"
  using refl_Id by simp

lemma "sym {(1,1),(2,2)}"
  by (simp add: sym_def)

lemma "sym {(x::int,y). x \<noteq> y}"
  by (simp add: sym_def)

lemma "sym {(x::int,y). x \<le> y} = False"
  apply (simp add: sym_def)
  apply(rule_tac x = 1 in exI)
  apply(rule_tac x = 2 in exI) by simp

lemma "sym {(x::int,y). x = y}"
  by (simp add: sym_def)

lemma "sym Id"
  using sym_Id by simp

value "trans {(1::int,2),(2,3),(1,3)}"

lemma "trans {(x::int,y). x < y}"
  by (simp add:trans_def)

lemma "trans {(x::int,y). x \<le> y}"
  by (simp add:trans_def)

lemma "trans {(x::int,y). x = y}"
  by (simp add:trans_def)

lemma "trans {(x::int,y). x \<noteq> y} = False"
  apply (simp add:trans_def)
  apply (rule_tac x = 1 in exI)
  apply (rule_tac x = 2 in exI)
  by simp

lemma "trans Id"
  by (simp add:trans_def)

lemma "refl {} = False"
  unfolding refl_on_def by auto

lemma "sym {} = True"
  unfolding sym_def by auto

lemma "trans {} = True"
  unfolding trans_def by auto

lemma "refl UNIV = True"
  unfolding refl_on_def by auto

lemma "sym UNIV = True"
  unfolding sym_def by auto

lemma "trans UNIV = True"
  unfolding trans_def by auto

definition equiv_on :: "'a set \<Rightarrow> ('a \<times> 'a) set \<Rightarrow> bool"
  where "equiv_on A r \<equiv> refl_on A r \<and> sym r \<and> trans r"

definition equiv :: "('a \<times> 'a) set \<Rightarrow> bool"
  where "equiv r \<equiv> equiv_on UNIV r"

lemma "equiv_on A (A\<times>A)"
  unfolding equiv_on_def refl_on_def sym_def trans_def by auto

lemma "equiv_on A (Id_on A)"
  unfolding equiv_on_def refl_on_def sym_def trans_def by auto

lemma "equiv UNIV = True"
  unfolding equiv_def equiv_on_def refl_on_def sym_def trans_def by auto

lemma "equiv Id = True"
  unfolding equiv_def equiv_on_def refl_on_def sym_def trans_def by auto

lemma "refl {} = False"
  unfolding refl_on_def by auto
lemma "sym {} = True"
  unfolding sym_def by auto
lemma "trans {} = True"
  by auto

end


(*  Title:      HOL/ex/Functions.thy
    Author:     Alexander Krauss, TU Muenchen
*)

section \<open>Examples of function definitions\<close>

theory Functions
imports Main "HOL-Library.Monad_Syntax"
begin

subsection \<open>Very basic\<close>

fun fib :: "nat \<Rightarrow> nat"
where
  "fib 0 = 1"
| "fib (Suc 0) = 1"
| "fib (Suc (Suc n)) = fib n + fib (Suc n)"

text \<open>Partial simp and induction rules:\<close>
thm fib.psimps
thm fib.pinduct

text \<open>There is also a cases rule to distinguish cases along the definition:\<close>
thm fib.cases

text \<open>Total simp and induction rules:\<close>
thm fib.simps
thm fib.induct

text \<open>Elimination rules:\<close>
thm fib.elims

subsection \<open>Currying\<close>

fun add
where
  "add 0 y = y"
| "add (Suc x) y = Suc (add x y)"

thm add.simps
thm add.induct  \<comment> \<open>Note the curried induction predicate\<close>

subsection \<open>Nested recursion\<close>

function nz
where
  "nz 0 = 0"
| "nz (Suc x) = nz (nz x)"
by pat_completeness auto

lemma nz_is_zero:  \<comment> \<open>A lemma we need to prove termination\<close>
  assumes trm: "nz_dom x"
  shows "nz x = 0"
using trm
by induct (auto simp: nz.psimps)

termination nz
  by (relation "less_than") (auto simp:nz_is_zero)

thm nz.simps
thm nz.induct

subsubsection \<open>Here comes McCarthy's 91-function\<close>

function f91 :: "nat \<Rightarrow> nat"
where
  "f91 n = (if 100 < n then n - 10 else f91 (f91 (n + 11)))"
by pat_completeness auto

text \<open>Prove a lemma before attempting a termination proof:\<close>
lemma f91_estimate:
  assumes trm: "f91_dom n"
  shows "n < f91 n + 11"
using trm by induct (auto simp: f91.psimps)

termination
proof
  let ?R = "measure (\<lambda>x. 101 - x)"
  show "wf ?R" ..

  fix n :: nat
  assume "\<not> 100 < n"  \<comment> \<open>Inner call\<close>
  then show "(n + 11, n) \<in> ?R" by simp

  assume inner_trm: "f91_dom (n + 11)"  \<comment> \<open>Outer call\<close>
  with f91_estimate have "n + 11 < f91 (n + 11) + 11" .
  with \<open>\<not> 100 < n\<close> show "(f91 (n + 11), n) \<in> ?R" by simp
qed

text \<open>Now trivial (even though it does not belong here):\<close>
lemma "f91 n = (if 100 < n then n - 10 else 91)"
  by (induct n rule: f91.induct) auto

subsubsection \<open>Here comes Takeuchi's function\<close>

definition tak_m1 where "tak_m1 = (\<lambda>(x,y,z). if x \<le> y then 0 else 1)"
definition tak_m2 where "tak_m2 = (\<lambda>(x,y,z). nat (Max {x, y, z} - Min {x, y, z}))"
definition tak_m3 where "tak_m3 = (\<lambda>(x,y,z). nat (x - Min {x, y, z}))"

function tak :: "int \<Rightarrow> int \<Rightarrow> int \<Rightarrow> int" where
  "tak x y z = (if x \<le> y then y else tak (tak (x-1) y z) (tak (y-1) z x) (tak (z-1) x y))"
  by auto

lemma tak_pcorrect:
  "tak_dom (x, y, z) \<Longrightarrow> tak x y z = (if x \<le> y then y else if y \<le> z then z else x)"
  by (induction x y z rule: tak.pinduct) (auto simp: tak.psimps)

termination
  by (relation "tak_m1 <*mlex*> tak_m2 <*mlex*> tak_m3 <*mlex*> {}")
     (auto simp: mlex_iff wf_mlex tak_pcorrect tak_m1_def tak_m2_def tak_m3_def min_def max_def)

theorem tak_correct: "tak x y z = (if x \<le> y then y else if y \<le> z then z else x)"
  by (induction x y z rule: tak.induct) auto

subsection \<open>More general patterns\<close>

subsubsection \<open>Overlapping patterns\<close>

text \<open>
  Currently, patterns must always be compatible with each other, since
  no automatic splitting takes place. But the following definition of
  GCD is OK, although patterns overlap:
\<close>

fun gcd2 :: "nat \<Rightarrow> nat \<Rightarrow> nat"
where
  "gcd2 x 0 = x"
| "gcd2 0 y = y"
| "gcd2 (Suc x) (Suc y) = (if x < y then gcd2 (Suc x) (y - x)
                                    else gcd2 (x - y) (Suc y))"

thm gcd2.simps
thm gcd2.induct

subsubsection \<open>Guards\<close>

text \<open>We can reformulate the above example using guarded patterns:\<close>

function gcd3 :: "nat \<Rightarrow> nat \<Rightarrow> nat"
where
  "gcd3 x 0 = x"
| "gcd3 0 y = y"
| "gcd3 (Suc x) (Suc y) = gcd3 (Suc x) (y - x)" if "x < y"
| "gcd3 (Suc x) (Suc y) = gcd3 (x - y) (Suc y)" if "\<not> x < y"
  apply (case_tac x, case_tac a, auto)
  apply (case_tac ba, auto)
  done
termination by lexicographic_order

thm gcd3.simps
thm gcd3.induct

text \<open>General patterns allow even strange definitions:\<close>

function ev :: "nat \<Rightarrow> bool"
where
  "ev (2 * n) = True"
| "ev (2 * n + 1) = False"
proof -  \<comment> \<open>completeness is more difficult here \dots\<close>
  fix P :: bool
  fix x :: nat
  assume c1: "\<And>n. x = 2 * n \<Longrightarrow> P"
    and c2: "\<And>n. x = 2 * n + 1 \<Longrightarrow> P"
  have divmod: "x = 2 * (x div 2) + (x mod 2)" by auto
  show P
  proof (cases "x mod 2 = 0")
    case True
    with divmod have "x = 2 * (x div 2)" by simp
    with c1 show "P" .
  next
    case False
    then have "x mod 2 = 1" by simp
    with divmod have "x = 2 * (x div 2) + 1" by simp
    with c2 show "P" .
  qed
qed presburger+  \<comment> \<open>solve compatibility with presburger\<close>
termination by lexicographic_order

thm ev.simps
thm ev.induct
thm ev.cases

subsection \<open>Mutual Recursion\<close>

fun evn od :: "nat \<Rightarrow> bool"
where
  "evn 0 = True"
| "od 0 = False"
| "evn (Suc n) = od n"
| "od (Suc n) = evn n"

thm evn.simps
thm od.simps

thm evn_od.induct
thm evn_od.termination

thm evn.elims
thm od.elims

subsection \<open>Definitions in local contexts\<close>

locale my_monoid =
  fixes opr :: "'a \<Rightarrow> 'a \<Rightarrow> 'a"
    and un :: "'a"
  assumes assoc: "opr (opr x y) z = opr x (opr y z)"
    and lunit: "opr un x = x"
    and runit: "opr x un = x"
begin

fun foldR :: "'a list \<Rightarrow> 'a"
where
  "foldR [] = un"
| "foldR (x # xs) = opr x (foldR xs)"

fun foldL :: "'a list \<Rightarrow> 'a"
where
  "foldL [] = un"
| "foldL [x] = x"
| "foldL (x # y # ys) = foldL (opr x y # ys)"

thm foldL.simps

lemma foldR_foldL: "foldR xs = foldL xs"
  by (induct xs rule: foldL.induct) (auto simp:lunit runit assoc)

thm foldR_foldL

end

thm my_monoid.foldL.simps
thm my_monoid.foldR_foldL

subsection \<open>\<open>fun_cases\<close>\<close>

subsubsection \<open>Predecessor\<close>

fun pred :: "nat \<Rightarrow> nat"
where
  "pred 0 = 0"
| "pred (Suc n) = n"

thm pred.elims

lemma
  assumes "pred x = y"
  obtains "x = 0" "y = 0" | "n" where "x = Suc n" "y = n"
  by (fact pred.elims[OF assms])

text \<open>If the predecessor of a number is 0, that number must be 0 or 1.\<close>

fun_cases pred0E[elim]: "pred n = 0"

lemma "pred n = 0 \<Longrightarrow> n = 0 \<or> n = Suc 0"
  by (erule pred0E) metis+

text \<open>
  Other expressions on the right-hand side also work, but whether the
  generated rule is useful depends on how well the simplifier can
  simplify it. This example works well:
\<close>

fun_cases pred42E[elim]: "pred n = 42"

lemma "pred n = 42 \<Longrightarrow> n = 43"
  by (erule pred42E)

subsubsection \<open>List to option\<close>

fun list_to_option :: "'a list \<Rightarrow> 'a option"
where
  "list_to_option [x] = Some x"
| "list_to_option _ = None"

fun_cases list_to_option_NoneE: "list_to_option xs = None"
  and list_to_option_SomeE: "list_to_option xs = Some x"

lemma "list_to_option xs = Some y \<Longrightarrow> xs = [y]"
  by (erule list_to_option_SomeE)

subsubsection \<open>Boolean Functions\<close>

fun xor :: "bool \<Rightarrow> bool \<Rightarrow> bool"
where
  "xor False False = False"
| "xor True True = False"
| "xor _ _ = True"

thm xor.elims

text \<open>
  \<open>fun_cases\<close> does not only recognise function equations, but also works with
  functions that return a boolean, e.g.:
\<close>

fun_cases xor_TrueE: "xor a b" and xor_FalseE: "\<not>xor a b"
print_theorems

subsubsection \<open>Many parameters\<close>

fun sum4 :: "nat \<Rightarrow> nat \<Rightarrow> nat \<Rightarrow> nat \<Rightarrow> nat"
  where "sum4 a b c d = a + b + c + d"

fun_cases sum40E: "sum4 a b c d = 0"

lemma "sum4 a b c d = 0 \<Longrightarrow> a = 0"
  by (erule sum40E)

subsection \<open>Partial Function Definitions\<close>

text \<open>Partial functions in the option monad:\<close>

partial_function (option)
  collatz :: "nat \<Rightarrow> nat list option"
where
  "collatz n =
    (if n \<le> 1 then Some [n]
     else if even n
       then do { ns \<leftarrow> collatz (n div 2); Some (n # ns) }
       else do { ns \<leftarrow> collatz (3 * n + 1);  Some (n # ns)})"

declare collatz.simps[code]
value "collatz 23"

text \<open>Tail-recursive functions:\<close>

partial_function (tailrec) fixpoint :: "('a \<Rightarrow> 'a) \<Rightarrow> 'a \<Rightarrow> 'a"
where
  "fixpoint f x = (if f x = x then x else fixpoint f (f x))"

subsection \<open>Regression tests\<close>

text \<open>
  The following examples mainly serve as tests for the
  function package.
\<close>

fun listlen :: "'a list \<Rightarrow> nat"
where
  "listlen [] = 0"
| "listlen (x#xs) = Suc (listlen xs)"

subsubsection \<open>Context recursion\<close>

fun f :: "nat \<Rightarrow> nat"
where
  zero: "f 0 = 0"
| succ: "f (Suc n) = (if f n = 0 then 0 else f n)"

subsubsection \<open>A combination of context and nested recursion\<close>

function h :: "nat \<Rightarrow> nat"
where
  "h 0 = 0"
| "h (Suc n) = (if h n = 0 then h (h n) else h n)"
by pat_completeness auto

subsubsection \<open>Context, but no recursive call\<close>

fun i :: "nat \<Rightarrow> nat"
where
  "i 0 = 0"
| "i (Suc n) = (if n = 0 then 0 else i n)"

subsubsection \<open>Tupled nested recursion\<close>

fun fa :: "nat \<Rightarrow> nat \<Rightarrow> nat"
where
  "fa 0 y = 0"
| "fa (Suc n) y = (if fa n y = 0 then 0 else fa n y)"

subsubsection \<open>Let\<close>

fun j :: "nat \<Rightarrow> nat"
where
  "j 0 = 0"
| "j (Suc n) = (let u = n in Suc (j u))"

text \<open>There were some problems with fresh names \dots\<close>
function  k :: "nat \<Rightarrow> nat"
where
  "k x = (let a = x; b = x in k x)"
  by pat_completeness auto

function f2 :: "(nat \<times> nat) \<Rightarrow> (nat \<times> nat)"
where
  "f2 p = (let (x,y) = p in f2 (y,x))"
  by pat_completeness auto

subsubsection \<open>Abbreviations\<close>

fun f3 :: "'a set \<Rightarrow> bool"
where
  "f3 x = finite x"

subsubsection \<open>Simple Higher-Order Recursion\<close>

datatype 'a tree = Leaf 'a | Branch "'a tree list"

fun treemap :: "('a \<Rightarrow> 'a) \<Rightarrow> 'a tree \<Rightarrow> 'a tree"
where
  "treemap fn (Leaf n) = (Leaf (fn n))"
| "treemap fn (Branch l) = (Branch (map (treemap fn) l))"

fun tinc :: "nat tree \<Rightarrow> nat tree"
where
  "tinc (Leaf n) = Leaf (Suc n)"
| "tinc (Branch l) = Branch (map tinc l)"

fun testcase :: "'a tree \<Rightarrow> 'a list"
where
  "testcase (Leaf a) = [a]"
| "testcase (Branch x) =
    (let xs = concat (map testcase x);
         ys = concat (map testcase x) in
     xs @ ys)"

subsubsection \<open>Pattern matching on records\<close>

record point =
  Xcoord :: int
  Ycoord :: int

function swp :: "point \<Rightarrow> point"
where
  "swp \<lparr> Xcoord = x, Ycoord = y \<rparr> = \<lparr> Xcoord = y, Ycoord = x \<rparr>"
proof -
  fix P x
  assume "\<And>xa y. x = \<lparr>Xcoord = xa, Ycoord = y\<rparr> \<Longrightarrow> P"
  then show P by (cases x)
qed auto
termination by rule auto

subsubsection \<open>The diagonal function\<close>

fun diag :: "bool \<Rightarrow> bool \<Rightarrow> bool \<Rightarrow> nat"
where
  "diag x True False = 1"
| "diag False y True = 2"
| "diag True False z = 3"
| "diag True True True = 4"
| "diag False False False = 5"

subsubsection \<open>Many equations (quadratic blowup)\<close>

datatype DT =
  A | B | C | D | E | F | G | H | I | J | K | L | M | N | P
| Q | R | S | T | U | V

fun big :: "DT \<Rightarrow> nat"
where
  "big A = 0"
| "big B = 0"
| "big C = 0"
| "big D = 0"
| "big E = 0"
| "big F = 0"
| "big G = 0"
| "big H = 0"
| "big I = 0"
| "big J = 0"
| "big K = 0"
| "big L = 0"
| "big M = 0"
| "big N = 0"
| "big P = 0"
| "big Q = 0"
| "big R = 0"
| "big S = 0"
| "big T = 0"
| "big U = 0"
| "big V = 0"

subsubsection \<open>Automatic pattern splitting\<close>

fun f4 :: "nat \<Rightarrow> nat \<Rightarrow> bool"
where
  "f4 0 0 = True"
| "f4 _ _ = False"

subsubsection \<open>Polymorphic partial-function\<close>

partial_function (option) f5 :: "'a list \<Rightarrow> 'a option"
where
  "f5 x = f5 x"

end