(*  Title:      HOL/Fields.thy
    Author:     Gertrud Bauer
    Author:     Steven Obua
    Author:     Tobias Nipkow
    Author:     Lawrence C Paulson
    Author:     Markus Wenzel
    Author:     Jeremy Avigad
*)

section \<open>Fields\<close>

theory Fields
imports Nat
begin

context idom
begin

lemma inj_mult_left [simp]: \<open>inj ((*) a) \<longleftrightarrow> a \<noteq> 0\<close> (is \<open>?P \<longleftrightarrow> ?Q\<close>)
proof
  assume ?P
  show ?Q
  proof
    assume \<open>a = 0\<close>
    with \<open>?P\<close> have "inj ((*) 0)"
      by simp
    moreover have "0 * 0 = 0 * 1"
      by simp
    ultimately have "0 = 1"
      by (rule injD)
    then show False
      by simp
  qed
next
  assume ?Q then show ?P
    by (auto intro: injI)
qed

end

subsection \<open>Division rings\<close>

text \<open>
  A division ring is like a field, but without the commutativity requirement.
\<close>

class inverse = divide +
  fixes inverse :: "'a \<Rightarrow> 'a"
begin

abbreviation inverse_divide :: "'a \<Rightarrow> 'a \<Rightarrow> 'a"  (infixl "'/" 70)
where
  "inverse_divide \<equiv> divide"

end

text \<open>Setup for linear arithmetic prover\<close>

ML_file \<open>~~/src/Provers/Arith/fast_lin_arith.ML\<close>
ML_file \<open>Tools/lin_arith.ML\<close>
setup \<open>Lin_Arith.global_setup\<close>
declaration \<open>K (
  Lin_Arith.init_arith_data
  #> Lin_Arith.add_discrete_type \<^type_name>\<open>nat\<close>
  #> Lin_Arith.add_lessD @{thm Suc_leI}
  #> Lin_Arith.add_simps @{thms simp_thms ring_distribs if_True if_False
      minus_diff_eq
      add_0_left add_0_right order_less_irrefl
      zero_neq_one zero_less_one zero_le_one
      zero_neq_one [THEN not_sym] not_one_le_zero not_one_less_zero
      add_Suc add_Suc_right nat.inject
      Suc_le_mono Suc_less_eq Zero_not_Suc
      Suc_not_Zero le_0_eq One_nat_def}
  #> Lin_Arith.add_simprocs [\<^simproc>\<open>group_cancel_add\<close>, \<^simproc>\<open>group_cancel_diff\<close>,
      \<^simproc>\<open>group_cancel_eq\<close>, \<^simproc>\<open>group_cancel_le\<close>,
      \<^simproc>\<open>group_cancel_less\<close>,
      \<^simproc>\<open>nateq_cancel_sums\<close>,\<^simproc>\<open>natless_cancel_sums\<close>,
      \<^simproc>\<open>natle_cancel_sums\<close>])\<close>

simproc_setup fast_arith_nat ("(m::nat) < n" | "(m::nat) \<le> n" | "(m::nat) = n") =
  \<open>K Lin_Arith.simproc\<close> \<comment> \<open>Because of this simproc, the arithmetic solver is
   really only useful to detect inconsistencies among the premises for subgoals which are
   \<^emph>\<open>not\<close> themselves (in)equalities, because the latter activate
   \<^text>\<open>fast_nat_arith_simproc\<close> anyway. However, it seems cheaper to activate the
   solver all the time rather than add the additional check.\<close>

lemmas [arith_split] = nat_diff_split split_min split_max

text\<open>Lemmas \<open>divide_simps\<close> move division to the outside and eliminates them on (in)equalities.\<close>

named_theorems divide_simps "rewrite rules to eliminate divisions"

class division_ring = ring_1 + inverse +
  assumes left_inverse [simp]:  "a \<noteq> 0 \<Longrightarrow> inverse a * a = 1"
  assumes right_inverse [simp]: "a \<noteq> 0 \<Longrightarrow> a * inverse a = 1"
  assumes divide_inverse: "a / b = a * inverse b"
  assumes inverse_zero [simp]: "inverse 0 = 0"
begin

subclass ring_1_no_zero_divisors
proof
  fix a b :: 'a
  assume a: "a \<noteq> 0" and b: "b \<noteq> 0"
  show "a * b \<noteq> 0"
  proof
    assume ab: "a * b = 0"
    hence "0 = inverse a * (a * b) * inverse b" by simp
    also have "\<dots> = (inverse a * a) * (b * inverse b)"
      by (simp only: mult.assoc)
    also have "\<dots> = 1" using a b by simp
    finally show False by simp
  qed
qed

lemma nonzero_imp_inverse_nonzero:
  "a \<noteq> 0 \<Longrightarrow> inverse a \<noteq> 0"
proof
  assume ianz: "inverse a = 0"
  assume "a \<noteq> 0"
  hence "1 = a * inverse a" by simp
  also have "... = 0" by (simp add: ianz)
  finally have "1 = 0" .
  thus False by (simp add: eq_commute)
qed

lemma inverse_zero_imp_zero:
  assumes "inverse a = 0" shows "a = 0"
proof (rule ccontr)
  assume "a \<noteq> 0"
  then have "inverse a \<noteq> 0"
    by (simp add: nonzero_imp_inverse_nonzero)
  with assms show False
    by auto
qed

lemma inverse_unique:
  assumes ab: "a * b = 1"
  shows "inverse a = b"
proof -
  have "a \<noteq> 0" using ab by (cases "a = 0") simp_all
  moreover have "inverse a * (a * b) = inverse a" by (simp add: ab)
  ultimately show ?thesis by (simp add: mult.assoc [symmetric])
qed

lemma nonzero_inverse_minus_eq:
  "a \<noteq> 0 \<Longrightarrow> inverse (- a) = - inverse a"
by (rule inverse_unique) simp

lemma nonzero_inverse_inverse_eq:
  "a \<noteq> 0 \<Longrightarrow> inverse (inverse a) = a"
by (rule inverse_unique) simp

lemma nonzero_inverse_eq_imp_eq:
  assumes "inverse a = inverse b" and "a \<noteq> 0" and "b \<noteq> 0"
  shows "a = b"
proof -
  from \<open>inverse a = inverse b\<close>
  have "inverse (inverse a) = inverse (inverse b)" by (rule arg_cong)
  with \<open>a \<noteq> 0\<close> and \<open>b \<noteq> 0\<close> show "a = b"
    by (simp add: nonzero_inverse_inverse_eq)
qed

lemma inverse_1 [simp]: "inverse 1 = 1"
by (rule inverse_unique) simp

lemma nonzero_inverse_mult_distrib:
  assumes "a \<noteq> 0" and "b \<noteq> 0"
  shows "inverse (a * b) = inverse b * inverse a"
proof -
  have "a * (b * inverse b) * inverse a = 1" using assms by simp
  hence "a * b * (inverse b * inverse a) = 1" by (simp only: mult.assoc)
  thus ?thesis by (rule inverse_unique)
qed

lemma division_ring_inverse_add:
  "a \<noteq> 0 \<Longrightarrow> b \<noteq> 0 \<Longrightarrow> inverse a + inverse b = inverse a * (a + b) * inverse b"
by (simp add: algebra_simps)

lemma division_ring_inverse_diff:
  "a \<noteq> 0 \<Longrightarrow> b \<noteq> 0 \<Longrightarrow> inverse a - inverse b = inverse a * (b - a) * inverse b"
by (simp add: algebra_simps)

lemma right_inverse_eq: "b \<noteq> 0 \<Longrightarrow> a / b = 1 \<longleftrightarrow> a = b"
proof
  assume neq: "b \<noteq> 0"
  {
    hence "a = (a / b) * b" by (simp add: divide_inverse mult.assoc)
    also assume "a / b = 1"
    finally show "a = b" by simp
  next
    assume "a = b"
    with neq show "a / b = 1" by (simp add: divide_inverse)
  }
qed

lemma nonzero_inverse_eq_divide: "a \<noteq> 0 \<Longrightarrow> inverse a = 1 / a"
by (simp add: divide_inverse)

lemma divide_self [simp]: "a \<noteq> 0 \<Longrightarrow> a / a = 1"
by (simp add: divide_inverse)

lemma inverse_eq_divide [field_simps, field_split_simps, divide_simps]: "inverse a = 1 / a"
by (simp add: divide_inverse)

lemma add_divide_distrib: "(a+b) / c = a/c + b/c"
by (simp add: divide_inverse algebra_simps)

lemma times_divide_eq_right [simp]: "a * (b / c) = (a * b) / c"
  by (simp add: divide_inverse mult.assoc)

lemma minus_divide_left: "- (a / b) = (-a) / b"
  by (simp add: divide_inverse)

lemma nonzero_minus_divide_right: "b \<noteq> 0 \<Longrightarrow> - (a / b) = a / (- b)"
  by (simp add: divide_inverse nonzero_inverse_minus_eq)

lemma nonzero_minus_divide_divide: "b \<noteq> 0 \<Longrightarrow> (-a) / (-b) = a / b"
  by (simp add: divide_inverse nonzero_inverse_minus_eq)

lemma divide_minus_left [simp]: "(-a) / b = - (a / b)"
  by (simp add: divide_inverse)

lemma diff_divide_distrib: "(a - b) / c = a / c - b / c"
  using add_divide_distrib [of a "- b" c] by simp

lemma nonzero_eq_divide_eq [field_simps]: "c \<noteq> 0 \<Longrightarrow> a = b / c \<longleftrightarrow> a * c = b"
proof -
  assume [simp]: "c \<noteq> 0"
  have "a = b / c \<longleftrightarrow> a * c = (b / c) * c" by simp
  also have "... \<longleftrightarrow> a * c = b" by (simp add: divide_inverse mult.assoc)
  finally show ?thesis .
qed

lemma nonzero_divide_eq_eq [field_simps]: "c \<noteq> 0 \<Longrightarrow> b / c = a \<longleftrightarrow> b = a * c"
proof -
  assume [simp]: "c \<noteq> 0"
  have "b / c = a \<longleftrightarrow> (b / c) * c = a * c" by simp
  also have "... \<longleftrightarrow> b = a * c" by (simp add: divide_inverse mult.assoc)
  finally show ?thesis .
qed

lemma nonzero_neg_divide_eq_eq [field_simps]: "b \<noteq> 0 \<Longrightarrow> - (a / b) = c \<longleftrightarrow> - a = c * b"
  using nonzero_divide_eq_eq[of b "-a" c] by simp

lemma nonzero_neg_divide_eq_eq2 [field_simps]: "b \<noteq> 0 \<Longrightarrow> c = - (a / b) \<longleftrightarrow> c * b = - a"
  using nonzero_neg_divide_eq_eq[of b a c] by auto

lemma divide_eq_imp: "c \<noteq> 0 \<Longrightarrow> b = a * c \<Longrightarrow> b / c = a"
  by (simp add: divide_inverse mult.assoc)

lemma eq_divide_imp: "c \<noteq> 0 \<Longrightarrow> a * c = b \<Longrightarrow> a = b / c"
  by (drule sym) (simp add: divide_inverse mult.assoc)

lemma add_divide_eq_iff [field_simps]:
  "z \<noteq> 0 \<Longrightarrow> x + y / z = (x * z + y) / z"
  by (simp add: add_divide_distrib nonzero_eq_divide_eq)

lemma divide_add_eq_iff [field_simps]:
  "z \<noteq> 0 \<Longrightarrow> x / z + y = (x + y * z) / z"
  by (simp add: add_divide_distrib nonzero_eq_divide_eq)

lemma diff_divide_eq_iff [field_simps]:
  "z \<noteq> 0 \<Longrightarrow> x - y / z = (x * z - y) / z"
  by (simp add: diff_divide_distrib nonzero_eq_divide_eq eq_diff_eq)

lemma minus_divide_add_eq_iff [field_simps]:
  "z \<noteq> 0 \<Longrightarrow> - (x / z) + y = (- x + y * z) / z"
  by (simp add: add_divide_distrib diff_divide_eq_iff)

lemma divide_diff_eq_iff [field_simps]:
  "z \<noteq> 0 \<Longrightarrow> x / z - y = (x - y * z) / z"
  by (simp add: field_simps)

lemma minus_divide_diff_eq_iff [field_simps]:
  "z \<noteq> 0 \<Longrightarrow> - (x / z) - y = (- x - y * z) / z"
  by (simp add: divide_diff_eq_iff[symmetric])

lemma division_ring_divide_zero [simp]:
  "a / 0 = 0"
  by (simp add: divide_inverse)

lemma divide_self_if [simp]:
  "a / a = (if a = 0 then 0 else 1)"
  by simp

lemma inverse_nonzero_iff_nonzero [simp]:
  "inverse a = 0 \<longleftrightarrow> a = 0"
  by rule (fact inverse_zero_imp_zero, simp)

lemma inverse_minus_eq [simp]:
  "inverse (- a) = - inverse a"
proof cases
  assume "a=0" thus ?thesis by simp
next
  assume "a\<noteq>0"
  thus ?thesis by (simp add: nonzero_inverse_minus_eq)
qed

lemma inverse_inverse_eq [simp]:
  "inverse (inverse a) = a"
proof cases
  assume "a=0" thus ?thesis by simp
next
  assume "a\<noteq>0"
  thus ?thesis by (simp add: nonzero_inverse_inverse_eq)
qed

lemma inverse_eq_imp_eq:
  "inverse a = inverse b \<Longrightarrow> a = b"
  by (drule arg_cong [where f="inverse"], simp)

lemma inverse_eq_iff_eq [simp]:
  "inverse a = inverse b \<longleftrightarrow> a = b"
  by (force dest!: inverse_eq_imp_eq)

lemma mult_commute_imp_mult_inverse_commute:
  assumes "y * x = x * y"
  shows   "inverse y * x = x * inverse y"
proof (cases "y=0")
  case False
  hence "x * inverse y = inverse y * y * x * inverse y"
    by simp
  also have "\<dots> = inverse y * (x * y * inverse y)"
    by (simp add: mult.assoc assms)
  finally show ?thesis by (simp add: mult.assoc False)
qed simp

lemmas mult_inverse_of_nat_commute =
  mult_commute_imp_mult_inverse_commute[OF mult_of_nat_commute]

lemma divide_divide_eq_left':
  "(a / b) / c = a / (c * b)"
  by (cases "b = 0 \<or> c = 0")
     (auto simp: divide_inverse mult.assoc nonzero_inverse_mult_distrib)

lemma add_divide_eq_if_simps [field_split_simps, divide_simps]:
    "a + b / z = (if z = 0 then a else (a * z + b) / z)"
    "a / z + b = (if z = 0 then b else (a + b * z) / z)"
    "- (a / z) + b = (if z = 0 then b else (-a + b * z) / z)"
    "a - b / z = (if z = 0 then a else (a * z - b) / z)"
    "a / z - b = (if z = 0 then -b else (a - b * z) / z)"
    "- (a / z) - b = (if z = 0 then -b else (- a - b * z) / z)"
  by (simp_all add: add_divide_eq_iff divide_add_eq_iff diff_divide_eq_iff divide_diff_eq_iff
      minus_divide_diff_eq_iff)

lemma [field_split_simps, divide_simps]:
  shows divide_eq_eq: "b / c = a \<longleftrightarrow> (if c \<noteq> 0 then b = a * c else a = 0)"
    and eq_divide_eq: "a = b / c \<longleftrightarrow> (if c \<noteq> 0 then a * c = b else a = 0)"
    and minus_divide_eq_eq: "- (b / c) = a \<longleftrightarrow> (if c \<noteq> 0 then - b = a * c else a = 0)"
    and eq_minus_divide_eq: "a = - (b / c) \<longleftrightarrow> (if c \<noteq> 0 then a * c = - b else a = 0)"
  by (auto simp add:  field_simps)

end

subsection \<open>Fields\<close>

class field = comm_ring_1 + inverse +
  assumes field_inverse: "a \<noteq> 0 \<Longrightarrow> inverse a * a = 1"
  assumes field_divide_inverse: "a / b = a * inverse b"
  assumes field_inverse_zero: "inverse 0 = 0"
begin

subclass division_ring
proof
  fix a :: 'a
  assume "a \<noteq> 0"
  thus "inverse a * a = 1" by (rule field_inverse)
  thus "a * inverse a = 1" by (simp only: mult.commute)
next
  fix a b :: 'a
  show "a / b = a * inverse b" by (rule field_divide_inverse)
next
  show "inverse 0 = 0"
    by (fact field_inverse_zero)
qed

subclass idom_divide
proof
  fix b a
  assume "b \<noteq> 0"
  then show "a * b / b = a"
    by (simp add: divide_inverse ac_simps)
next
  fix a
  show "a / 0 = 0"
    by (simp add: divide_inverse)
qed

text\<open>There is no slick version using division by zero.\<close>
lemma inverse_add:
  "a \<noteq> 0 \<Longrightarrow> b \<noteq> 0 \<Longrightarrow> inverse a + inverse b = (a + b) * inverse a * inverse b"
  by (simp add: division_ring_inverse_add ac_simps)

lemma nonzero_mult_divide_mult_cancel_left [simp]:
  assumes [simp]: "c \<noteq> 0"
  shows "(c * a) / (c * b) = a / b"
proof (cases "b = 0")
  case True then show ?thesis by simp
next
  case False
  then have "(c*a)/(c*b) = c * a * (inverse b * inverse c)"
    by (simp add: divide_inverse nonzero_inverse_mult_distrib)
  also have "... =  a * inverse b * (inverse c * c)"
    by (simp only: ac_simps)
  also have "... =  a * inverse b" by simp
    finally show ?thesis by (simp add: divide_inverse)
qed

lemma nonzero_mult_divide_mult_cancel_right [simp]:
  "c \<noteq> 0 \<Longrightarrow> (a * c) / (b * c) = a / b"
  using nonzero_mult_divide_mult_cancel_left [of c a b] by (simp add: ac_simps)

lemma times_divide_eq_left [simp]: "(b / c) * a = (b * a) / c"
  by (simp add: divide_inverse ac_simps)

lemma divide_inverse_commute: "a / b = inverse b * a"
  by (simp add: divide_inverse mult.commute)

lemma add_frac_eq:
  assumes "y \<noteq> 0" and "z \<noteq> 0"
  shows "x / y + w / z = (x * z + w * y) / (y * z)"
proof -
  have "x / y + w / z = (x * z) / (y * z) + (y * w) / (y * z)"
    using assms by simp
  also have "\<dots> = (x * z + y * w) / (y * z)"
    by (simp only: add_divide_distrib)
  finally show ?thesis
    by (simp only: mult.commute)
qed

text\<open>Special Cancellation Simprules for Division\<close>

lemma nonzero_divide_mult_cancel_right [simp]:
  "b \<noteq> 0 \<Longrightarrow> b / (a * b) = 1 / a"
  using nonzero_mult_divide_mult_cancel_right [of b 1 a] by simp

lemma nonzero_divide_mult_cancel_left [simp]:
  "a \<noteq> 0 \<Longrightarrow> a / (a * b) = 1 / b"
  using nonzero_mult_divide_mult_cancel_left [of a 1 b] by simp

lemma nonzero_mult_divide_mult_cancel_left2 [simp]:
  "c \<noteq> 0 \<Longrightarrow> (c * a) / (b * c) = a / b"
  using nonzero_mult_divide_mult_cancel_left [of c a b] by (simp add: ac_simps)

lemma nonzero_mult_divide_mult_cancel_right2 [simp]:
  "c \<noteq> 0 \<Longrightarrow> (a * c) / (c * b) = a / b"
  using nonzero_mult_divide_mult_cancel_right [of b c a] by (simp add: ac_simps)

lemma diff_frac_eq:
  "y \<noteq> 0 \<Longrightarrow> z \<noteq> 0 \<Longrightarrow> x / y - w / z = (x * z - w * y) / (y * z)"
  by (simp add: field_simps)

lemma frac_eq_eq:
  "y \<noteq> 0 \<Longrightarrow> z \<noteq> 0 \<Longrightarrow> (x / y = w / z) = (x * z = w * y)"
  by (simp add: field_simps)

lemma divide_minus1 [simp]: "x / - 1 = - x"
  using nonzero_minus_divide_right [of "1" x] by simp

text\<open>This version builds in division by zero while also re-orienting
      the right-hand side.\<close>
lemma inverse_mult_distrib [simp]:
  "inverse (a * b) = inverse a * inverse b"
proof cases
  assume "a \<noteq> 0 \<and> b \<noteq> 0"
  thus ?thesis by (simp add: nonzero_inverse_mult_distrib ac_simps)
next
  assume "\<not> (a \<noteq> 0 \<and> b \<noteq> 0)"
  thus ?thesis by force
qed

lemma inverse_divide [simp]:
  "inverse (a / b) = b / a"
  by (simp add: divide_inverse mult.commute)

text \<open>Calculations with fractions\<close>

text\<open>There is a whole bunch of simp-rules just for class \<open>field\<close> but none for class \<open>field\<close> and \<open>nonzero_divides\<close>
because the latter are covered by a simproc.\<close>

lemmas mult_divide_mult_cancel_left = nonzero_mult_divide_mult_cancel_left

lemmas mult_divide_mult_cancel_right = nonzero_mult_divide_mult_cancel_right

lemma divide_divide_eq_right [simp]:
  "a / (b / c) = (a * c) / b"
  by (simp add: divide_inverse ac_simps)

lemma divide_divide_eq_left [simp]:
  "(a / b) / c = a / (b * c)"
  by (simp add: divide_inverse mult.assoc)

lemma divide_divide_times_eq:
  "(x / y) / (z / w) = (x * w) / (y * z)"
  by simp

text \<open>Special Cancellation Simprules for Division\<close>

lemma mult_divide_mult_cancel_left_if [simp]:
  shows "(c * a) / (c * b) = (if c = 0 then 0 else a / b)"
  by simp

text \<open>Division and Unary Minus\<close>

lemma minus_divide_right:
  "- (a / b) = a / - b"
  by (simp add: divide_inverse)

lemma divide_minus_right [simp]:
  "a / - b = - (a / b)"
  by (simp add: divide_inverse)

lemma minus_divide_divide:
  "(- a) / (- b) = a / b"
  by (cases "b=0") (simp_all add: nonzero_minus_divide_divide)

lemma inverse_eq_1_iff [simp]:
  "inverse x = 1 \<longleftrightarrow> x = 1"
  by (insert inverse_eq_iff_eq [of x 1], simp)

lemma divide_eq_0_iff [simp]:
  "a / b = 0 \<longleftrightarrow> a = 0 \<or> b = 0"
  by (simp add: divide_inverse)

lemma divide_cancel_right [simp]:
  "a / c = b / c \<longleftrightarrow> c = 0 \<or> a = b"
  by (cases "c=0") (simp_all add: divide_inverse)

lemma divide_cancel_left [simp]:
  "c / a = c / b \<longleftrightarrow> c = 0 \<or> a = b"
  by (cases "c=0") (simp_all add: divide_inverse)

lemma divide_eq_1_iff [simp]:
  "a / b = 1 \<longleftrightarrow> b \<noteq> 0 \<and> a = b"
  by (cases "b=0") (simp_all add: right_inverse_eq)

lemma one_eq_divide_iff [simp]:
  "1 = a / b \<longleftrightarrow> b \<noteq> 0 \<and> a = b"
  by (simp add: eq_commute [of 1])

lemma divide_eq_minus_1_iff:
   "(a / b = - 1) \<longleftrightarrow> b \<noteq> 0 \<and> a = - b"
using divide_eq_1_iff by fastforce

lemma times_divide_times_eq:
  "(x / y) * (z / w) = (x * z) / (y * w)"
  by simp

lemma add_frac_num:
  "y \<noteq> 0 \<Longrightarrow> x / y + z = (x + z * y) / y"
  by (simp add: add_divide_distrib)

lemma add_num_frac:
  "y \<noteq> 0 \<Longrightarrow> z + x / y = (x + z * y) / y"
  by (simp add: add_divide_distrib add.commute)

lemma dvd_field_iff:
  "a dvd b \<longleftrightarrow> (a = 0 \<longrightarrow> b = 0)"
proof (cases "a = 0")
  case False
  then have "b = a * (b / a)"
    by (simp add: field_simps)
  then have "a dvd b" ..
  with False show ?thesis
    by simp
qed simp

lemma inj_divide_right [simp]:
  "inj (\<lambda>b. b / a) \<longleftrightarrow> a \<noteq> 0"
proof -
  have "(\<lambda>b. b / a) = (*) (inverse a)"
    by (simp add: field_simps fun_eq_iff)
  then have "inj (\<lambda>y. y / a) \<longleftrightarrow> inj ((*) (inverse a))"
    by simp
  also have "\<dots> \<longleftrightarrow> inverse a \<noteq> 0"
    by simp
  also have "\<dots> \<longleftrightarrow> a \<noteq> 0"
    by simp
  finally show ?thesis
    by simp
qed

end

class field_char_0 = field + ring_char_0

subsection \<open>Ordered fields\<close>

class field_abs_sgn = field + idom_abs_sgn
begin

lemma sgn_inverse [simp]:
  "sgn (inverse a) = inverse (sgn a)"
proof (cases "a = 0")
  case True then show ?thesis by simp
next
  case False
  then have "a * inverse a = 1"
    by simp
  then have "sgn (a * inverse a) = sgn 1"
    by simp
  then have "sgn a * sgn (inverse a) = 1"
    by (simp add: sgn_mult)
  then have "inverse (sgn a) * (sgn a * sgn (inverse a)) = inverse (sgn a) * 1"
    by simp
  then have "(inverse (sgn a) * sgn a) * sgn (inverse a) = inverse (sgn a)"
    by (simp add: ac_simps)
  with False show ?thesis
    by (simp add: sgn_eq_0_iff)
qed

lemma abs_inverse [simp]:
  "\<bar>inverse a\<bar> = inverse \<bar>a\<bar>"
proof -
  from sgn_mult_abs [of "inverse a"] sgn_mult_abs [of a]
  have "inverse (sgn a) * \<bar>inverse a\<bar> = inverse (sgn a * \<bar>a\<bar>)"
    by simp
  then show ?thesis by (auto simp add: sgn_eq_0_iff)
qed

lemma sgn_divide [simp]:
  "sgn (a / b) = sgn a / sgn b"
  unfolding divide_inverse sgn_mult by simp

lemma abs_divide [simp]:
  "\<bar>a / b\<bar> = \<bar>a\<bar> / \<bar>b\<bar>"
  unfolding divide_inverse abs_mult by simp

end

class linordered_field = field + linordered_idom
begin

lemma positive_imp_inverse_positive:
  assumes a_gt_0: "0 < a"
  shows "0 < inverse a"
proof -
  have "0 < a * inverse a"
    by (simp add: a_gt_0 [THEN less_imp_not_eq2])
  thus "0 < inverse a"
    by (simp add: a_gt_0 [THEN less_not_sym] zero_less_mult_iff)
qed

lemma negative_imp_inverse_negative:
  "a < 0 \<Longrightarrow> inverse a < 0"
  by (insert positive_imp_inverse_positive [of "-a"],
    simp add: nonzero_inverse_minus_eq less_imp_not_eq)

lemma inverse_le_imp_le:
  assumes invle: "inverse a \<le> inverse b" and apos: "0 < a"
  shows "b \<le> a"
proof (rule classical)
  assume "\<not> b \<le> a"
  hence "a < b"  by (simp add: linorder_not_le)
  hence bpos: "0 < b"  by (blast intro: apos less_trans)
  hence "a * inverse a \<le> a * inverse b"
    by (simp add: apos invle less_imp_le mult_left_mono)
  hence "(a * inverse a) * b \<le> (a * inverse b) * b"
    by (simp add: bpos less_imp_le mult_right_mono)
  thus "b \<le> a"  by (simp add: mult.assoc apos bpos less_imp_not_eq2)
qed

lemma inverse_positive_imp_positive:
  assumes inv_gt_0: "0 < inverse a" and nz: "a \<noteq> 0"
  shows "0 < a"
proof -
  have "0 < inverse (inverse a)"
    using inv_gt_0 by (rule positive_imp_inverse_positive)
  thus "0 < a"
    using nz by (simp add: nonzero_inverse_inverse_eq)
qed

lemma inverse_negative_imp_negative:
  assumes inv_less_0: "inverse a < 0" and nz: "a \<noteq> 0"
  shows "a < 0"
proof -
  have "inverse (inverse a) < 0"
    using inv_less_0 by (rule negative_imp_inverse_negative)
  thus "a < 0" using nz by (simp add: nonzero_inverse_inverse_eq)
qed

lemma linordered_field_no_lb:
  "\<forall>x. \<exists>y. y < x"
proof
  fix x::'a
  have m1: "- (1::'a) < 0" by simp
  from add_strict_right_mono[OF m1, where c=x]
  have "(- 1) + x < x" by simp
  thus "\<exists>y. y < x" by blast
qed

lemma linordered_field_no_ub:
  "\<forall> x. \<exists>y. y > x"
proof
  fix x::'a
  have m1: " (1::'a) > 0" by simp
  from add_strict_right_mono[OF m1, where c=x]
  have "1 + x > x" by simp
  thus "\<exists>y. y > x" by blast
qed

lemma less_imp_inverse_less:
  assumes less: "a < b" and apos:  "0 < a"
  shows "inverse b < inverse a"
proof (rule ccontr)
  assume "\<not> inverse b < inverse a"
  hence "inverse a \<le> inverse b" by simp
  hence "\<not> (a < b)"
    by (simp add: not_less inverse_le_imp_le [OF _ apos])
  thus False by (rule notE [OF _ less])
qed

lemma inverse_less_imp_less:
  assumes "inverse a < inverse b" "0 < a"
  shows "b < a"
proof -
  have "a \<noteq> b"
    using assms by (simp add: less_le)
  moreover have "b \<le> a"
    using assms by (force simp: less_le dest: inverse_le_imp_le)
  ultimately show ?thesis
    by (simp add: less_le)
qed

text\<open>Both premises are essential. Consider -1 and 1.\<close>
lemma inverse_less_iff_less [simp]:
  "0 < a \<Longrightarrow> 0 < b \<Longrightarrow> inverse a < inverse b \<longleftrightarrow> b < a"
  by (blast intro: less_imp_inverse_less dest: inverse_less_imp_less)

lemma le_imp_inverse_le:
  "a \<le> b \<Longrightarrow> 0 < a \<Longrightarrow> inverse b \<le> inverse a"
  by (force simp add: le_less less_imp_inverse_less)

lemma inverse_le_iff_le [simp]:
  "0 < a \<Longrightarrow> 0 < b \<Longrightarrow> inverse a \<le> inverse b \<longleftrightarrow> b \<le> a"
  by (blast intro: le_imp_inverse_le dest: inverse_le_imp_le)

text\<open>These results refer to both operands being negative.  The opposite-sign
case is trivial, since inverse preserves signs.\<close>
lemma inverse_le_imp_le_neg:
  assumes "inverse a \<le> inverse b" "b < 0"
  shows "b \<le> a"
proof (rule classical)
  assume "\<not> b \<le> a"
  with \<open>b < 0\<close> have "a < 0"
    by force
  with assms show "b \<le> a"
    using inverse_le_imp_le [of "-b" "-a"] by (simp add: nonzero_inverse_minus_eq)
qed

lemma less_imp_inverse_less_neg:
  assumes "a < b" "b < 0"
  shows "inverse b < inverse a"
proof -
  have "a < 0"
    using assms by (blast intro: less_trans)
  with less_imp_inverse_less [of "-b" "-a"] show ?thesis
    by (simp add: nonzero_inverse_minus_eq assms)
qed

lemma inverse_less_imp_less_neg:
  assumes "inverse a < inverse b" "b < 0"
  shows "b < a"
proof (rule classical)
  assume "\<not> b < a"
  with \<open>b < 0\<close> have "a < 0"
    by force
  with inverse_less_imp_less [of "-b" "-a"] show ?thesis
    by (simp add: nonzero_inverse_minus_eq assms)
qed

lemma inverse_less_iff_less_neg [simp]:
  "a < 0 \<Longrightarrow> b < 0 \<Longrightarrow> inverse a < inverse b \<longleftrightarrow> b < a"
  using inverse_less_iff_less [of "-b" "-a"]
  by (simp del: inverse_less_iff_less add: nonzero_inverse_minus_eq)

lemma le_imp_inverse_le_neg:
  "a \<le> b \<Longrightarrow> b < 0 \<Longrightarrow> inverse b \<le> inverse a"
  by (force simp add: le_less less_imp_inverse_less_neg)

lemma inverse_le_iff_le_neg [simp]:
  "a < 0 \<Longrightarrow> b < 0 \<Longrightarrow> inverse a \<le> inverse b \<longleftrightarrow> b \<le> a"
  by (blast intro: le_imp_inverse_le_neg dest: inverse_le_imp_le_neg)

lemma one_less_inverse:
  "0 < a \<Longrightarrow> a < 1 \<Longrightarrow> 1 < inverse a"
  using less_imp_inverse_less [of a 1, unfolded inverse_1] .

lemma one_le_inverse:
  "0 < a \<Longrightarrow> a \<le> 1 \<Longrightarrow> 1 \<le> inverse a"
  using le_imp_inverse_le [of a 1, unfolded inverse_1] .

lemma pos_le_divide_eq [field_simps]:
  assumes "0 < c"
  shows "a \<le> b / c \<longleftrightarrow> a * c \<le> b"
proof -
  from assms have "a \<le> b / c \<longleftrightarrow> a * c \<le> (b / c) * c"
    using mult_le_cancel_right [of a c "b * inverse c"] by (auto simp add: field_simps)
  also have "... \<longleftrightarrow> a * c \<le> b"
    by (simp add: less_imp_not_eq2 [OF assms] divide_inverse mult.assoc)
  finally show ?thesis .
qed

lemma pos_less_divide_eq [field_simps]:
  assumes "0 < c"
  shows "a < b / c \<longleftrightarrow> a * c < b"
proof -
  from assms have "a < b / c \<longleftrightarrow> a * c < (b / c) * c"
    using mult_less_cancel_right [of a c "b / c"] by auto
  also have "... = (a*c < b)"
    by (simp add: less_imp_not_eq2 [OF assms] divide_inverse mult.assoc)
  finally show ?thesis .
qed

lemma neg_less_divide_eq [field_simps]:
  assumes "c < 0"
  shows "a < b / c \<longleftrightarrow> b < a * c"
proof -
  from assms have "a < b / c \<longleftrightarrow> (b / c) * c < a * c"
    using mult_less_cancel_right [of "b / c" c a] by auto
  also have "... \<longleftrightarrow> b < a * c"
    by (simp add: less_imp_not_eq [OF assms] divide_inverse mult.assoc)
  finally show ?thesis .
qed

lemma neg_le_divide_eq [field_simps]:
  assumes "c < 0"
  shows "a \<le> b / c \<longleftrightarrow> b \<le> a * c"
proof -
  from assms have "a \<le> b / c \<longleftrightarrow> (b / c) * c \<le> a * c"
    using mult_le_cancel_right [of "b * inverse c" c a] by (auto simp add: field_simps)
  also have "... \<longleftrightarrow> b \<le> a * c"
    by (simp add: less_imp_not_eq [OF assms] divide_inverse mult.assoc)
  finally show ?thesis .
qed

lemma pos_divide_le_eq [field_simps]:
  assumes "0 < c"
  shows "b / c \<le> a \<longleftrightarrow> b \<le> a * c"
proof -
  from assms have "b / c \<le> a \<longleftrightarrow> (b / c) * c \<le> a * c"
    using mult_le_cancel_right [of "b / c" c a] by auto
  also have "... \<longleftrightarrow> b \<le> a * c"
    by (simp add: less_imp_not_eq2 [OF assms] divide_inverse mult.assoc)
  finally show ?thesis .
qed

lemma pos_divide_less_eq [field_simps]:
  assumes "0 < c"
  shows "b / c < a \<longleftrightarrow> b < a * c"
proof -
  from assms have "b / c < a \<longleftrightarrow> (b / c) * c < a * c"
    using mult_less_cancel_right [of "b / c" c a] by auto
  also have "... \<longleftrightarrow> b < a * c"
    by (simp add: less_imp_not_eq2 [OF assms] divide_inverse mult.assoc)
  finally show ?thesis .
qed

lemma neg_divide_le_eq [field_simps]:
  assumes "c < 0"
  shows "b / c \<le> a \<longleftrightarrow> a * c \<le> b"
proof -
  from assms have "b / c \<le> a \<longleftrightarrow> a * c \<le> (b / c) * c"
    using mult_le_cancel_right [of a c "b / c"] by auto
  also have "... \<longleftrightarrow> a * c \<le> b"
    by (simp add: less_imp_not_eq [OF assms] divide_inverse mult.assoc)
  finally show ?thesis .
qed

lemma neg_divide_less_eq [field_simps]:
  assumes "c < 0"
  shows "b / c < a \<longleftrightarrow> a * c < b"
proof -
  from assms have "b / c < a \<longleftrightarrow> a * c < b / c * c"
    using mult_less_cancel_right [of a c "b / c"] by auto
  also have "... \<longleftrightarrow> a * c < b"
    by (simp add: less_imp_not_eq [OF assms] divide_inverse mult.assoc)
  finally show ?thesis .
qed

text\<open>The following \<open>field_simps\<close> rules are necessary, as minus is always moved atop of
division but we want to get rid of division.\<close>

lemma pos_le_minus_divide_eq [field_simps]: "0 < c \<Longrightarrow> a \<le> - (b / c) \<longleftrightarrow> a * c \<le> - b"
  unfolding minus_divide_left by (rule pos_le_divide_eq)

lemma neg_le_minus_divide_eq [field_simps]: "c < 0 \<Longrightarrow> a \<le> - (b / c) \<longleftrightarrow> - b \<le> a * c"
  unfolding minus_divide_left by (rule neg_le_divide_eq)

lemma pos_less_minus_divide_eq [field_simps]: "0 < c \<Longrightarrow> a < - (b / c) \<longleftrightarrow> a * c < - b"
  unfolding minus_divide_left by (rule pos_less_divide_eq)

lemma neg_less_minus_divide_eq [field_simps]: "c < 0 \<Longrightarrow> a < - (b / c) \<longleftrightarrow> - b < a * c"
  unfolding minus_divide_left by (rule neg_less_divide_eq)

lemma pos_minus_divide_less_eq [field_simps]: "0 < c \<Longrightarrow> - (b / c) < a \<longleftrightarrow> - b < a * c"
  unfolding minus_divide_left by (rule pos_divide_less_eq)

lemma neg_minus_divide_less_eq [field_simps]: "c < 0 \<Longrightarrow> - (b / c) < a \<longleftrightarrow> a * c < - b"
  unfolding minus_divide_left by (rule neg_divide_less_eq)

lemma pos_minus_divide_le_eq [field_simps]: "0 < c \<Longrightarrow> - (b / c) \<le> a \<longleftrightarrow> - b \<le> a * c"
  unfolding minus_divide_left by (rule pos_divide_le_eq)

lemma neg_minus_divide_le_eq [field_simps]: "c < 0 \<Longrightarrow> - (b / c) \<le> a \<longleftrightarrow> a * c \<le> - b"
  unfolding minus_divide_left by (rule neg_divide_le_eq)

lemma frac_less_eq:
  "y \<noteq> 0 \<Longrightarrow> z \<noteq> 0 \<Longrightarrow> x / y < w / z \<longleftrightarrow> (x * z - w * y) / (y * z) < 0"
  by (subst less_iff_diff_less_0) (simp add: diff_frac_eq )

lemma frac_le_eq:
  "y \<noteq> 0 \<Longrightarrow> z \<noteq> 0 \<Longrightarrow> x / y \<le> w / z \<longleftrightarrow> (x * z - w * y) / (y * z) \<le> 0"
  by (subst le_iff_diff_le_0) (simp add: diff_frac_eq )

lemma divide_pos_pos[simp]:
  "0 < x \<Longrightarrow> 0 < y \<Longrightarrow> 0 < x / y"
by(simp add:field_simps)

lemma divide_nonneg_pos:
  "0 \<le> x \<Longrightarrow> 0 < y \<Longrightarrow> 0 \<le> x / y"
by(simp add:field_simps)

lemma divide_neg_pos:
  "x < 0 \<Longrightarrow> 0 < y \<Longrightarrow> x / y < 0"
  by(simp add:field_simps)

lemma divide_nonpos_pos:
  "x \<le> 0 \<Longrightarrow> 0 < y \<Longrightarrow> x / y \<le> 0"
  by(simp add:field_simps)

lemma divide_pos_neg:
  "0 < x \<Longrightarrow> y < 0 \<Longrightarrow> x / y < 0"
  by(simp add:field_simps)

lemma divide_nonneg_neg:
  "0 \<le> x \<Longrightarrow> y < 0 \<Longrightarrow> x / y \<le> 0"
  by(simp add:field_simps)

lemma divide_neg_neg:
  "x < 0 \<Longrightarrow> y < 0 \<Longrightarrow> 0 < x / y"
  by(simp add:field_simps)

lemma divide_nonpos_neg:
  "x \<le> 0 \<Longrightarrow> y < 0 \<Longrightarrow> 0 \<le> x / y"
  by(simp add:field_simps)

lemma divide_strict_right_mono:
  "\<lbrakk>a < b; 0 < c\<rbrakk> \<Longrightarrow> a / c < b / c"
  by (simp add: less_imp_not_eq2 divide_inverse mult_strict_right_mono
      positive_imp_inverse_positive)

lemma divide_strict_right_mono_neg:
  assumes "b < a" "c < 0" shows "a / c < b / c"
proof -
  have "b / - c < a / - c"
    by (rule divide_strict_right_mono) (use assms in auto)
  then show ?thesis
    by (simp add: less_imp_not_eq)
qed

text\<open>The last premise ensures that \<^term>\<open>a\<close> and \<^term>\<open>b\<close>
      have the same sign\<close>
lemma divide_strict_left_mono:
  "\<lbrakk>b < a; 0 < c; 0 < a*b\<rbrakk> \<Longrightarrow> c / a < c / b"
  by (auto simp: field_simps zero_less_mult_iff mult_strict_right_mono)

lemma divide_left_mono:
  "\<lbrakk>b \<le> a; 0 \<le> c; 0 < a*b\<rbrakk> \<Longrightarrow> c / a \<le> c / b"
  by (auto simp: field_simps zero_less_mult_iff mult_right_mono)

lemma divide_strict_left_mono_neg:
  "\<lbrakk>a < b; c < 0; 0 < a*b\<rbrakk> \<Longrightarrow> c / a < c / b"
  by (auto simp: field_simps zero_less_mult_iff mult_strict_right_mono_neg)

lemma mult_imp_div_pos_le: "0 < y \<Longrightarrow> x \<le> z * y \<Longrightarrow> x / y \<le> z"
by (subst pos_divide_le_eq, assumption+)

lemma mult_imp_le_div_pos: "0 < y \<Longrightarrow> z * y \<le> x \<Longrightarrow> z \<le> x / y"
by(simp add:field_simps)

lemma mult_imp_div_pos_less: "0 < y \<Longrightarrow> x < z * y \<Longrightarrow> x / y < z"
by(simp add:field_simps)

lemma mult_imp_less_div_pos: "0 < y \<Longrightarrow> z * y < x \<Longrightarrow> z < x / y"
by(simp add:field_simps)

lemma frac_le:
  assumes "0 \<le> y" "x \<le> y" "0 < w" "w \<le> z"
  shows "x / z \<le> y / w"
proof (rule mult_imp_div_pos_le)
  show "z > 0"
    using assms by simp
  have "x \<le> y * z / w"
  proof (rule mult_imp_le_div_pos [OF \<open>0 < w\<close>])
    show "x * w \<le> y * z"
      using assms by (auto intro: mult_mono)
  qed
  also have "... = y / w * z"
    by simp
  finally show "x \<le> y / w * z" .
qed

lemma frac_less:
  assumes "0 \<le> x" "x < y" "0 < w" "w \<le> z"
  shows "x / z < y / w"
proof (rule mult_imp_div_pos_less)
  show "z > 0"
    using assms by simp
  have "x < y * z / w"
  proof (rule mult_imp_less_div_pos [OF \<open>0 < w\<close>])
    show "x * w < y * z"
      using assms by (auto intro: mult_less_le_imp_less)
  qed
  also have "... = y / w * z"
    by simp
  finally show "x < y / w * z" .
qed

lemma frac_less2:
  assumes "0 < x" "x \<le> y" "0 < w" "w < z"
  shows "x / z < y / w"
proof (rule mult_imp_div_pos_less)
  show "z > 0"
    using assms by simp
  show "x < y / w * z"
    using assms by (force intro: mult_imp_less_div_pos mult_le_less_imp_less)
qed

lemma less_half_sum: "a < b \<Longrightarrow> a < (a+b) / (1+1)"
  by (simp add: field_simps zero_less_two)

lemma gt_half_sum: "a < b \<Longrightarrow> (a+b)/(1+1) < b"
  by (simp add: field_simps zero_less_two)

subclass unbounded_dense_linorder
proof
  fix x y :: 'a
  from less_add_one show "\<exists>y. x < y" ..
  from less_add_one have "x + (- 1) < (x + 1) + (- 1)" by (rule add_strict_right_mono)
  then have "x - 1 < x + 1 - 1" by simp
  then have "x - 1 < x" by (simp add: algebra_simps)
  then show "\<exists>y. y < x" ..
  show "x < y \<Longrightarrow> \<exists>z>x. z < y" by (blast intro!: less_half_sum gt_half_sum)
qed

subclass field_abs_sgn ..

lemma inverse_sgn [simp]:
  "inverse (sgn a) = sgn a"
  by (cases a 0 rule: linorder_cases) simp_all

lemma divide_sgn [simp]:
  "a / sgn b = a * sgn b"
  by (cases b 0 rule: linorder_cases) simp_all

lemma nonzero_abs_inverse:
  "a \<noteq> 0 \<Longrightarrow> \<bar>inverse a\<bar> = inverse \<bar>a\<bar>"
  by (rule abs_inverse)

lemma nonzero_abs_divide:
  "b \<noteq> 0 \<Longrightarrow> \<bar>a / b\<bar> = \<bar>a\<bar> / \<bar>b\<bar>"
  by (rule abs_divide)

lemma field_le_epsilon:
  assumes e: "\<And>e. 0 < e \<Longrightarrow> x \<le> y + e"
  shows "x \<le> y"
proof (rule dense_le)
  fix t assume "t < x"
  hence "0 < x - t" by (simp add: less_diff_eq)
  from e [OF this] have "x + 0 \<le> x + (y - t)" by (simp add: algebra_simps)
  then have "0 \<le> y - t" by (simp only: add_le_cancel_left)
  then show "t \<le> y" by (simp add: algebra_simps)
qed

lemma inverse_positive_iff_positive [simp]: "(0 < inverse a) = (0 < a)"
proof (cases "a = 0")
  case False
  then show ?thesis
    by (blast intro: inverse_positive_imp_positive positive_imp_inverse_positive)
qed auto

lemma inverse_negative_iff_negative [simp]: "(inverse a < 0) = (a < 0)"
proof (cases "a = 0")
  case False
  then show ?thesis
    by (blast intro: inverse_negative_imp_negative negative_imp_inverse_negative)
qed auto

lemma inverse_nonnegative_iff_nonnegative [simp]: "0 \<le> inverse a \<longleftrightarrow> 0 \<le> a"
  by (simp add: not_less [symmetric])

lemma inverse_nonpositive_iff_nonpositive [simp]: "inverse a \<le> 0 \<longleftrightarrow> a \<le> 0"
  by (simp add: not_less [symmetric])

lemma one_less_inverse_iff: "1 < inverse x \<longleftrightarrow> 0 < x \<and> x < 1"
  using less_trans[of 1 x 0 for x]
  by (cases x 0 rule: linorder_cases) (auto simp add: field_simps)

lemma one_le_inverse_iff: "1 \<le> inverse x \<longleftrightarrow> 0 < x \<and> x \<le> 1"
proof (cases "x = 1")
  case True then show ?thesis by simp
next
  case False then have "inverse x \<noteq> 1" by simp
  then have "1 \<noteq> inverse x" by blast
  then have "1 \<le> inverse x \<longleftrightarrow> 1 < inverse x" by (simp add: le_less)
  with False show ?thesis by (auto simp add: one_less_inverse_iff)
qed

lemma inverse_less_1_iff: "inverse x < 1 \<longleftrightarrow> x \<le> 0 \<or> 1 < x"
  by (simp add: not_le [symmetric] one_le_inverse_iff)

lemma inverse_le_1_iff: "inverse x \<le> 1 \<longleftrightarrow> x \<le> 0 \<or> 1 \<le> x"
  by (simp add: not_less [symmetric] one_less_inverse_iff)

lemma [field_split_simps, divide_simps]:
  shows le_divide_eq: "a \<le> b / c \<longleftrightarrow> (if 0 < c then a * c \<le> b else if c < 0 then b \<le> a * c else a \<le> 0)"
    and divide_le_eq: "b / c \<le> a \<longleftrightarrow> (if 0 < c then b \<le> a * c else if c < 0 then a * c \<le> b else 0 \<le> a)"
    and less_divide_eq: "a < b / c \<longleftrightarrow> (if 0 < c then a * c < b else if c < 0 then b < a * c else a < 0)"
    and divide_less_eq: "b / c < a \<longleftrightarrow> (if 0 < c then b < a * c else if c < 0 then a * c < b else 0 < a)"
    and le_minus_divide_eq: "a \<le> - (b / c) \<longleftrightarrow> (if 0 < c then a * c \<le> - b else if c < 0 then - b \<le> a * c else a \<le> 0)"
    and minus_divide_le_eq: "- (b / c) \<le> a \<longleftrightarrow> (if 0 < c then - b \<le> a * c else if c < 0 then a * c \<le> - b else 0 \<le> a)"
    and less_minus_divide_eq: "a < - (b / c) \<longleftrightarrow> (if 0 < c then a * c < - b else if c < 0 then - b < a * c else  a < 0)"
    and minus_divide_less_eq: "- (b / c) < a \<longleftrightarrow> (if 0 < c then - b < a * c else if c < 0 then a * c < - b else 0 < a)"
  by (auto simp: field_simps not_less dest: antisym)

text \<open>Division and Signs\<close>

lemma
  shows zero_less_divide_iff: "0 < a / b \<longleftrightarrow> 0 < a \<and> 0 < b \<or> a < 0 \<and> b < 0"
    and divide_less_0_iff: "a / b < 0 \<longleftrightarrow> 0 < a \<and> b < 0 \<or> a < 0 \<and> 0 < b"
    and zero_le_divide_iff: "0 \<le> a / b \<longleftrightarrow> 0 \<le> a \<and> 0 \<le> b \<or> a \<le> 0 \<and> b \<le> 0"
    and divide_le_0_iff: "a / b \<le> 0 \<longleftrightarrow> 0 \<le> a \<and> b \<le> 0 \<or> a \<le> 0 \<and> 0 \<le> b"
  by (auto simp add: field_split_simps)

text \<open>Division and the Number One\<close>

text\<open>Simplify expressions equated with 1\<close>

lemma zero_eq_1_divide_iff [simp]: "0 = 1 / a \<longleftrightarrow> a = 0"
  by (cases "a = 0") (auto simp: field_simps)

lemma one_divide_eq_0_iff [simp]: "1 / a = 0 \<longleftrightarrow> a = 0"
  using zero_eq_1_divide_iff[of a] by simp

text\<open>Simplify expressions such as \<open>0 < 1/x\<close> to \<open>0 < x\<close>\<close>

lemma zero_le_divide_1_iff [simp]:
  "0 \<le> 1 / a \<longleftrightarrow> 0 \<le> a"
  by (simp add: zero_le_divide_iff)

lemma zero_less_divide_1_iff [simp]:
  "0 < 1 / a \<longleftrightarrow> 0 < a"
  by (simp add: zero_less_divide_iff)

lemma divide_le_0_1_iff [simp]:
  "1 / a \<le> 0 \<longleftrightarrow> a \<le> 0"
  by (simp add: divide_le_0_iff)

lemma divide_less_0_1_iff [simp]:
  "1 / a < 0 \<longleftrightarrow> a < 0"
  by (simp add: divide_less_0_iff)

lemma divide_right_mono:
  "\<lbrakk>a \<le> b; 0 \<le> c\<rbrakk> \<Longrightarrow> a/c \<le> b/c"
  by (force simp add: divide_strict_right_mono le_less)

lemma divide_right_mono_neg: "a \<le> b \<Longrightarrow> c \<le> 0 \<Longrightarrow> b / c \<le> a / c"
  by (auto dest: divide_right_mono [of _ _ "- c"])

lemma divide_left_mono_neg: "a \<le> b \<Longrightarrow> c \<le> 0 \<Longrightarrow> 0 < a * b \<Longrightarrow> c / a \<le> c / b"
  by (auto simp add: mult.commute dest: divide_left_mono [of _ _ "- c"])

lemma inverse_le_iff: "inverse a \<le> inverse b \<longleftrightarrow> (0 < a * b \<longrightarrow> b \<le> a) \<and> (a * b \<le> 0 \<longrightarrow> a \<le> b)"
  by (cases a 0 b 0 rule: linorder_cases[case_product linorder_cases])
     (auto simp add: field_simps zero_less_mult_iff mult_le_0_iff)

lemma inverse_less_iff: "inverse a < inverse b \<longleftrightarrow> (0 < a * b \<longrightarrow> b < a) \<and> (a * b \<le> 0 \<longrightarrow> a < b)"
  by (subst less_le) (auto simp: inverse_le_iff)

lemma divide_le_cancel: "a / c \<le> b / c \<longleftrightarrow> (0 < c \<longrightarrow> a \<le> b) \<and> (c < 0 \<longrightarrow> b \<le> a)"
  by (simp add: divide_inverse mult_le_cancel_right)

lemma divide_less_cancel: "a / c < b / c \<longleftrightarrow> (0 < c \<longrightarrow> a < b) \<and> (c < 0 \<longrightarrow> b < a) \<and> c \<noteq> 0"
  by (auto simp add: divide_inverse mult_less_cancel_right)

text\<open>Simplify quotients that are compared with the value 1.\<close>

lemma le_divide_eq_1:
  "(1 \<le> b / a) = ((0 < a \<and> a \<le> b) \<or> (a < 0 \<and> b \<le> a))"
  by (auto simp add: le_divide_eq)

lemma divide_le_eq_1:
  "(b / a \<le> 1) = ((0 < a \<and> b \<le> a) \<or> (a < 0 \<and> a \<le> b) \<or> a=0)"
  by (auto simp add: divide_le_eq)

lemma less_divide_eq_1:
  "(1 < b / a) = ((0 < a \<and> a < b) \<or> (a < 0 \<and> b < a))"
  by (auto simp add: less_divide_eq)

lemma divide_less_eq_1:
  "(b / a < 1) = ((0 < a \<and> b < a) \<or> (a < 0 \<and> a < b) \<or> a=0)"
  by (auto simp add: divide_less_eq)

lemma divide_nonneg_nonneg [simp]:
  "0 \<le> x \<Longrightarrow> 0 \<le> y \<Longrightarrow> 0 \<le> x / y"
  by (auto simp add: field_split_simps)

lemma divide_nonpos_nonpos:
  "x \<le> 0 \<Longrightarrow> y \<le> 0 \<Longrightarrow> 0 \<le> x / y"
  by (auto simp add: field_split_simps)

lemma divide_nonneg_nonpos:
  "0 \<le> x \<Longrightarrow> y \<le> 0 \<Longrightarrow> x / y \<le> 0"
  by (auto simp add: field_split_simps)

lemma divide_nonpos_nonneg:
  "x \<le> 0 \<Longrightarrow> 0 \<le> y \<Longrightarrow> x / y \<le> 0"
  by (auto simp add: field_split_simps)

text \<open>Conditional Simplification Rules: No Case Splits\<close>

lemma le_divide_eq_1_pos [simp]:
  "0 < a \<Longrightarrow> (1 \<le> b/a) = (a \<le> b)"
  by (auto simp add: le_divide_eq)

lemma le_divide_eq_1_neg [simp]:
  "a < 0 \<Longrightarrow> (1 \<le> b/a) = (b \<le> a)"
  by (auto simp add: le_divide_eq)

lemma divide_le_eq_1_pos [simp]:
  "0 < a \<Longrightarrow> (b/a \<le> 1) = (b \<le> a)"
  by (auto simp add: divide_le_eq)

lemma divide_le_eq_1_neg [simp]:
  "a < 0 \<Longrightarrow> (b/a \<le> 1) = (a \<le> b)"
  by (auto simp add: divide_le_eq)

lemma less_divide_eq_1_pos [simp]:
  "0 < a \<Longrightarrow> (1 < b/a) = (a < b)"
  by (auto simp add: less_divide_eq)

lemma less_divide_eq_1_neg [simp]:
  "a < 0 \<Longrightarrow> (1 < b/a) = (b < a)"
  by (auto simp add: less_divide_eq)

lemma divide_less_eq_1_pos [simp]:
  "0 < a \<Longrightarrow> (b/a < 1) = (b < a)"
  by (auto simp add: divide_less_eq)

lemma divide_less_eq_1_neg [simp]:
  "a < 0 \<Longrightarrow> b/a < 1 \<longleftrightarrow> a < b"
  by (auto simp add: divide_less_eq)

lemma eq_divide_eq_1 [simp]:
  "(1 = b/a) = ((a \<noteq> 0 \<and> a = b))"
  by (auto simp add: eq_divide_eq)

lemma divide_eq_eq_1 [simp]:
  "(b/a = 1) = ((a \<noteq> 0 \<and> a = b))"
  by (auto simp add: divide_eq_eq)

lemma abs_div_pos: "0 < y \<Longrightarrow> \<bar>x\<bar> / y = \<bar>x / y\<bar>"
  by (simp add: order_less_imp_le)

lemma zero_le_divide_abs_iff [simp]: "(0 \<le> a / \<bar>b\<bar>) = (0 \<le> a \<or> b = 0)"
  by (auto simp: zero_le_divide_iff)

lemma divide_le_0_abs_iff [simp]: "(a / \<bar>b\<bar> \<le> 0) = (a \<le> 0 \<or> b = 0)"
  by (auto simp: divide_le_0_iff)

lemma field_le_mult_one_interval:
  assumes *: "\<And>z. \<lbrakk> 0 < z ; z < 1 \<rbrakk> \<Longrightarrow> z * x \<le> y"
  shows "x \<le> y"
proof (cases "0 < x")
  assume "0 < x"
  thus ?thesis
    using dense_le_bounded[of 0 1 "y/x"] *
    unfolding le_divide_eq if_P[OF \<open>0 < x\<close>] by simp
next
  assume "\<not>0 < x" hence "x \<le> 0" by simp
  obtain s::'a where s: "0 < s" "s < 1" using dense[of 0 "1::'a"] by auto
  hence "x \<le> s * x" using mult_le_cancel_right[of 1 x s] \<open>x \<le> 0\<close> by auto
  also note *[OF s]
  finally show ?thesis .
qed

text\<open>For creating values between \<^term>\<open>u\<close> and \<^term>\<open>v\<close>.\<close>
lemma scaling_mono:
  assumes "u \<le> v" "0 \<le> r" "r \<le> s"
  shows "u + r * (v - u) / s \<le> v"
proof -
  have "r/s \<le> 1" using assms
    using divide_le_eq_1 by fastforce
  moreover have "0 \<le> v - u"
    using assms by simp
  ultimately have "(r/s) * (v - u) \<le> 1 * (v - u)"
    by (rule mult_right_mono)
  then show ?thesis
    by (simp add: field_simps)
qed

end

text \<open>Min/max Simplification Rules\<close>

lemma min_mult_distrib_left:
  fixes x::"'a::linordered_idom"
  shows "p * min x y = (if 0 \<le> p then min (p*x) (p*y) else max (p*x) (p*y))"
by (auto simp add: min_def max_def mult_le_cancel_left)

lemma min_mult_distrib_right:
  fixes x::"'a::linordered_idom"
  shows "min x y * p = (if 0 \<le> p then min (x*p) (y*p) else max (x*p) (y*p))"
by (auto simp add: min_def max_def mult_le_cancel_right)

lemma min_divide_distrib_right:
  fixes x::"'a::linordered_field"
  shows "min x y / p = (if 0 \<le> p then min (x/p) (y/p) else max (x/p) (y/p))"
by (simp add: min_mult_distrib_right divide_inverse)

lemma max_mult_distrib_left:
  fixes x::"'a::linordered_idom"
  shows "p * max x y = (if 0 \<le> p then max (p*x) (p*y) else min (p*x) (p*y))"
by (auto simp add: min_def max_def mult_le_cancel_left)

lemma max_mult_distrib_right:
  fixes x::"'a::linordered_idom"
  shows "max x y * p = (if 0 \<le> p then max (x*p) (y*p) else min (x*p) (y*p))"
by (auto simp add: min_def max_def mult_le_cancel_right)

lemma max_divide_distrib_right:
  fixes x::"'a::linordered_field"
  shows "max x y / p = (if 0 \<le> p then max (x/p) (y/p) else min (x/p) (y/p))"
by (simp add: max_mult_distrib_right divide_inverse)

hide_fact (open) field_inverse field_divide_inverse field_inverse_zero

code_identifier
  code_module Fields \<rightharpoonup> (SML) Arith and (OCaml) Arith and (Haskell) Arith

end


(*  Title:      HOL/HOLCF/ex/Fix2.thy
    Author:     Franz Regensburger

Show that fix is the unique least fixed-point operator.
From axioms gix1_def,gix2_def it follows that fix = gix
*)

theory Fix2
imports HOLCF
begin

axiomatization
  gix :: "('a \<rightarrow> 'a) \<rightarrow>'a" where
  gix1_def: "F\<cdot>(gix\<cdot>F) = gix\<cdot>F" and
  gix2_def: "F\<cdot>y = y \<Longrightarrow> gix\<cdot>F << y"

lemma lemma1: "fix = gix"
apply (rule cfun_eqI)
apply (rule below_antisym)
apply (rule fix_least)
apply (rule gix1_def)
apply (rule gix2_def)
apply (rule fix_eq [symmetric])
done

lemma lemma2: "gix\<cdot>F = lub (range (\<lambda>i. iterate i\<cdot>F\<cdot>UU))"
apply (rule lemma1 [THEN subst])
apply (rule fix_def2)
done

end


(* Author: Tobias Nipkow *)

section "Trie1"

theory Trie1
imports Main
begin

hide_const (open) insert

declare Let_def[simp]

subsection "Trie"

datatype trie = Leaf | Node bool "trie * trie"

fun isin :: "trie \<Rightarrow> bool list \<Rightarrow> bool" where
"isin Leaf ks = False" |
"isin (Node b (l,r)) ks =
   (case ks of
      [] \<Rightarrow> b |
      k#ks \<Rightarrow> isin (if k then r else l) ks)"

fun insert :: "bool list \<Rightarrow> trie \<Rightarrow> trie" where
"insert [] Leaf = Node True (Leaf,Leaf)" |
"insert [] (Node b lr) = Node True lr" |
"insert (k#ks) Leaf =
  Node False (if k then (Leaf, insert ks Leaf)
                   else (insert ks Leaf, Leaf))" |
"insert (k#ks) (Node b (l,r)) =
  Node b (if k then (l, insert ks r)
               else (insert ks l, r))"

lemma isin_insert: "isin (insert as t) bs = (as = bs \<or> isin t bs)"
apply(induction as t arbitrary: bs rule: insert.induct)
apply (auto split: list.splits)
done

text \<open>A simple implementation of delete; does not shrink the trie!\<close>

fun delete :: "bool list \<Rightarrow> trie \<Rightarrow> trie" where
"delete ks Leaf = Leaf" |
"delete ks (Node b (l,r)) =
   (case ks of
      [] \<Rightarrow> Node False (l,r) |
      k#ks' \<Rightarrow> Node b (if k then (l, delete ks' r) else (delete ks' l, r)))"

lemma "isin (delete as t) bs = (as \<noteq> bs \<and> isin t bs)"
apply(induction as t arbitrary: bs rule: delete.induct)
apply (auto split: list.splits)
done

fun node :: "bool \<Rightarrow> trie * trie \<Rightarrow> trie" where
"node b lr = (if \<not> b \<and> lr = (Leaf,Leaf) then Leaf else Node b lr)"

fun delete2 :: "bool list \<Rightarrow> trie \<Rightarrow> trie" where
"delete2 ks Leaf = Leaf" |
"delete2 ks (Node b (l,r)) =
   (case ks of
      [] \<Rightarrow> node False (l,r) |
      k#ks' \<Rightarrow> node b (if k then (l, delete2 ks' r) else (delete2 ks' l, r)))"

lemma "isin (delete2 as t) bs = isin (delete as t) bs"
apply(induction as t arbitrary: bs rule: delete2.induct)
 apply simp
apply (force split: list.splits)
done

subsection "Patricia Trie"

datatype ptrie = LeafP | NodeP "bool list" bool "ptrie * ptrie"

fun isinP :: "ptrie \<Rightarrow> bool list \<Rightarrow> bool" where
"isinP LeafP ks = False" |
"isinP (NodeP ps b (l,r)) ks =
  (let n = length ps in
   if ps = take n ks
   then case drop n ks of [] \<Rightarrow> b | k#ks' \<Rightarrow> isinP (if k then r else l) ks'
   else False)"

fun split where
"split [] ys = ([],[],ys)" |
"split xs [] = ([],xs,[])" |
"split (x#xs) (y#ys) =
  (if x\<noteq>y then ([],x#xs,y#ys)
   else let (ps,xs',ys') = split xs ys in (x#ps,xs',ys'))"

fun insertP :: "bool list \<Rightarrow> ptrie \<Rightarrow> ptrie" where
"insertP ks LeafP  = NodeP ks True (LeafP,LeafP)" |
"insertP ks (NodeP ps b (l,r)) =
  (case split ks ps of
     (qs,k#ks',p#ps') \<Rightarrow>
       let tp = NodeP ps' b (l,r); tk = NodeP ks' True (LeafP,LeafP) in
       NodeP qs False (if k then (tp,tk) else (tk,tp)) |
     (qs,k#ks',[]) \<Rightarrow>
       NodeP ps b (if k then (l, insertP ks' r) else (insertP ks' l, r)) |
     (qs,[],p#ps') \<Rightarrow>
       let t = NodeP ps' b (l,r) in
       NodeP qs True (if p then (LeafP,t) else (t,LeafP)) |
     (qs,[],[]) \<Rightarrow> NodeP ps True (l,r))"

fun prefix_trie :: "bool list \<Rightarrow> trie \<Rightarrow> trie" where
"prefix_trie [] t = t" |
"prefix_trie (k#ks) t =
  (let t' = prefix_trie ks t in Node False (if k then (Leaf,t') else (t',Leaf)))"

fun abs_ptrie :: "ptrie \<Rightarrow> trie" where
"abs_ptrie LeafP = Leaf" |
"abs_ptrie (NodeP ps b (l,r)) = prefix_trie ps (Node b (abs_ptrie l, abs_ptrie r))"

lemma isin_prefix_trie: "isin (prefix_trie ps t) ks =
 (length ks \<ge> length ps \<and>
  (let n = length ps in ps = take n ks \<and> isin t (drop n ks)))"
apply(induction ps arbitrary: ks)
apply(auto split: list.split)
done

lemma isinP: "isinP t ks = isin (abs_ptrie t) ks"
apply(induction t arbitrary: ks rule: abs_ptrie.induct)
 apply(auto simp: isin_prefix_trie split: list.split)
 using nat_le_linear apply force
using nat_le_linear apply force
done

lemma prefix_trie_Leafs: "prefix_trie ks (Node True (Leaf,Leaf)) = insert ks Leaf"
apply(induction ks)
apply auto
done

lemma insert_prefix_trie_same:
  "insert ps (prefix_trie ps (Node b lr)) = prefix_trie ps (Node True lr)"
apply(induction ps)
apply auto
done

lemma insert_append: "insert (ks @ k # ks') (prefix_trie ks (Node b (t1,t2))) =
  prefix_trie ks (Node b (if k then (t1, insert ks' t2) else (insert ks' t1, t2)))"
apply(induction ks)
apply auto
done

lemma prefix_trie_append: "prefix_trie (ps @ qs) t = prefix_trie ps (prefix_trie qs t)"
apply(induction ps)
apply auto
done

lemma split_if: "split ks ps = (qs, ks', ps') \<Longrightarrow>
  ks = qs @ ks' \<and> ps = qs @ ps' \<and> (ks' \<noteq> [] \<and> ps' \<noteq> [] \<longrightarrow> hd ks' \<noteq> hd ps')"
apply(induction ks ps arbitrary: qs ks' ps' rule: split.induct)
apply(auto split: prod.splits if_splits)
done

lemma abs_ptrie_insertP:
  "abs_ptrie (insertP ks t) = insert ks (abs_ptrie t)"
apply(induction t arbitrary: ks)
apply(auto simp: prefix_trie_Leafs insert_prefix_trie_same insert_append prefix_trie_append
           dest!: split_if split: list.split prod.split)
done

corollary isinP_insertP: "isinP (insertP ks t) ks' = (ks=ks' \<or> isinP t ks')"
by (simp add: isin_insert isinP abs_ptrie_insertP)

end


theory soma
  imports Main
begin
primrec soma::"nat \<Rightarrow> nat \<Rightarrow> nat" where
somaeq1:"soma x 0 = x"|
somaeq2:"soma x (Suc y) = Suc (soma x y)"

thm nat.induct
print_statement nat.induct

value "soma 1 0"
value "soma 1 1"

theorem soma1:"\<forall>x. soma x y = x + y"
proof (induct y)
  show "\<forall>x. soma x 0 = x + 0"
  proof (rule allI)
    fix x0::nat
    have "soma x0 0 = x0" by (simp only:somaeq1)
    also have "... = x0 + 0" by simp
    finally show "soma x0 0 = x0 + 0" by simp
  qed
next
  fix y0::nat
  assume HI:"\<forall>x. soma x y0 = x + y0"
  show "\<forall>x. soma x (Suc y0) = x + (Suc y0)"
  proof (rule allI)
    fix x0::nat
    have "soma x0 (Suc y0) = Suc (soma x0 y0)" by (simp only:somaeq2)
    also have "... = Suc (x0 + y0)" by (simp only:HI)
    also have "... = x0 + (Suc y0)" by simp
    finally show "soma x0 (Suc y0) = x0 + (Suc y0)" by simp
  qed
qed

theorem soma2:"\<forall>x. soma x y = soma y x"
proof (induct y)
  show "\<forall>x. soma x 0 = soma 0 x"
  proof (rule allI)
    fix x0::nat
    have "soma x0 0 = x0" by (simp only:somaeq1)
    also have "... = 0 + x0" by simp
    also have "... = soma 0 x0" by (simp only:soma1)
    finally show "soma x0 0 = soma 0 x0" by simp
  qed
next
  fix y0::nat
  assume HI:"\<forall>x. soma x y0 = soma y0 x"
  show "\<forall>x. soma x (Suc y0) = soma (Suc y0) x"
  proof (rule allI)
    fix x0::nat
    have "soma x0 (Suc y0) = Suc (soma x0 y0)" by (simp only:somaeq2)
    also have "... = Suc (soma y0 x0)" by (simp only:HI)
    also  have "... = soma (Suc y0) x0" by (simp only:soma1)
    finally show "soma x0 (Suc y0) = soma (Suc y0) x0" by simp
  qed
qed

theorem soma3:"\<forall>x. soma x (Suc y) = soma (Suc x) y"
proof (induct y)
  show "\<forall>x. soma x (Suc 0) = soma (Suc x) 0"
  proof (rule allI)
    fix x0::nat
    have "soma x0 (Suc 0) = Suc (soma x0 0)" by (simp only:somaeq2)
    also have "... = Suc (x0)" by (simp only:somaeq1)
    also have "... = soma (Suc x0) 0" by (simp only:soma1)
    finally show "soma x0 (Suc 0) = soma (Suc x0) 0" by simp
  qed
next
  fix y0::nat
  assume HI:"\<forall>x. soma x (Suc y0) = soma (Suc x) y0"
  show "\<forall>x. soma x (Suc (Suc y0)) = soma (Suc x) (Suc y0)"
  proof (rule allI)
    fix x0::nat
    have "soma x0 (Suc (Suc y0)) = Suc (soma x0 (Suc y0))" by (simp only:somaeq2)
    also have "... = Suc (soma (Suc x0) y0)" by (simp only:HI)
    also have "... = soma (Suc x0) (Suc y0)" by (simp only:soma1)
    finally show "soma x0 (Suc (Suc y0)) = soma (Suc x0) (Suc y0)" by simp
  qed
qed

end


theory E4_5
  imports Main
begin

inductive star :: "('a \<Rightarrow> 'a \<Rightarrow> bool) \<Rightarrow> 'a \<Rightarrow> 'a \<Rightarrow> bool" for r where
refl : "star r x x" |
step : "r x y \<Longrightarrow> star r y z \<Longrightarrow> star r x z"

inductive iter :: "('a \<Rightarrow> 'a \<Rightarrow> bool) \<Rightarrow> nat \<Rightarrow> 'a \<Rightarrow> 'a \<Rightarrow> bool" for r where
iter0 : "iter r n x x" |
iter1 : "r x y \<Longrightarrow> iter r 1 x y \<Longrightarrow> iter r n y z \<Longrightarrow> iter r (n + 1) x z" |
iter2 : "iter r n x y \<Longrightarrow> r y z \<Longrightarrow> iter r (n + 1) x z" |
iter3 : "iter r n x y \<Longrightarrow> iter r m y z \<Longrightarrow> iter r (m + n) x z"

lemma star_trans[simp, intro] : "star r x y \<Longrightarrow> star r y z \<Longrightarrow> star r x z"
proof (induction rule : star.induct)
  case (refl x)
  thus ?case by auto
next
  case (step x y z)
  thus ?case by (meson star.step)
qed

lemma "iter r n x y \<Longrightarrow> star r x y"
proof (induction rule : iter.induct)
  case (iter0 n x)
  then show ?case by (meson star.simps)
next
  case (iter1 x y n z)
  then show ?case by blast
next
  case (iter2 n x y z)
  then show ?case by (meson star.refl star.step star_trans)
next
  case (iter3 n x y m z)
  then show ?case by blast
qed

end


theory Submission
imports Defs "HOL-Library.Sublist"
begin

subsection \<open>Some lemmas about \<^const>\<open>takeWhile\<close> and \<^const>\<open>dropWhile\<close>\<close>

(* TODO Move all of this *)
lemma takeWhile_eq_Nil [simp]: "xs = [] \<or> \<not>P (hd xs) \<Longrightarrow> takeWhile P xs = []"
  by (cases xs) auto

lemma dropWhile_eq_self [simp]: "xs = [] \<or> \<not>P (hd xs) \<Longrightarrow> dropWhile P xs = xs"
  by (cases xs) auto

lemma takeWhile_append3: "ys = [] \<or> \<not>P (hd ys) \<Longrightarrow> takeWhile P (xs @ ys) = takeWhile P xs"
  by (induction xs) auto

lemma takeWhile_append:
  "takeWhile P (xs @ ys) = (if \<forall>x\<in>set xs. P x then xs @ takeWhile P ys else takeWhile P xs)"
  using takeWhile_append1[of _ xs P ys] takeWhile_append2[of xs P ys] by auto

lemma takeWhile_replicate: "takeWhile P (replicate n x) = (if P x then replicate n x else [])"
  and dropWhile_replicate: "dropWhile P (replicate n x) = (if P x then [] else replicate n x)"
  by (induction n; simp)+

lemma takeWhile_replicate_True [simp]: "P x \<Longrightarrow> takeWhile P (replicate n x) = replicate n x"
  and takeWhile_replicate_False [simp]: "\<not>P x \<Longrightarrow> takeWhile P (replicate n x) = []"
  and dropWhile_replicate_True [simp]: "P x \<Longrightarrow> dropWhile P (replicate n x) = []"
  and dropWhile_replicate_False [simp]: "\<not>P x \<Longrightarrow> dropWhile P (replicate n x) = replicate n x"
  by (simp_all add: takeWhile_replicate dropWhile_replicate)

lemma takeWhile_replicate_append_True [simp]:
        "P x \<Longrightarrow> takeWhile P (replicate n x @ xs) = replicate n x @ takeWhile P xs"
  and takeWhile_replicate_append_False [simp]:
        "\<not>P x \<Longrightarrow> n > 0 \<Longrightarrow> takeWhile P (replicate n x @ xs) = []"
  and dropWhile_replicate_append_True [simp]:
        "P x \<Longrightarrow> dropWhile P (replicate n x @ xs) = dropWhile P xs"
  and dropWhile_replicate_append_False [simp]:
        "\<not>P x \<Longrightarrow> n > 0 \<Longrightarrow> dropWhile P (replicate n x @ xs) = replicate n x @ xs"
     by (induction n; simp; fail)+

subsection \<open>Applying a relation to successive elements in a list\<close>

inductive successively :: "('a \<Rightarrow> 'a \<Rightarrow> bool) \<Rightarrow> 'a list \<Rightarrow> bool" for P where
  "successively P []"
| "successively P [x]"
| "P x y \<Longrightarrow> successively P (y # xs) \<Longrightarrow> successively P (x # y # xs)"

lemmas [simp, intro] = successively.intros(1,2)

lemma successively_Cons_Cons [simp]:
  "successively P (x # y # xs) \<longleftrightarrow> P x y \<and> successively P (y # xs)"
  by (subst successively.simps) auto

lemma successively_Cons:
  "successively P (x # xs) \<longleftrightarrow> xs = [] \<or> P x (hd xs) \<and> successively P xs"
  by (cases xs) auto

lemma successively_ConsI [intro]:
  "P x (hd xs) \<Longrightarrow> successively P xs \<Longrightarrow> successively P (x # xs)"
  by (auto simp: successively_Cons)

lemma successively_ConsD [dest]:
  "successively P (x # xs) \<Longrightarrow> successively P xs"
  by (auto simp: successively_Cons)

lemma successively_append_iff:
  "successively P (xs @ ys) \<longleftrightarrow>
     successively P xs \<and> successively P ys \<and>
     (xs = [] \<or> ys = [] \<or> P (last xs) (hd ys))"
  by (induction xs) (auto simp: successively_Cons)

lemma
  assumes "successively P (xs @ ys)"
  shows   successively_appendD1 [dest]: "successively P xs"
    and   successively_appendD2 [dest]: "successively P ys"
  using assms by (auto simp: successively_append_iff)

lemma successively_appendI [intro?]:
  assumes "successively P xs" "successively P ys" "xs = [] \<or> ys = [] \<or> P (last xs) (hd ys)"
  shows   "successively P (xs @ ys)"
  using assms by (auto simp: successively_append_iff)

lemma successively_sublist:
  assumes "successively P ys" "sublist xs ys"
  shows   "successively P xs"
  using assms by (auto simp: sublist_def)

lemma sorted_wrt_imp_successively: "sorted_wrt P xs \<Longrightarrow> successively P xs"
  by (induction xs rule: induct_list012) auto

lemma successively_conv_sorted_wrt:
  assumes "\<And>x y z. x \<in> set xs \<Longrightarrow> y \<in> set xs \<Longrightarrow> z \<in> set xs \<Longrightarrow>
                   P x y \<Longrightarrow> P y z \<Longrightarrow> P x z"
  shows   "successively P xs \<longleftrightarrow> sorted_wrt P xs"
proof
  assume "successively P xs"
  from this and assms show "sorted_wrt P xs"
  proof (induction rule: successively.induct)
    case (3 x y xs)
    have IH: "sorted_wrt P (y # xs)"
      using "3.prems" unfolding set_simps(2)[of _ "y # xs"] by (intro "3.IH") blast
    have "P x z" if "z \<in> set xs" for z
    proof -
      from "3.hyps" have "P x y"
        by auto
      moreover from IH and that have "P y z"
        by auto
      ultimately show "P x z"
        using "3.prems" that by auto
    qed
    with IH and \<open>P x y\<close> show ?case by auto
  qed auto
qed (use sorted_wrt_imp_successively in blast)

lemma successively_conv_sorted_wrt':
  assumes "transp P"
  shows   "successively P xs \<longleftrightarrow> sorted_wrt P xs"
  using assms unfolding transp_def
  by (intro successively_conv_sorted_wrt) blast

subsection \<open>Lists without repeated adjacent elements\<close>

definition adj_distinct where
  "adj_distinct = successively (\<noteq>)"

lemmas adj_distinct_induct = successively.induct[of "(\<noteq>)", folded adj_distinct_def, consumes 1]

lemma adj_distinct_Nil [simp]: "adj_distinct []"
  and adj_distinct_singleton [simp]: "adj_distinct [x]"
  by (auto simp: adj_distinct_def)

lemma adj_distinct_Cons_Cons [simp]: "adj_distinct (x # y # xs) \<longleftrightarrow> x \<noteq> y \<and> adj_distinct (y # xs)"
  by (auto simp: adj_distinct_def)

lemma adj_distinct_Cons: "adj_distinct (x # xs) \<longleftrightarrow> xs = [] \<or> x \<noteq> hd xs \<and> adj_distinct xs"
  by (cases xs) auto

lemma adj_distinct_ConsI [intro?]: "x \<noteq> hd xs \<and> adj_distinct xs \<Longrightarrow> adj_distinct (x # xs)"
  by (cases xs) auto

lemma adj_distinct_ConsD1 [dest]: "adj_distinct (x # xs) \<Longrightarrow> xs \<noteq> [] \<Longrightarrow> x \<noteq> hd xs"
  by (cases xs) auto

lemma adj_distinct_ConsD2 [dest]: "adj_distinct (x # xs) \<Longrightarrow> adj_distinct xs"
  by (cases xs) auto

lemma adj_distinct_remdups_adj [intro]: "adj_distinct (remdups_adj xs)"
  by (induction xs rule: remdups_adj.induct) (auto simp: adj_distinct_Cons)

lemma adj_distinct_altdef: "adj_distinct xs \<longleftrightarrow> remdups_adj xs = xs"
proof
  assume eq: "remdups_adj xs = xs"
  have "adj_distinct (remdups_adj xs)"
    by blast
  with eq show "adj_distinct xs"
    by simp
next
  assume "adj_distinct xs"
  thus "remdups_adj xs = xs"
    by (induction rule: adj_distinct_induct) auto
qed

lemma adj_distinct_rev [simp]: "adj_distinct (rev xs) \<longleftrightarrow> adj_distinct xs"
  by (simp add: adj_distinct_altdef)

lemma adj_distinct_append_iff:
  "adj_distinct (xs @ ys) \<longleftrightarrow>
     adj_distinct xs \<and> adj_distinct ys \<and> (xs = [] \<or> ys = [] \<or> last xs \<noteq> hd ys)"
  by (auto simp: adj_distinct_def successively_append_iff)

lemma adj_distinct_appendD1 [dest]: "adj_distinct (xs @ ys) \<Longrightarrow> adj_distinct xs"
  and adj_distinct_appendD2 [dest]: "adj_distinct (xs @ ys) \<Longrightarrow> adj_distinct ys"
  by (auto simp: adj_distinct_append_iff)

lemma adj_distinct_sublist:
  assumes "adj_distinct ys" "sublist xs ys"
  shows   "adj_distinct xs"
  using assms by (auto simp: sublist_def)

subsection \<open>Run-length encoding\<close>

lemmas [termination_simp] = length_dropWhile_le

text \<open>
  The following function performs run-length encoding of a list, converting each run of \<open>n > 0\<close>
  successive equal elements \<open>x\<close> into a single element \<open>(x, n)\<close>.
\<close>

lemma length_rle: "length (rle xs) \<le> length xs"
  by (induction xs rule: rle.induct) (auto intro: order.trans[OF _ length_dropWhile_le])

lemma rle_eq_Nil_iff [simp]: "rle xs = [] \<longleftrightarrow> xs = []"
  by (cases xs) auto

lemma Nil_eq_rle_iff [simp]: "[] = rle xs \<longleftrightarrow> xs = []"
  by (cases xs) auto

lemma rle_replicate: "rle (replicate n x) = (if n = 0 then [] else [(x, n)])"
  by (cases n) auto

lemma rle_replicate' [simp]: "n > 0 \<Longrightarrow> rle (replicate n x) = [(x, n)]"
  by (subst rle_replicate) auto

lemma fst_hd_rle [simp]: "xs \<noteq> [] \<Longrightarrow> fst (hd (rle xs)) = hd xs"
  by (cases xs) auto

lemma map_fst_run_le [simp]: "map fst (rle xs) = remdups_adj xs"
  by (induction xs rule: remdups_adj.induct) auto

lemma fst_set_rle [simp]: "fst ` set (rle xs) = set xs"
proof -
  have "fst ` set (rle xs) = set (map fst (rle xs))"
    by (rule set_map [symmetric])
  also have "map fst (rle xs) = remdups_adj xs"
    by simp
  finally show ?thesis
    by simp
qed

lemma snd_rle_pos: "n \<in> snd ` set (rle xs) \<Longrightarrow> n > 0"
  by (induction xs rule: rle.induct) auto

text \<open>
  A valid run-length encoding contains no zero-length runs, and two adjacent runs always
  have a different element.
\<close>
definition valid_rle :: "('a \<times> nat) list \<Rightarrow> bool" where
  "valid_rle xs \<longleftrightarrow> 0 \<notin> snd ` set xs \<and> adj_distinct (map fst xs)"

lemma valid_rle_append_iff [intro]:
  "valid_rle (xs @ ys) \<longleftrightarrow>
     valid_rle xs \<and> valid_rle ys \<and> (xs = [] \<or> ys = [] \<or> fst (last xs) \<noteq> fst (hd ys))"
  by (auto simp: valid_rle_def adj_distinct_append_iff last_map hd_map)

lemma
  assumes "valid_rle (xs @ ys)"
  shows valid_rle_appendD1 [dest]: "valid_rle xs"
    and valid_rle_appendD2 [dest]: "valid_rle ys"
  using assms by (auto simp: valid_rle_append_iff)

lemma valid_rle_ConsD [dest]: "valid_rle (x # xs) \<Longrightarrow> valid_rle xs"
  by (auto simp: valid_rle_def)

lemma valid_rle_rle [intro]: "valid_rle (rle xs)"
  using snd_rle_pos[of _ xs] by (auto simp: valid_rle_def)

lemma valid_rle_rev [simp]: "valid_rle (rev xs) \<longleftrightarrow> valid_rle xs"
  by (auto simp: valid_rle_def simp flip: rev_map)

text \<open>
  The inverse of the run-length encoding function:
\<close>
definition unrle
  where "unrle = concat \<circ> map (\<lambda>(x, n). replicate n x)"

lemma unrle_Nil [simp]: "unrle [] = []"
  and unrle_Cons [simp]: "unrle (x # xs) = replicate (snd x) (fst x) @ unrle xs"
  and unrle_append [simp]: "unrle (xs @ ys) = unrle xs @ unrle ys"
  and unrle_rev [simp]: "unrle (rev xs) = rev (unrle xs)"
  by (auto simp: unrle_def case_prod_unfold rev_concat rev_map o_def)

lemma unrle_eq_Nil_iff [simp]: "unrle xs = [] \<longleftrightarrow> snd ` set xs \<subseteq> {0}"
  by (induction xs) auto

lemma unrle_Nil_eq_iff [simp]: "Nil = unrle xs \<longleftrightarrow> snd ` set xs \<subseteq> {0}"
  by (induction xs) auto

lemma hd_unrle [simp]: "xs \<noteq> [] \<Longrightarrow> snd (hd xs) > 0 \<Longrightarrow> hd (unrle xs) = fst (hd xs)"
  by (cases xs) (auto simp: unrle_def)

lemma unrle_map_1 [simp]: "unrle (map (\<lambda>x. (x, Suc 0)) xs) = xs"
  by (induction xs) (auto simp: unrle_def o_def)

lemma unrle_rle [simp]: "unrle (rle xs) = xs"
proof (induction xs rule: rle.induct)
  case (2 x xs)
  have "replicate (length (takeWhile (\<lambda>y. y = x) xs)) x = takeWhile (\<lambda>y. y = x) xs"
    by (induction xs) auto
  thus ?case
    using 2 by simp
qed auto

lemma rle_unrle [simp]:
  assumes "valid_rle xs"
  shows   "rle (unrle xs) = xs"
  using assms
proof (induction xs)
  case (Cons x' xs)
  obtain x n where [simp]: "x' = (x, n)"
    by (cases x')
  have [simp]: "n > 0" "n \<noteq> 0"
    using Cons.prems by (auto simp: valid_rle_def)
  show ?case
  proof (cases "xs = []")
    case [simp]: False
    have [simp]: "snd (hd xs) > 0" "x \<noteq> fst (hd xs)"
      using Cons.prems by (auto simp: valid_rle_def adj_distinct_Cons hd_map)
    have "takeWhile (\<lambda>y. y = x) (unrle xs) = []"
         "dropWhile (\<lambda>y. y = x) (unrle xs) = unrle xs"
      by (subst takeWhile_eq_Nil dropWhile_eq_self; force; fail)+
    hence "rle (replicate n x @ unrle xs) = (x, n) # rle (unrle xs)"
      by (cases n) auto
    thus ?thesis
      using Cons by (auto simp: valid_rle_def adj_distinct_Cons hd_unrle)
  qed auto
qed auto

text \<open>
  The \<^const>\<open>unrle\<close> function is injective on all valid run-length encodings
\<close>
lemma unrle_eqD [simp]:
  assumes "valid_rle xs" "valid_rle ys"
  assumes "unrle xs = unrle ys"
  shows   "xs = ys"
proof -
  have "rle (unrle xs) = rle (unrle ys)"
    by (simp add: assms(3))
  with assms(1,2) show ?thesis
    by (subst (asm) (1 2) rle_unrle) auto
qed

text \<open>
  The injectivity of \<^const>\<open>unrle\<close> allows us to show several properties of \<^const>\<open>rle\<close> more
  easily using the following lemma:
\<close>
lemma rle_eqI:
  assumes "valid_rle ys" "unrle ys = xs"
  shows "rle xs = ys"
  by (rule unrle_eqD) (use assms in auto)

lemma rle_rev [simp]: "rle (rev xs) = rev (rle xs)"
  by (rule rle_eqI) auto

lemma fst_last_rle [simp]: "xs \<noteq> [] \<Longrightarrow> fst (last (rle xs)) = last xs"
  by (simp flip: hd_rev rle_rev)

lemma rle_append:
  assumes "xs = [] \<or> ys = [] \<or> last xs \<noteq> hd ys"
  shows   "rle (xs @ ys) = rle xs @ rle ys"
  by (rule rle_eqI) (use assms in \<open>auto simp: valid_rle_append_iff\<close>)

lemma rle_of_adj_distinct: "adj_distinct xs \<Longrightarrow> rle xs = map (\<lambda>x. (x, 1)) xs"
  by (rule rle_eqI) (auto simp: valid_rle_def o_def)

lemma rle_rev_if_rle_append: "(xs = [] \<or> ys = [] \<or> last xs \<noteq> hd ys \<Longrightarrow> rle (xs @ ys) = rle xs @ rle ys)
       \<Longrightarrow>rle (rev xs) = rev (rle xs)"
  by (rule rle_eqI) auto

end


theory Sorted
imports "$HIPSTER_HOME/IsaHipster"

begin
datatype Nat =
  Z
  | Succ "Nat"

fun leq :: "Nat => Nat => bool"
where
  "leq Z y = True"
| "leq x Z = False"
| "leq (Succ x) (Succ y) = leq x y"

(*hipster leq*)
lemma lemma_a [thy_expl]: "leq x2 x2 = True"
by (hipster_induct_simp_metis Sorted.leq.simps)

lemma lemma_aa [thy_expl]: "leq x2 (Succ x2) = True"
by (hipster_induct_simp_metis Sorted.leq.simps)

lemma lemma_ab [thy_expl]: "leq (Succ x2) x2 = False"
by (hipster_induct_simp_metis Sorted.leq.simps)

fun sorted :: "Nat list => bool"
where
  "sorted [] = True"
| "sorted [x] = True"
| "sorted (x # y # xs) = ((leq x y) \<and> (sorted (y#xs)))"
thm sorted.induct

fun last :: "'a list \<Rightarrow> 'a" where
  "last ([t]) = t"
| "last (_ # ts) = last ts"
thm last.induct

fun ins :: " Nat => Nat list => Nat list"
where
 "ins x [] = [x]"
|"ins x (y#ys) = (if (leq x y) then (x#y#ys) else (y#(ins x ys)))"
thm ins.induct

(*hipster sorted ins*)
lemma lemma_ac [thy_expl]: "leq x2 x2 = True"
by (tactic \<open>Hipster_Tacs.induct_simp_metis @{context} @{thms Sorted.sorted.simps Sorted.ins.simps thy_expl}\<close>)

lemma lemma_ad [thy_expl]: "Sorted.sorted (ins Z x2) = Sorted.sorted x2"
by (tactic \<open>Hipster_Tacs.induct_simp_metis @{context} @{thms Sorted.sorted.simps Sorted.ins.simps thy_expl}\<close>)

lemma unknown [thy_expl]: "ins Z (ins x y) = ins x (ins Z y)"
oops

lemma unknown [thy_expl]: "ins x (ins y z) = ins y (ins x z)"
oops

lemma unknown [thy_expl]: "Sorted.sorted (ins x y) = Sorted.sorted y"
oops

fun isort :: "Nat list => Nat list"
where
  "isort [] = []"
| "isort (x#xs) = ins x (isort xs)"

lemma unknown [thy_expl]: "Sorted.sorted x \<Longrightarrow> isort x = x"
oops

(*hipster sorted ins isort*)
(*hipster_cond sorted isort*)
ML \<open>
  val _ = Proof_Context.init_global
\<close>
(*hipster_cond sorted isort leq sorted ins*)
lemma lemma_ae [thy_expl]: "ins Z (isort x2) = isort (ins Z x2)"
by (hipster_induct_simp_metis Sorted.sorted.simps Sorted.isort.simps Sorted.leq.simps Sorted.sorted.simps Sorted.ins.simps)
(*
lemma unknown [thy_expl]: "ins x (ins y z) = ins y (ins x z)"
oops

lemma unknown [thy_expl]: "Sorted.sorted (ins x y) = Sorted.sorted y"
oops

lemma unknown [thy_expl]: "isort (ins x y) = ins x (isort y)"
oops

lemma unknown [thy_expl]: "Sorted.sorted (isort x) = True"
oops

lemma unknown [thy_expl]: "isort (isort x) = isort x"
oops

lemma unknown [thy_expl]: "ins Z (ins x y) = ins x (ins Z y)"
oops

lemma unknown [thy_expl]: "Sorted.sorted x \<Longrightarrow> isort x = x"
oops *)

lemma insSortInvarZ [simp] : "sorted ts \<Longrightarrow> sorted (ins Z ts)"
by (hipster_induct_simp_metis Sorted.sorted.simps Sorted.ins.simps)
lemma insSortInvar: "sorted ts \<Longrightarrow> sorted (ins x ts)"
apply(case_tac x)
apply(simp_all)
apply(induction ts rule: ins.induct)
apply(simp_all)
apply (hipster_induct_simp_metis Sorted.sorted.simps Sorted.ins.simps Sorted.leq.simps)
oops

(*
lemma unknown [thy_expl]: "Sorted.sorted y \<Longrightarrow> Sorted.sorted (ins x y) = True"
oops

lemma unknown [thy_expl]: "Sorted.sorted y \<Longrightarrow> isort (ins x y) = ins x y"
oops

lemma unknown [thy_expl]: "Sorted.sorted x \<Longrightarrow> isort (ins Z x) = ins Z x"
oops *)

end


(*  Title:      HOL/Examples/AckermannM.thy
    Author:     Larry Paulson
*)

section \<open>A Tail-Recursive, Stack-Based Ackermann's Function\<close>

text \<open>Unlike the other Ackermann example, this termination proof uses the argument from
Nachum Dershowitz and Zohar Manna. Proving termination with multiset orderings.
Communications of the ACM 22 (8) 1979, 465–476.\<close>

theory AckermannM imports "HOL-Library.Multiset_Order" "HOL-Library.Product_Lexorder"

begin

text\<open>This theory investigates a stack-based implementation of Ackermann's function.
Let's recall the traditional definition,
as modified by R{\'o}zsa P\'eter and Raphael Robinson.\<close>

fun ack :: "[nat,nat] \<Rightarrow> nat" where
  "ack 0 n             = Suc n"
| "ack (Suc m) 0       = ack m 1"
| "ack (Suc m) (Suc n) = ack m (ack (Suc m) n)"

text\<open>Setting up the termination proof for the stack-based version.\<close>

fun ack_mset :: "nat list \<Rightarrow> (nat\<times>nat) multiset" where
  "ack_mset [] = {#}"
| "ack_mset [x] = {#}"
| "ack_mset (z#y#l) =  mset ((y,z) # map (\<lambda>x. (Suc x, 0)) l)"

lemma case1: "ack_mset (Suc n # l) < add_mset (0, n) {#(Suc x, 0). x \<in># mset l#}"
proof (cases l)
  case (Cons m list)
  have "{#(m, Suc n)#} < {#(Suc m, 0)#}"
    by auto
  also have "\<dots> \<le> {#(Suc m, 0), (0,n)#}"
    by auto
  finally show ?thesis
    by (simp add: Cons)
qed auto

text\<open>Here is the stack-based version, which uses lists.\<close>

function ackloop :: "nat list \<Rightarrow> nat" where
  "ackloop (n # 0 # l)         = ackloop (Suc n # l)"
| "ackloop (0 # Suc m # l)     = ackloop (1 # m # l)"
| "ackloop (Suc n # Suc m # l) = ackloop (n # Suc m # m # l)"
| "ackloop [m] = m"
| "ackloop [] =  0"
  by pat_completeness auto

termination
  by (relation "inv_image {(x,y). x<y} ack_mset") (auto simp: wf case1)

text \<open>Unlike the other Ackermann theory, no extra function is needed to prove equivalence\<close>
lemma ackloop_ack: "ackloop (n # m # l) = ackloop (ack m n # l)"
  by (induction m n arbitrary: l rule: ack.induct) auto

theorem ack: "ack m n = ackloop [n,m]"
  by (simp add: ackloop_ack)

end


(*
    Author:      René Thiemann
                 Akihisa Yamada
    License:     BSD
*)
section \<open>Neville Aitken Interpolation\<close>

text \<open>We prove soundness of Neville-Aitken's polynomial interpolation algorithm
  using the recursive formula directly. We further provide an implementation
  which avoids the exponential branching in the recursion.\<close>

theory Neville_Aitken_Interpolation
imports
  "HOL-Computational_Algebra.Polynomial"
begin

context
  fixes x :: "nat \<Rightarrow> 'a :: field"
  and f :: "nat \<Rightarrow> 'a"
begin

private definition X :: "nat \<Rightarrow> 'a poly" where [code_unfold]: "X i = [:-x i, 1:]"

function neville_aitken_main :: "nat \<Rightarrow> nat \<Rightarrow> 'a poly" where
  "neville_aitken_main i j = (if i < j then
      (smult (inverse (x j - x i)) (X i * neville_aitken_main (i + 1) j -
      X j * neville_aitken_main i (j - 1)))
    else [:f i:])"
  by pat_completeness auto

termination by (relation "measure (\<lambda> (i,j). j - i)", auto)

definition neville_aitken :: "nat \<Rightarrow> 'a poly" where
  "neville_aitken = neville_aitken_main 0"

declare neville_aitken_main.simps[simp del]

lemma neville_aitken_main: assumes dist: "\<And> i j. i < j \<Longrightarrow> j \<le> n \<Longrightarrow> x i \<noteq> x j"
  shows "i \<le> k \<Longrightarrow> k \<le> j \<Longrightarrow> j \<le> n \<Longrightarrow> poly (neville_aitken_main i j) (x k) = (f k)"
proof (induct i j arbitrary: k rule: neville_aitken_main.induct)
  case (1 i j k)
  note neville_aitken_main.simps[of i j, simp]
  show ?case
  proof (cases "i < j")
    case False
    with 1(3-) have "k = i" by auto
    with False show ?thesis by auto
  next
    case True note ij = this
    from dist[OF True 1(5)] have diff: "x i \<noteq> x j" by auto
    from True have id: "neville_aitken_main i j =
      (smult (inverse (x j - x i)) (X i * neville_aitken_main (i + 1) j - X j
        * neville_aitken_main i (j - 1)))" by simp
    note IH = 1(1-2)[OF True]
    show ?thesis
    proof (cases "k = i")
      case True
      show ?thesis unfolding id True poly_smult using IH(2)[of i] ij 1(3-) diff
        by (simp add: X_def field_simps)
    next
      case False note ki = this
      show ?thesis
      proof (cases "k = j")
        case True
        show ?thesis unfolding id True poly_smult using IH(1)[of j] ij 1(3-) diff
          by (simp add: X_def field_simps)
      next
        case False
        with ki show ?thesis unfolding id poly_smult using IH(1-2)[of k] ij 1(3-) diff
          by (simp add: X_def field_simps)
      qed
    qed
  qed
qed

lemma degree_neville_aitken_main: "degree (neville_aitken_main i j) \<le> j - i"
proof (induct i j rule: neville_aitken_main.induct)
  case (1 i j)
  note simp = neville_aitken_main.simps[of i j]
  show ?case
  proof (cases "i < j")
    case False
    thus ?thesis unfolding simp by simp
  next
    case True
    note IH = 1[OF this]
    let ?n = neville_aitken_main
    have X: "\<And> i. degree (X i) = Suc 0" unfolding X_def by auto
    have "degree (X i * ?n (i + 1) j) \<le> Suc (degree (?n (i+1) j))"
      by (rule order.trans[OF degree_mult_le], simp add: X)
    also have "\<dots> \<le> Suc (j - (i+1))" using IH(1) by simp
    finally have 1: "degree (X i * ?n (i + 1) j) \<le> j - i" using True by auto
    have "degree (X j * ?n i (j - 1)) \<le> Suc (degree (?n i (j - 1)))"
      by (rule order.trans[OF degree_mult_le], simp add: X)
    also have "\<dots> \<le> Suc ((j - 1) - i)" using IH(2) by simp
    finally have 2: "degree (X j * ?n i (j - 1)) \<le> j - i" using True by auto
    have id: "?n i j = smult (inverse (x j - x i))
            (X i * ?n (i + 1) j - X j * ?n i (j - 1))" unfolding simp using True by simp
    have "degree (?n i j) \<le> degree (X i * ?n (i + 1) j - X j * ?n i (j - 1))"
      unfolding id by simp
    also have "\<dots> \<le> max (degree (X i * ?n (i + 1) j)) (degree (X j * ?n i (j - 1)))"
      by (rule degree_diff_le_max)
    also have "\<dots> \<le> j - i" using 1 2 by auto
    finally show ?thesis .
  qed
qed

lemma degree_neville_aitken: "degree (neville_aitken n) \<le> n"
  unfolding neville_aitken_def using degree_neville_aitken_main[of 0 n] by simp

fun neville_aitken_merge :: "('a \<times> 'a \<times> 'a poly) list \<Rightarrow> ('a \<times> 'a \<times> 'a poly) list" where
  "neville_aitken_merge ((xi,xj,p_ij) # (xsi,xsj,p_sisj) # rest) =
     (xi,xsj, smult (inverse (xsj - xi)) ([:-xi,1:] * p_sisj
      + [:xsj,-1:] * p_ij)) # neville_aitken_merge ((xsi,xsj,p_sisj) # rest)"
| "neville_aitken_merge [_] = []"
| "neville_aitken_merge [] = []"

lemma length_neville_aitken_merge[termination_simp]: "length (neville_aitken_merge xs) = length xs - 1"
  by (induct xs rule: neville_aitken_merge.induct, auto)

fun neville_aitken_impl_main :: "('a \<times> 'a \<times> 'a poly) list \<Rightarrow> 'a poly" where
  "neville_aitken_impl_main (e1 # e2 # es) =
     neville_aitken_impl_main (neville_aitken_merge (e1 # e2 # es))"
| "neville_aitken_impl_main [(_,_,p)] = p"
| "neville_aitken_impl_main [] = 0"

lemma neville_aitken_merge:
  "xs = map (\<lambda> i. (x i, x (i + j), neville_aitken_main i (i + j)))  [l ..< Suc (l + k)]
   \<Longrightarrow> neville_aitken_merge xs
       = (map (\<lambda> i. (x i, x (i + Suc j), neville_aitken_main i (i + Suc j))) [l ..< l + k])"
proof (induct xs arbitrary: l k rule: neville_aitken_merge.induct)
  case (1 xi xj p_ij xsi xsj p_sisj rest l k)
  let ?n = neville_aitken_main
  let ?f = "\<lambda> j i. (x i, x (i + j), ?n i (i + j))"
  define f where "f = ?f"
  let ?map = "\<lambda> j. map (?f j)"
  note res = 1(2)
  from arg_cong[OF res, of length] obtain kk where k: "k = Suc kk" by (cases k, auto)
  hence id: "[l..<Suc (l + k)] = l # [Suc l ..< Suc (Suc l + kk)]"
    by (simp add: upt_rec)
  from res[unfolded id] have id2: "(xsi, xsj, p_sisj) # rest =
    ?map j [Suc l..< Suc (Suc l + kk)]"
    and id3: "xi = x l" "xj = x (l + j)" "p_ij = ?n l (l + j)"
        "xsi = x (Suc l)" "xsj = x (Suc (l + j))" "p_sisj = ?n (Suc l) (Suc (l + j))"
      by (auto simp: upt_rec)
  note IH = 1(1)[OF id2]
  have X: "[:x (Suc (l + j)), - 1:] = - X (Suc l + j)" unfolding X_def by simp
  have id4: "(xi, xsj, smult (inverse (xsj - xi)) ([:- xi, 1:] * p_sisj +
     [:xsj, - 1:] * p_ij)) = (x l, x (l + Suc j), ?n l (l + Suc j))"
    unfolding id3 neville_aitken_main.simps[of l "l + Suc j"]
      X_def[symmetric] X by simp
  have id5: "[l..<l + k] = l # [Suc l ..< Suc l + kk]" unfolding k
    by (simp add: upt_rec)
  show ?case unfolding neville_aitken_merge.simps IH id4
    unfolding id5 by simp
qed auto

lemma neville_aitken_impl_main:
  "xs = map (\<lambda> i. (x i, x (i + j), neville_aitken_main i (i + j)))  [l ..< Suc (l + k)]
   \<Longrightarrow> neville_aitken_impl_main xs = neville_aitken_main l (l + j + k)"
proof (induct xs arbitrary: l k j rule: neville_aitken_impl_main.induct)
  case (1 e1 e2 es l k j)
  note res = 1(2)
  from res obtain kk where k: "k = Suc kk" by (cases k, auto)
  hence id1: "l + k = Suc (l + kk)" by auto
  show ?case unfolding neville_aitken_impl_main.simps 1(1)[OF neville_aitken_merge[OF 1(2), unfolded id1]]
    by (simp add: k)
qed auto

lemma neville_aitken: assumes "\<And> i j. i < j \<Longrightarrow> j \<le> n \<Longrightarrow> x i \<noteq> x j"
  shows "j \<le> n \<Longrightarrow> poly (neville_aitken x f n) (x j) = (f j)"
  unfolding neville_aitken_def
  by (rule neville_aitken_main[OF assms, of n], auto)

definition neville_aitken_interpolation_poly :: "('a :: field \<times> 'a)list \<Rightarrow> 'a poly" where
  "neville_aitken_interpolation_poly x_fs = (let
    start = map (\<lambda> (xi,fi). (xi,xi,[:fi:])) x_fs in
    neville_aitken_impl_main start)"

lemma neville_aitken_interpolation_impl: assumes "x_fs \<noteq> []"
  shows "neville_aitken_interpolation_poly x_fs =
  neville_aitken (\<lambda> i. fst (x_fs ! i)) (\<lambda> i. snd (x_fs ! i)) (length x_fs - 1)"
proof -
  from assms have id: "Suc (length x_fs - 1) = length x_fs" by auto
  show ?thesis
    unfolding neville_aitken_interpolation_poly_def Let_def
    by (rule neville_aitken_impl, unfold id, rule nth_equalityI, auto split: prod.splits)
qed

lemma neville_aitken_interpolation_poly: assumes dist: "distinct (map fst xs_ys)"
  and p: "p = neville_aitken_interpolation_poly xs_ys"
  and xy: "(x,y) \<in> set xs_ys"
  shows "poly p x = y"
proof -
  have p: "p = neville_aitken (\<lambda> i. fst (xs_ys ! i)) (\<lambda> i. snd (xs_ys ! i)) (length xs_ys - 1)"
    unfolding p
    by (rule neville_aitken_interpolation_impl, insert xy, auto)
  from xy obtain i where i: "i < length xs_ys" and x: "x = fst (xs_ys ! i)" and y: "y = snd (xs_ys ! i)"
    unfolding set_conv_nth by (metis fst_conv in_set_conv_nth snd_conv xy)
  show ?thesis unfolding p x y
  proof (rule neville_aitken)
    fix i j
    show "i < j \<Longrightarrow> j \<le> length xs_ys - 1 \<Longrightarrow> fst (xs_ys ! i) \<noteq> fst (xs_ys ! j)" using dist
      by (metis (mono_tags, lifting) One_nat_def diff_less dual_order.strict_trans2 length_map
        length_pos_if_in_set lessI less_or_eq_imp_le neq_iff nth_eq_iff_index_eq nth_map xy)
  qed (insert i, auto)
qed

lemma degree_neville_aitken_interpolation_poly:
  shows "degree (neville_aitken_interpolation_poly xs_ys) \<le> length xs_ys - 1"
proof (cases "length xs_ys")
  case 0
  hence id: "xs_ys = []" by (cases xs_ys, auto)
  show ?thesis unfolding id neville_aitken_interpolation_poly_def Let_def by simp
next
  case (Suc nn)
  have id: "neville_aitken_interpolation_poly xs_ys =
    neville_aitken (\<lambda> i. fst (xs_ys ! i)) (\<lambda> i. snd (xs_ys ! i)) (length xs_ys - 1)"
    by (rule neville_aitken_interpolation_impl, insert Suc, auto)
  show ?thesis unfolding id by (rule degree_neville_aitken)
qed

end


theory Submission
  imports Defs
begin

theorem solution:
  fixes G (structure) and H (structure) and f
  assumes
    hom: "f \<in> hom G H" and
    group_G: "group G" and
    group_H: "group H" and
    h1: "\<forall>a b. a \<otimes> b \<otimes> inv a \<otimes> inv b \<in> group.center G" and
    h2: "\<forall>x \<in> group.center G. f x = \<one>\<^bsub>H\<^esub> \<longrightarrow> x = \<one>"
  shows "inj_on f (carrier G)"
proof -
  have "\<forall> a \<in> carrier G. f a = \<one>\<^bsub>H\<^esub> \<longrightarrow> a = \<one>"
  proof safe
    fix a :: 'a
    assume [simp]: \<open>a \<in> carrier G\<close> and [simp]: \<open>f a = \<one>\<^bsub>H\<^esub>\<close>
    then have "a \<in> group.center G"
      unfolding group.center_def[OF group_G]
    proof safe
      fix g :: 'a
      assume [simp]: \<open>g \<in> carrier G\<close>
      note h[simp] = hom_mult[OF hom] hom_one[OF hom]
      note closed[simp] = monoid.m_closed[OF group.is_monoid, OF group_G] hom_in_carrier[OF hom]
      note group[simp] = group_G group_H group.is_monoid
      have "f (a \<otimes> g \<otimes> inv a \<otimes> inv g) = \<one>\<^bsub>H\<^esub>"
      proof -
        have [simp]: "f (inv a) = inv\<^bsub>H\<^esub> (f a)"
          by (metis \<open>a \<in> carrier G\<close> \<open>f a = \<one>\<^bsub>H\<^esub>\<close> group.inv_closed group.l_cancel_one' group.l_inv
                group_G group_H h hom hom_in_carrier)
        have "f (a \<otimes> g \<otimes> inv a \<otimes> inv g) = f a \<otimes>\<^bsub>H\<^esub> f g \<otimes>\<^bsub>H\<^esub> f (inv a) \<otimes>\<^bsub>H\<^esub> f (inv g)"
          by simp
        also have "\<dots> = f g \<otimes>\<^bsub>H\<^esub> f (inv g)"
          by (simp add: monoid.inv_one)
        also have "\<dots> = \<one>\<^bsub>H\<^esub>"
          by (simp flip: h add: group.r_inv)
        finally show ?thesis .
      qed
      with h1 h2 have "a \<otimes> g \<otimes> inv a \<otimes> inv g = \<one>"
        by auto
      then show \<open>a \<otimes> g = g \<otimes> a\<close>
        by (subst group.inv_solve_right'[symmetric]; simp) (subst (asm) group.inv_solve_right'; simp)
    qed
    with h2 \<open>f a = \<one>\<^bsub>H\<^esub>\<close> show \<open>a = \<one>\<close>
      by simp
  qed
  with hom have "f \<in> mon G H"
    unfolding mon_iff_hom_one[OF group_G group_H] by simp
  then show ?thesis \<comment> \<open>Missing \<open>monoid_hom.injective_iff\<close> from Lean here\<close>
    unfolding mon_def by simp
qed

end


\<^marker>\<open>creator "Kevin Kappelmann"\<close>
paragraph \<open>Irreflexive\<close>
theory Binary_Relations_Irreflexive
  imports
    Binary_Relation_Functions
    HOL_Syntax_Bundles_Lattices
begin

consts irreflexive_on :: "'a \<Rightarrow> ('b \<Rightarrow> 'b \<Rightarrow> bool) \<Rightarrow> bool"

overloading
  irreflexive_on_pred \<equiv> "irreflexive_on :: ('a \<Rightarrow> bool) \<Rightarrow> ('a \<Rightarrow> 'a \<Rightarrow> bool) \<Rightarrow> bool"
begin
  definition "irreflexive_on_pred P R \<equiv> \<forall>x. P x \<longrightarrow> \<not>(R x x)"
end

lemma irreflexive_onI [intro]:
  assumes "\<And>x. P x \<Longrightarrow> \<not>(R x x)"
  shows "irreflexive_on P R"
  using assms unfolding irreflexive_on_pred_def by blast

lemma irreflexive_onD [dest]:
  assumes "irreflexive_on P R"
  and "P x"
  shows "\<not>(R x x)"
  using assms unfolding irreflexive_on_pred_def by blast

definition "irreflexive (R :: 'a \<Rightarrow> _) \<equiv> irreflexive_on (\<top> :: 'a \<Rightarrow> bool) R"

lemma irreflexive_eq_irreflexive_on:
  "irreflexive (R :: 'a \<Rightarrow> _) = irreflexive_on (\<top> :: 'a \<Rightarrow> bool) R"
  unfolding irreflexive_def ..

lemma irreflexiveI [intro]:
  assumes "\<And>x. \<not>(R x x)"
  shows "irreflexive R"
  unfolding irreflexive_eq_irreflexive_on using assms by (intro irreflexive_onI)

lemma irreflexiveD:
  assumes "irreflexive R"
  shows "\<not>(R x x)"
  using assms unfolding irreflexive_eq_irreflexive_on by auto

lemma irreflexive_on_if_irreflexive:
  fixes P :: "'a \<Rightarrow> bool" and R :: "'a \<Rightarrow> _"
  assumes "irreflexive R"
  shows "irreflexive_on P R"
  using assms by (intro irreflexive_onI) (blast dest: irreflexiveD)

end


theory Chap2
imports Main

begin

datatype nat = Zero | Suc nat

fun add :: "nat \<Rightarrow> nat \<Rightarrow> nat" where
"add Zero n = n" |
"add (Suc m) n = Suc(add m n)"

lemma add_02: "add m Zero = m"
apply(induction m)
apply(auto)
done

end


theory "Traceable-Objects"
imports Main
begin

section \<open>A few properties of foldl\<close>

lemma l1:"foldl (o) a (rev (x#xs)) = (foldl (o) a (rev xs)) o x"
  by simp

lemma l2:"foldl (o) a (x#xs) = a o (foldl (o) x xs)"
proof (induct "rev xs" arbitrary:a x xs)
  case Nil
  then show ?case
    by auto
next
  case (Cons a xa)
  then show ?case
    by (metis (no_types, lifting) append_Cons comp_assoc l1 rev.simps(2) rev_swap)
qed

lemma l3:"foldl (o) x xs = x o (foldl (o) id xs)"
  by (metis comp_id foldl_Cons l2)

text \<open>TODO: this could be generalized to multiplicative commutative monoids
(functions with the composition operation are a multiplicative commutative monoid).\<close>

section \<open>Data types and traceability\<close>

locale data_type =
  fixes f :: "'b \<Rightarrow> 'a \<Rightarrow> 'a" \<comment> \<open>the transition function of the data type\<close>
  and init :: "'a"
begin

definition exec \<comment> \<open>a state transformer corresponding to applying all operations in order\<close>
  where "exec ops \<equiv> foldl (o) id (map f ops)" \<comment> \<open>@{term "(o)"} is function composition \<close>

lemma exec_Cons:"exec (x#xs) = (f x) o (exec xs)"
  using exec_def l3 by force

lemma exec_Nil:"exec [] = id"
  by (simp add: exec_def)

definition is_traceable \<comment> \<open>A state has a unique history from the initial state\<close>
  where "is_traceable \<equiv> \<forall> ops\<^sub>1 ops\<^sub>2 . exec ops\<^sub>1 init = exec ops\<^sub>2 init \<longrightarrow> ops\<^sub>1 = ops\<^sub>2"

end

locale traceable_data_type = data_type f init for f init +
  assumes traceable:"is_traceable"
begin

text \<open>Prove some facts about traceable datatypes...\<close>

end

section \<open>Append-only lists are traceable\<close>

interpretation list_data_type: data_type "(#)" "[]" .

lemma l4:"list_data_type.exec xs [] =  xs"
proof (induct xs)
  case Nil
  then show ?case
    by (simp add: list_data_type.exec_Nil)
next
  case (Cons a xs)
  then show ?case
    by (simp add: data_type.exec_Cons)
qed

interpretation list_traceable:traceable_data_type "(#)" "[]"
  using l4 list_data_type.is_traceable_def traceable_data_type_def by fastforce

text \<open>Now the facts proved about traceable datatypes are available for append-only lists.\<close>

end


(* This Isabelle theory is produced using the TIP tool offered at the following website:
     https://github.com/tip-org/tools
   This file was originally provided as part of TIP benchmark at the following website:
     https://github.com/tip-org/benchmarks
   Yutaka Nagashima at CIIRC, CTU changed the TIP output theory file slightly
   to make it compatible with Isabelle2017.*)
  theory TIP_list_nat_perm_trans
imports "../../Test_Base"
begin

datatype 'a list = nil2 | cons2 "'a" "'a list"

fun elem :: "'a => 'a list => bool" where
"elem x (nil2) = False"
| "elem x (cons2 z xs) = ((z = x) | (elem x xs))"

fun deleteBy :: "('a => ('a => bool)) => 'a => 'a list =>
                 'a list" where
"deleteBy x y (nil2) = nil2"
| "deleteBy x y (cons2 y2 ys) =
     (if (x y) y2 then ys else cons2 y2 (deleteBy x y ys))"

fun isPermutation :: "'a list => 'a list => bool" where
"isPermutation (nil2) (nil2) = True"
| "isPermutation (nil2) (cons2 z x2) = False"
| "isPermutation (cons2 x3 xs) y =
     ((elem x3 y) &
        (isPermutation
           xs (deleteBy (% (x4 :: 'a) => % (x5 :: 'a) => (x4 = x5)) x3 y)))"

theorem property0 :
  "((isPermutation xs ys) ==>
      ((isPermutation ys zs) ==> (isPermutation xs zs)))"
  oops

end