theory Rudin
  imports Complex_Main (* comment by Angeliki: switched to Complex_Main and imported some Analysis*)
"HOL-Analysis.Abstract_Euclidean_Space"
"HOL-Analysis.Derivative"
"HOL-Analysis.Interval_Integral"
"HOL-Analysis.Elementary_Topology"
(*"HOL-Hahn_Banach.Function_Order"*)
begin

(*
problem_number:1_1a
natural language statement:
If $r$ is rational $(r \neq 0)$ and $x$ is irrational, prove that $r+x$ is irrational.
lean statement:
theorem exercise_1_1a
  (x : \<real>) (y : \<rat>) :
  ( irrational x ) -> irrational ( x + y ) :=
begin
  apply irrational.add_rat,
end

codex statement:
theorem irrational_of_add_irrational_rational:
  fixes r :: real and x::real
  assumes "r \<noteq> 0" "irrational x"
  shows "irrational (r + x)"
(*Our comment on the codex statement: <wrong: missed one assumption,so what it wants to
prove is false. Also used the def.
 "irrational" which doesn't exist >*)
*)
theorem exercise_1_1a:
   fixes r :: rat and x::real
  assumes "r \<noteq> 0" " x \<notin> Rats"
  shows " (r + x) \<notin> Rats "
  oops

(*
problem_number:1_1b
natural language statement:
If $r$ is rational $(r \neq 0)$ and $x$ is irrational, prove that $rx$ is irrational.
lean statement:
theorem exercise_1_1b
(x : \<real>)
(y : \<rat>)
(h : y \<noteq> 0)
: ( irrational x ) -> irrational ( x * y ) :=
begin
  intro g,
  apply irrational.mul_rat g h,
end

codex statement:
theorem irrational_of_rational_times_irrational:
  fixes r::real and x::real
  assumes "r \<noteq> 0" "irrational x" "rational r"
  shows "irrational (r*x)"
Our comment on the codex statement: < the mistake here is that it used the def "irrational" which
doesn't exist in Isabelle>
 *)
theorem exercise_1_1b:
   fixes r :: rat and x::real
  assumes "r \<noteq> 0" " x \<notin> Rats"
  shows " r*x \<notin> Rats "

  oops

(*
problem_number:1_2
natural language statement:
Prove that there is no rational number whose square is $12$.
lean statement:
theorem exercise_1_2
: ¬ \<exists> (x : \<rat>), ( x ^ 2 = 12 ) :=

codex statement:
theorem no_rational_square_eq_12:
  assumes "\<exists>x. x^2 = 12"
  shows "False"
Our comment on the codex statement: <it didn't include the rationality assumption;
the formalisation is wrong, plus the claim it presents is not true.>
 *)
theorem exercise_1_2: assumes "\<exists> x \<in> Rats. x^2 = 12"
  shows False oops

(*
problem_number:1_4
natural language statement:
Let $E$ be a nonempty subset of an ordered set; suppose $\alpha$ is a lower bound of $E$ and
$\beta$ is an upper bound of $E$. Prove that $\alpha \leq \beta$.
lean statement:
theorem exercise_1_4
(\<alpha> : Type* ) [partial_order \<alpha>]
(s : set \<alpha>)
(x y : \<alpha>)
(h₀ : set.nonempty s)
(h_1 : x \<in> lower_bounds s)
(h_2 : y \<in> upper_bounds s)
: x \<le> y :=
begin
  have h : \<exists> z, z \<in> s := h₀,
  cases h with z,
  have xlez : x \<le> z :=
  begin
  apply h_1,
  assumption,
  end,
  have zley : z \<le> y :=
  begin
  apply h_2,
  assumption,
  end,
  exact xlez.trans zley,
end

codex statement:
theorem lower_bound_leq_upper_bound:
  fixes E::"'a::linorder set"
  assumes "E \<noteq> {}" "\<forall>x\<in>E. \<alpha> \<le> x" "\<forall>x\<in>E. x \<le> β"
  shows "\<alpha> \<le> β"

Our comment on the codex statement: <correct formalisation! I copy-paste it below.>
 *)

theorem exercise_1_4: fixes E::"'a::linorder set"
  assumes "E \<noteq> {}" "\<forall>x\<in>E. \<alpha> \<le> x" "\<forall>x\<in>E. x \<le> \<beta>"
  shows "\<alpha> \<le> \<beta>"
  oops

(*

problem_number:1_5
natural language statement:
Let $A$ be a nonempty set of real numbers which is bounded below. Let $-A$ be the set of all
numbers $-x$, where $x \in A$. Prove that $\inf A=-\sup (-A)$.
lean statement:
theorem exercise_1_5
  (A minus_A : set \<real>) (hA : A.nonempty) (hA_bdd_below : bdd_below A)
  (hminus_A : minus_A = {x | -x \<in> A}) :
  Inf A = Sup minus_A :=

codex statement:
theorem inf_of_neg_sup_of_neg:
  fixes A::"real set"
  assumes "bdd_below A" "A \<noteq> {}"
  shows "Inf A = - Sup (-A)"
Our comment on the codex statement: <  chosen notation is wrong: -A denotes
the complement of A  >
*)

theorem exercise_1_5:  fixes A::"real set" and minusA::"real set"
  assumes "bdd_below A" "A \<noteq> {}" and " minusA = {x. -x \<in> A}"
  shows "Inf A = - Sup (minusA)"

  oops

(*
problem_number:1_8
natural language statement:
Prove that no order can be defined in the complex field that turns it into an ordered field.
Hint: $-1$ is a square.
lean statement:
theorem exercise_1_8
  : ¬ \<exists> (r : \<complex> \<rightarrow> \<complex> \<rightarrow> Prop), is_linear_order \<complex> r :=

codex statement:
theorem no_order_in_complex_field:
  fixes z::complex
  assumes "\<forall>x y. x \<le> y \<longrightarrow> x + z \<le> y + z"
"\<forall>x y. x \<le> y \<longrightarrow> x * z \<le> y * z" "\<forall>x. x \<le> x"
"\<forall>x y. x \<le> y \<longrightarrow> y \<le> x \<longrightarrow> x = y"
"\<forall>x y z. x \<le> y \<longrightarrow> x + z \<le> y + z" "\<forall>x y. x \<le> y \<longrightarrow> x * y \<le> y * x"
"\<forall>x y z. x \<le> y \<longrightarrow> x * (y + z) \<le> x * y + x * z" "\<exists>x. x < x"
  shows False
Our comment on the codex statement: < overall wrong>

*)

theorem exercise_1_8:
  fixes C:: "complex set"
  shows "\<not> (\<exists> r. linear_order_on C r)"

  oops

(*
problem_number:1_17
natural language statement:
Prove that $|\mathbf{x}+\mathbf{y}|^{2}+|\mathbf{x}-\mathbf{y}|^{2}=2|\mathbf{x}|^{2}+2|\mathbf{y}|^{2}$
if $\mathbf{x} \in R^{k}$ and $\mathbf{y} \in R^{k}$.
lean statement:
exercise_1_17
(n : ℕ)
(x y : euclidean_space ℝ (fin n)) -- R^n
: ∥x + y∥^2 + ∥x - y∥^2 = 2*∥x∥^2 + 2*∥y∥^2 :
codex statement:
theorem sum_add_square_sub_square_eq_sum_square:
  fixes x y::"'a::euclidean_space"
  shows "norm (x+y)^2 + norm (x - y) ^ 2 = 2 * (norm x)^2 + 2* (norm y)^2"

Our comment on the codex statement: < correct,I copy-paste it below >
 *)

theorem exercise_1_17:
  fixes x y::"'a::euclidean_space"
  shows "norm (x+y)^2 + norm (x - y) ^ 2 = 2 * (norm x)^2 + 2* (norm y)^2"

  oops
(*
problem_number:1_14
natural language statement:
If $z$ is a complex number such that $|z|=1$, that is, such that $z \bar{z}=1$, compute $|1+z|^{2}+|1-z|^{2}$.
lean statement:
theorem exercise_1_14
  (z : \<complex>) (h : abs z = 1)
  : (abs (1 + z)) ^ 2 + (abs (1 - z)) ^ 2 = 4 :=

codex statement:
theorem sum_square_of_sum_sub_of_abs_eq_one:
  fixes z::complex
  assumes "norm z = 1"
  shows "norm (1 + z)^2 + norm (1 - z)^2 = 4"
Our comment on the codex statement: <Unsure how to compare: the natural language version says
"compute" without giving the answer, both the formalised and codex-autoformalised versions
give the answer and ask for proving what it is. The extra hint "that is, such that $z \bar{z}=1$" did not need to
be formalised and wasn't autoformalised either. The autoformalisation is correct, I copy-paste it below. >
 *)
theorem exercise_1_14:
 fixes z::complex
  assumes "norm z = 1"
  shows "norm (1 + z)^2 + norm (1 - z)^2 = 4"
  oops

(*
problem_number:1_18a
natural language statement:
If $k \geq 2$ and $\mathbf{x} \in R^{k}$, prove that
there exists $\mathbf{y} \in R^{k}$ such that $\mathbf{y} \neq 0$ but $\mathbf{x} \cdot \mathbf{y}=0$
lean statement:
theorem exercise_1_18a
  (n : \<nat>)
  (h : n > 1)
  (x : euclidean_space \<real> (fin n)) -- R^n
  : \<exists> (y : euclidean_space \<real> (fin n)), y \<noteq> 0 \<and> (inner x y) = (0 : \<real>) :=

codex statement:
theorem exists_nonzero_orthogonal_vector:
  fixes x::"'a::euclidean_space"
  assumes "k\<ge>2"
  shows "\<exists>y. y \<noteq> 0 \<and> x ⋅ y = 0"
Our comment on the codex statement: <  missed the assumption that k is the dimension
and had wrong inner product symbol>
 *)
theorem exercise_1_18a:
  fixes x::"'a::euclidean_space"
  assumes " DIM('a::euclidean_space) \<ge> 2"
  shows "\<exists>y. y \<noteq> 0 \<and> inner  x  y = 0"

  oops

(*
problem_number:1_25
natural language statement:
25: Prove that every compact metric space $K$ has a countable base.
lean statement:
MISSING
codex statement:

theorem compact_metric_space_has_countable_base:
  fixes K::"'a::metric_space set"
  assumes "compact K"
  shows "countable (UNIV::'a set)"

Our comment on the codex statement: <wrong conclusion>

*)
theorem exercise_1_25:

  fixes K::"'a::metric_space set"
  assumes "compact K"
  shows
 "\<exists> B. (countable B) \<and> (topological_basis B)
 \<and> (\<forall> b\<in> B. b \<subseteq> K)"
  oops

(* TODO CHECK THE ABOVE *)

(*
problem_number:1_27a
natural language statement:
27a: Suppose $E\subset\mathbb{R}^k$ is uncountable, and let $P$ be the set
of condensation points of $E$. Prove that $P$ is perfect.
lean statement:

codex statement:
theorem perfect_of_uncountable_condensation_points:
  fixes E::"'a::euclidean_space set"
  assumes "uncountable E" "P = condensation_points E"
  shows "perfect P"
Our comment on the codex statement: <makes up definitions that don't exist in Isabelle,
(perfect which doesn't work for perfect set, condensation_points). >
*)

theorem exercise_1_27a:
undefined

(*shows " P= {x.  x islimpt P}"*)
  oops (* TODO  note the def:  If every neighbourhood of x contains uncountably many points of
S, then x is a type of limit point called a condensation point of S. *)

(*
problem_number:1_27b
natural language statement:
27b: Suppose $E\subset\mathbb{R}^k$ is uncountable, and let $P$ be the set of condensation points of $E$.
Prove that at most countably many point of $E$ are not in $P$.
lean statement:
MISSING
codex statement:
theorem countable_of_uncountable_set_of_condensation_points:
  fixes E::"'a::euclidean_space set"
  assumes "uncountable E"
  shows "countable {x\<in>E. x\<notin>condensation_points E}"
Our comment on the codex statement: <  uses nonexistent
Isabelle definitions (condensation_points) otherwise correct
>
 *)
theorem exercise_1_27b:
  undefined oops

(*
problem_number:1_28
natural language statement:
Prove that every closed set in a separable metric space is the union of a
(possibly empty) perfect set and a set which is at most countable.
lean statement:
MISSING
codex statement:
theorem closed_set_union_perfect_set_countable_set:
  fixes X::"'a::metric_space set"
  assumes "separable X" "closed X"
  shows "\<exists>P C. perfect P \<and> countable C \<and> X = P ∪ C"
Our comment on the codex statement: <uses nonexistent Isabelle definitions (perfect which
doesn't work for perfect set, separable)> *)

theorem exercise_1_28:

   fixes X::"'a::metric_space set"
   assumes "\<exists> T ⊆ X . countable T \<and> X ⊆ closure T"  "closed S" and "S \<subseteq> X"
   shows "\<exists> P C. countable C \<and> P = {x \<in> P. x islimpt P} \<and> S = P ∪ C  "

  oops

(*
problem_number:1_29
natural language statement:
Prove that every open set in $\mathbb{R}$ is the union of an at most countable collection of disjoint segments.
lean statement:
MISSING
codex statement:
theorem open_set_union_of_countable_disjoint_segments:
  fixes A::"real set"
  assumes "open A"

  shows "\<exists>f. countable (f ` (UNIV::nat set)) \<and> pairwise disjoint (f ` (UNIV::nat set))
\<and> (\<Union>i\<in>UNIV. f i) = A"
Our comment on the codex statement: <wrong >

 *)
theorem exercise_1_29:
  undefined oops

(*
problem_number:2_19a
natural language statement:
If $A$ and $B$ are disjoint closed sets in some metric space $X$, prove that they are separated.
lean statement:
theorem exercise_2_19a {X : Type*} [metric_space X]
  (A B : set X) (hA : is_closed A) (hB : is_closed B) (hAB : disjoint A B) :
  separated_nhds A B :=

codex statement:
theorem separated_of_disjoint_closed:
  fixes A B::"'a::metric_space set"
  assumes "closed A" "closed B" "A ∩ B = {}"
  shows "separated A B"
Our comment on the codex statement: < Almost correct: used nonexistent Isabelle definition
(separated)> *)
theorem exercise_2_19a:

   fixes  A B::"'a::metric_space set"
   assumes "closed A" "closed B" "A ∩ B = {}"  "A ⊆ topspace X"
   "B ⊆ topspace X"
  shows "separatedin X A B"

  oops

(*
problem_number:2_24
natural language statement:
Let $X$ be a metric space in which every infinite subset has a limit point.
 Prove that $X$ is separable. Hint: Fix $\delta>0$, and pick $x_{1} \in X$.
Having chosen $x_{1}, \ldots, x_{J} \in X$,
lean statement:
theorem exercise_2_24 {X : Type*} [metric_space X]
  (hX : \<forall> (A : set X), infinite A \<rightarrow> \<exists> (x : X), x \<in> closure A) :
  separable_space X :=

codex statement:
theorem separable_of_infinite_subset_has_limit_point:
  fixes X::"'a::metric_space set"
  assumes
"\<forall>A. infinite A \<longrightarrow>
\<exists>x\<in>A. \<forall>\<epsilon>>0. \<exists>y\<in>A. y\<noteq>x \<and> dist x y < \<epsilon>"
  shows "separable X"
Our comment on the codex statement: <uses nonexistent Isabelle definition (separable),
syntax error due to not including expression in parenthesis, missed  that
A \<subseteq> X in assumption, missed the Isabelle limit point definition>
 *)
theorem exercise_2_24:

   fixes X::"'a::metric_space set"
   assumes "\<forall>A \<subseteq> X. infinite A \<longrightarrow>
( \<exists>x\<in>A. x islimpt A )"
   obtains T where "countable T" "T ⊆ X" "X ⊆ closure T"

  oops

(*
problem_number:3_1a
natural language statement:
Prove that convergence of $\left\{s_{n}\right\}$ implies convergence of $\left\{\left|s_{n}\right|\right\}$.
lean statement:
theorem exercise_3_1a
  (f : \<nat> \<rightarrow> \<real>)
  (h : \<exists> (a : \<real>), tendsto (\<lambda> (n : \<nat>), f n) at_top (𝓝 a))
  : \<exists> (a : \<real>), tendsto (\<lambda> (n : \<nat>), |f n|) at_top (𝓝 a) :=
begin
  cases h with a h,
  use |a|,
  apply filter.tendsto.abs h,
end

codex statement:
theorem convergent_of_convergent_abs:
  fixes s::"nat \<Rightarrow> 'a::real_normed_vector"
  assumes "convergent s"
  shows "convergent (\<lambda>n. norm (s n))"
Our comment on the codex statement: < correct, copy-pasted below>
 *)
theorem exercise_3_1a:
  fixes s::"nat \<Rightarrow> 'a::real_normed_vector"
  assumes "convergent s"
  shows "convergent (\<lambda>n. norm (s n))"
oops

(*
problem_number:3_3
natural language statement:
If $s_{1}=\sqrt{2}$, and $s_{n+1}=\sqrt{2+\sqrt{s_{n}}} \quad(n=1,2,3, \ldots),$
prove that $\left\{s_{n}\right\}$ converges, and that $s_{n}<2$ for $n=1,2,3, \ldots$.
lean statement:
theorem exercise_3_3
  : \<exists> (x : \<real>), tendsto f at_top (𝓝 x) \<and> \<forall> n, f n < 2 :=

codex statement:
theorem sqrt_2_lt_2_of_sqrt_2_plus_sqrt_s_n:
  fixes s::"nat \<Rightarrow> real"
  assumes "s 1 = sqrt 2" "\<forall>n. s (n+1) = sqrt (2 + sqrt (s n))"
  shows "\<forall>n. s n < 2"
Our comment on the codex statement: < missed one of the conclusions to be shown, otherwise ok>
 *)
theorem exercise_3_3:

   fixes s::"nat \<Rightarrow> real"
  assumes "s 1 = sqrt 2" "\<forall>n. s (n+1) = sqrt (2 + sqrt (s n))"
  shows "convergent s " and  "\<forall>n. s n < 2"
  oops

(*
problem_number:3_5
natural language statement:
For any two real sequences $\left\{a_{n}\right\},\left\{b_{n}\right\}$,
prove that $\limsup _{n \rightarrow \infty}\left(a_{n}+b_{n}\right) \leq
\limsup _{n \rightarrow \infty} a_{n}+\limsup _{n \rightarrow \infty} b_{n},$
provided the sum on the right is not of the form $\infty-\infty$.
lean statement:
theorem exercise_3_5 -- TODO fix
  (a b : \<nat> \<rightarrow> \<real>)
  (h : limsup a + limsup b \<noteq> 0) :
  limsup (\<lambda> n, a n + b n) \<le> limsup a + limsup b :=

codex statement:
theorem limsup_sum_leq_sum_limsup:
  fixes a b::"nat \<Rightarrow> real"
  assumes "\<forall>n. a n \<le> b n"
  shows "limsup (\<lambda>n. a n + b n) \<le> limsup a + limsup b"
Our comment on the codex statement: < not sure about the natural language statement here
(* TODO check *)
codex is wrong as it's adding nonexistent \<le> assumption >
 *)
theorem exercise_3_5:
  fixes a b::"nat \<Rightarrow> real"
  assumes  "convergent a" and "convergent b "
  shows "limsup (\<lambda>n. ¦ a n + b n¦) \<le> limsup a + limsup b"  oops

(*
problem_number:3_7
natural language statement:
Prove that the convergence of $\Sigma a_{n}$ implies the convergence of $\sum \frac{\sqrt{a_{n}}}{n}$ if $a_n\geq 0$.
lean statement:
theorem exercise_3_7
  (a : \<nat> \<rightarrow> \<real>)
  (h : \<exists> y, (tendsto (\<lambda> n, (\<Sum> i in (finset.range n), a i)) at_top (𝓝 y))) :
  \<exists> y, tendsto (\<lambda> n, (\<Sum> i in (finset.range n), sqrt (a i) / n)) at_top (𝓝 y) :=

codex statement:
theorem sum_sqrt_div_n_converges_of_sum_converges:
  fixes a::"nat \<Rightarrow> real"
  assumes "summable a" "\<forall>n. a n \<ge> 0"
  shows "summable (\<lambda>n. sqrt (a n) / n)"
Our comment on the codex statement: <correct, I copy-paste it below. Note that the natural
language statement features both \Sigma and \sum.>
 *)
theorem exercise_3_7:

  fixes a::"nat \<Rightarrow> real"
  assumes "summable a" "\<forall>n. a n \<ge> 0"
  shows "summable (\<lambda>n. sqrt (a n) / n)"
  oops

(*
problem_number:3_8
natural language statement:
If $\Sigma a_{n}$ converges, and if $\left\{b_{n}\right\}$
is monotonic and bounded, prove that $\Sigma a_{n} b_{n}$ converges.
lean statement:
theorem exercise_3_8
  (a b : \<nat> \<rightarrow> \<real>)
  (h1 : \<exists> y, (tendsto (\<lambda> n, (\<Sum> i in (finset.range n), a i)) at_top (𝓝 y)))
  (h2 : monotone b)
  (h3 : metric.bounded (set.range b)) :
  \<exists> y, tendsto (\<lambda> n, (\<Sum> i in (finset.range n), (a i) * (b i))) at_top (𝓝 y) :=

codex statement:
theorem convergent_of_convergent_and_monotonic_bounded:
  fixes a::"nat \<Rightarrow> real" and b::"nat \<Rightarrow> real"
  assumes "convergent a" "bounded (range b)" "mono b"
  shows "convergent (\<lambda>n. a n * b n)"
Our comment on the codex statement: < the mistake is that here it is meant summable by \Sigma,
so it should not be translated as convergent>
 *)
theorem exercise_3_8:
   fixes a::"nat \<Rightarrow> real" and b::"nat \<Rightarrow> real"
  assumes "summable a " "bounded (range b)" "mono b"
  shows "summable (\<lambda>n. a n * b n)"
  oops

(*
problem_number:3_13
natural language statement:
Prove that the Cauchy product of two absolutely convergent series converges absolutely.
lean statement:
theorem exercise_3_13
  (a b : \<nat> \<rightarrow> \<real>)
  (ha : \<exists> y, (tendsto (\<lambda> n, (\<Sum> i in (finset.range n), |a i|)) at_top (𝓝 y)))
  (hb : \<exists> y, (tendsto (\<lambda> n, (\<Sum> i in (finset.range n), |b i|)) at_top (𝓝 y))) :
  \<exists> y, (tendsto (\<lambda> n, (\<Sum> i in (finset.range n),
  \<lambda> i, (\<Sum> j in finset.range (i + 1), a j * b (i - j)))) at_top (𝓝 y)) :=

codex statement:
theorem abs_convergent_of_cauchy_product:
  fixes f g::"nat \<Rightarrow> 'a::real_normed_algebra_1"
  assumes "summable (\<lambda>n. abs (f n))" "summable (\<lambda>n. abs (g n))"
  shows "summable (\<lambda>n. abs (\<Sum>i<n. f i * g (n - i)))"
Our comment on the codex statement: < mistake in type: should be real instead of real_normed_algebra_1.
Otherwise impressive> *)

theorem exercise_3_13:
   fixes f g::"nat \<Rightarrow> real"
  assumes "summable (\<lambda>n. abs (f n))" "summable (\<lambda>n. abs (g n))"
  shows "summable (\<lambda>n. abs (\<Sum>i<n. f i * g (n - i)))"

  oops

(*
problem_number:3_20
natural language statement:
Suppose $\left\{p_{n}\right\}$ is a Cauchy sequence in a metric space $X$,
and some sequence $\left\{p_{n l}\right\}$ converges to a point $p \in X$.
 Prove that the full sequence $\left\{p_{n}\right\}$ converges to $p$.
lean statement:
theorem exercise_3_20 {X : Type*} [metric_space X]
  (p : \<nat> \<rightarrow> X) (l : \<nat>) (r : X)
  (hp : cauchy_seq p)
  (hpl : tendsto (\<lambda> n, p (l * n)) at_top (𝓝 r)) :
  tendsto p at_top (𝓝 r) :=

codex statement:
theorem convergent_of_subseq_convergent:
  fixes X::"'a::metric_space" and p::"'a" and pn::"nat \<Rightarrow> 'a"
  assumes "Cauchy pn" "convergent (\<lambda>n. pn (n l))" "\<forall>n. pn (n l) \<longrightarrow> p"
  shows "pn \<longrightarrow> p"
Our comment on the codex statement: < close but wrong>
 *)

theorem exercise_3_20:

  fixes X::"'a::metric_space" and p::"'a" and pn::"nat \<Rightarrow> 'a"
  assumes "Cauchy pn" and " ((λl. pn(n l)) ⤏ p) sequentially"
shows " ((λn. pn(n )) ⤏ p) sequentially"

  oops

(*
problem_number:3_21
natural language statement:
If $\left\{E_{n}\right\}$ is a sequence of closed nonempty and bounded sets in a complete metric
space $X$, if $E_{n} \supset E_{n+1}$,
and if $\lim _{n \rightarrow \infty} \operatorname{diam} E_{n}=0,$
then $\bigcap_{1}^{\infty} E_{n}$ consists of exactly one point.
lean statement:
theorem exercise_3_21
  {X : Type*} [metric_space X] [complete_space X]
  (E : \<nat> \<rightarrow> set X)
  (hE : \<forall> n, E n ⊃ E (n + 1))
  (hE' : tendsto (\<lambda> n, metric.diam (E n)) at_top (𝓝 0)) :
  \<exists> a, set.Inter E = {a} :=

codex statement:
theorem singleton_of_closed_nonempty_bounded_diam_zero:
  fixes X::"'a::metric_space set"
  assumes "\<forall>n. closed (E n)" "\<forall>n. E n \<noteq> {}" "\<forall>n. bounded (E n)"
"\<forall>n. E n \<subseteq> E (n+1)" "diameter (E n) \<longrightarrow> 0"
  shows "\<exists>x. (∩n. E n) = {x}"
Our comment on the codex statement: <several mistakes: symbols, misses assumptions, uses
subset instead of superset>
 *)
theorem exercise_3_21:

fixes X::"'a::metric_space set" and E:: " nat \<Rightarrow> 'a set"

assumes "\<forall>n. closed (E n)"  "complete X" "\<forall>n. E n \<noteq> {}"
"\<forall>n. bounded (E n)"
"\<forall>n. E n \<supset> E (n+1)" "((λn. diameter (E n)) ⤏ 0) sequentially"
shows
 " \<exists> x. ((\<Inter>n\<in> \<nat>. E n) ={x})"

  oops

(*
problem_number:3_22
natural language statement:
Suppose $X$ is a nonempty complete metric space,
and $\left\{G_{n}\right\}$ is a sequence of dense open sets of $X$.
Prove Baire's theorem, namely, that $\bigcap_{1}^{\infty} G_{n}$ is not empty.
lean statement:
theorem exercise_3_22 (X : Type* ) [metric_space X] [complete_space X]
  (G : \<nat> \<rightarrow> set X) (hG : \<forall> n, is_open (G n) \<and> dense (G n)) :
  \<exists> x, \<forall> n, x \<in> G n :=

codex statement:
theorem baire_theorem:
  fixes X::"'a::metric_space set" and G::"'a set set"
  assumes "complete_space X" "\<forall>n. openin (subtopology X UNIV) (G n)" "
\<forall>n. dense_in (subtopology X UNIV) (G n)"
  shows "\<exists>x. \<forall>n. x\<in>G n"
Our comment on the codex statement: <YOU CAN LEAVE YOUR COMMENT HERE >
 *)

theorem exercise_3_22:

   undefined

  oops

(*
problem_number:4_2a
natural language statement:
If $f$ is a continuous mapping of a metric space $X$ into a metric space $Y$, prove that
$f(\overline{E}) \subset \overline{f(E)}$ for every set $E \subset X$. ($\overline{E}$ denotes the closure of $E$).
lean statement:
theorem exercise_4_2a
  {\<alpha> : Type} [metric_space \<alpha>]
  {β : Type} [metric_space β]
  (f : \<alpha> \<rightarrow> β)
  (h_1 : continuous f)
  : \<forall> (x : set \<alpha>), f '' (closure x) \<subseteq> closure (f '' x) :=
begin
  intros X x h_2 Y h₃,
  simp at *,
  cases h₃ with h₃ h₄,
  cases h_2 with w h₅,
  cases h₅ with h₅ h₆,
  have h₈ : is_closed (f ⁻¹' Y) := is_closed.preimage h_1 h₃,
  have h₉ : closure X \<subseteq> f ⁻¹' Y := closure_minimal h₄ h₈,
  rw ←h₆,
  exact h₉ h₅,
end

codex statement:
theorem closure_of_continuous_image_subset_continuous_image_closure:
  fixes f::"'a::metric_space \<Rightarrow> 'b::metric_space" and E::"'a set"
  assumes "continuous_on UNIV f"
  shows "closure (f ` E) \<subseteq> f ` closure E"
Our comment on the codex statement: <shows the opposite (wrong) inclusion >
 *)
theorem exercise_4_2a:

  fixes f::"'a::metric_space \<Rightarrow> 'b::metric_space" and E::"'a set"
  assumes "continuous_on UNIV f"
  shows " f ` ( closure E) \<subseteq>  closure (f ` E)"
  oops

(*
problem_number:4_3
natural language statement:
Let $f$ be a continuous real function on a metric space $X$. Let $Z(f)$ (the zero set of $f$ )
be the set of all $p \in X$ at which $f(p)=0$. Prove that $Z(f)$ is closed.
lean statement:
theorem exercise_4_3
  {\<alpha> : Type} [metric_space \<alpha>]
  (f : \<alpha> \<rightarrow> \<real>) (h : continuous f) (z : set \<alpha>) (g : z = inv f' {0})
  : is_closed z :=
begin
  rw g,
  apply is_closed.preimage h,
  exact is_closed_singleton,
end

codex statement:
theorem zero_set_of_continuous_is_closed:
  fixes f::"'a::metric_space \<Rightarrow> real"
  assumes "continuous_on UNIV f"
  shows "closed {x\<in>UNIV. f x = 0}"
Our comment on the codex statement: <correct, I copy-paste it below>
 *)
theorem exercise_4_3:

  fixes f::"'a::metric_space \<Rightarrow> real"
  assumes "continuous_on UNIV f"
  shows "closed {x\<in>UNIV. f x = 0}"

  oops

(*
problem_number:4_4a
natural language statement:
Let $f$ and $g$ be continuous mappings of a metric space $X$ into a metric space $Y$,
and let $E$ be a dense subset of $X$. Prove that $f(E)$ is dense in $f(X)$.
lean statement:
theorem exercise_4_4a
  {\<alpha> : Type} [metric_space \<alpha>]
  {β : Type} [metric_space β]
  (f : \<alpha> \<rightarrow> β)
  (s : set \<alpha>)
  (h_1 : continuous f)
  (h_2 : dense s)
  : f '' set.univ \<subseteq> closure (f '' s) :=
begin
  simp,
  exact continuous.range_subset_closure_image_dense h_1 h_2,
end

codex statement:
theorem dense_of_continuous_dense:
  fixes f::"'a::metric_space \<Rightarrow> 'b::metric_space" and
g::"'a::metric_space \<Rightarrow> 'b::metric_space"
  assumes "continuous_on UNIV f" "continuous_on UNIV g" "dense (f ` UNIV)" "dense (g ` UNIV)"
  shows "dense ((f ∘ g) ` UNIV)"
Our comment on the codex statement: <wrong: missing assumptions, wrong statement to show,
uses nonexistent definition>
 *)
theorem exercise_4_4a:

  fixes f::"'a::metric_space \<Rightarrow> 'b::metric_space"
and g::"'a::metric_space \<Rightarrow> 'b::metric_space" and E::"'a set"
assumes " closure E = UNIV"
"continuous_on UNIV f" "continuous_on UNIV g"
shows "closure( f ` E) = ( f ` UNIV)  "

  oops

(* TODO In the natural language statement above, why is g introduced? something to check?*)

(*
problem_number:4_5a
natural language statement:
If $f$ is a real continuous function defined on a closed set $E \subset R^{1}$,
prove that there exist continuous real functions $g$ on $R^{1}$ such that $g(x)=f(x)$ for all $x \in E$.
lean statement:
theorem exercise_4_5a
  (f : \<real> \<rightarrow> \<real>)
  (E : set \<real>)
  (h_1 : is_closed E)
  (h_2 : continuous_on f E)
  : \<exists> (g : \<real> \<rightarrow> \<real>), continuous g \<and> \<forall> x \<in> E, f x = g x :=

codex statement:
theorem exists_continuous_extension:
  fixes f::"real \<Rightarrow> real" and E::"real set"
  assumes "continuous_on E f" "closed E"
  shows "\<exists>g. continuous_on UNIV g \<and> (\<forall>x\<in>E. g x = f x)"
Our comment on the codex statement: <correct, I copy-paste it below>
 *)
theorem exercise_4_5a:
  fixes f::"real \<Rightarrow> real" and E::"real set"
  assumes "continuous_on E f" "closed E"
  shows "\<exists>g. continuous_on UNIV g \<and> (\<forall>x\<in>E. g x = f x)"
  oops

(*
problem_number:4_6
natural language statement:
If $f$ is defined on $E$, the graph of $f$ is the set of points $(x, f(x))$,
for $x \in E$. In particular, if $E$ is a set of real numbers, and $f$ is real-valued,
the graph of $f$ is a subset of the plane. Suppose $E$ is compact, and prove that $f$ is
continuous on $E$ if and only if its graph is compact.
lean statement:
theorem exercise_4_6
  (f : \<real> \<rightarrow> \<real>)
  (E : set \<real>)
  (G : set (\<real> \<times> \<real>))
  (h_1 : is_compact E)
  (h_2 : G = {(x, f x) | x \<in> E})
  : continuous_on f E \<longleftrightarrow> is_compact G :=

codex statement:
theorem compact_of_continuous_graph:
  fixes f::"'a::metric_space \<Rightarrow> 'b::metric_space" and E::"'a::metric_space set"
  assumes "compact E" "continuous_on E f"
  shows "compact {(x, f x) | x. x \<in> E}"
Our comment on the codex statement: < missed the double implication but otherwise correct>
 *)
theorem exercise_4_6: fixes f::"'a::metric_space \<Rightarrow> 'b::metric_space"
and E::"'a::metric_space set"
assumes "compact E"
shows "continuous_on E f \<longleftrightarrow> compact  {(x, f x) | x. x \<in> E} " oops

(*
problem_number:4_8a
natural language statement:
Let $f$ be a real uniformly continuous function on the bounded set $E$ in $R^{1}$.
Prove that $f$ is bounded on $E$.
lean statement:
theorem exercise_4_8a
  (E : set \<real>) (f : \<real> \<rightarrow> \<real>) (hf : uniform_continuous_on f E)
  (hE : metric.bounded E) : metric.bounded (set.image f E) :=

codex statement:
theorem bounded_of_uniformly_continuous_on_bounded:
  fixes f::"'a::metric_space \<Rightarrow> 'b::real_normed_vector"
  assumes "bounded (UNIV::'a set)" "uniformly_continuous_on UNIV f"
  shows "bounded (range f)"
Our comment on the codex statement: < wrong (didn't refer to set E, wrong types) but quite close >
 *)
theorem exercise_4_8a:

   fixes f::"real \<Rightarrow> real" and E::" real set"
  assumes "bounded E" "uniformly_continuous_on E f"
  shows "bounded (range f)"

  oops

(*
problem_number:4_11a
natural language statement:
Suppose $f$ is a uniformly continuous mapping of a metric
space $X$ into a metric space $Y$ and prove that $\left\{f\left(x_{n}\right)\right\}$
is a Cauchy sequence in
lean statement:
theorem exercise_4_11a
  {X : Type*} [metric_space X]
  {Y : Type*} [metric_space Y]
  (f : X \<rightarrow> Y) (hf : uniform_continuous f)
  (x : \<nat> \<rightarrow> X) (hx : cauchy_seq x) :
  cauchy_seq (\<lambda> n, f (x n)) :=

codex statement:
theorem cauchy_of_uniform_continuous:
  fixes f::"'a::metric_space \<Rightarrow> 'b::metric_space"
  assumes "uniformly_continuous_on UNIV f" "cauchy (f ∘ g)"
  shows "cauchy g"
Our comment on the codex statement: <overall wrong, and it's
strange that it makes a function g appear out of nowhere. Also uses
cauchy instead of Cauchy (the former doesn't exist>
 *)

(*TODO something wrong with natural language statement? *)
theorem exercise_4_11a: undefined
  oops

(*
problem_number:4_12
natural language statement:
A uniformly continuous function of a uniformly continuous function is uniformly continuous.
lean statement:
theorem exercise_4_12
  {\<alpha> β \<nu> : Type*} [uniform_space \<alpha>] [uniform_space β] [uniform_space \<nu>]
  {f : \<alpha> \<rightarrow> β} {g : β \<rightarrow> \<nu>}
  (hf : uniform_continuous f) (hg : uniform_continuous g) :
  uniform_continuous (g ∘ f) :=

codex statement:
theorem uniform_continuous_of_uniform_continuous_comp:
  fixes f::"'a::metric_space \<Rightarrow> 'b::metric_space" and g::"'b::metric_space \<Rightarrow> 'c::metric_space"
  assumes "uniformly_continuous_on UNIV f" "uniformly_continuous_on UNIV g"
  shows "uniformly_continuous_on UNIV (g ∘ f)"
Our comment on the codex statement: <correct, I copy-paste it below>
 *)
theorem exercise_4_12:
  fixes f::"'a::metric_space \<Rightarrow> 'b::metric_space" and
g::"'b::metric_space \<Rightarrow> 'c::metric_space"
  assumes "uniformly_continuous_on UNIV f" "uniformly_continuous_on UNIV g"
  shows "uniformly_continuous_on UNIV (g ∘ f)"
    oops

(*
problem_number:4_14
natural language statement:
Let $I=[0,1]$ be the closed unit interval.
Suppose $f$ is a continuous mapping of $I$ into $I$. Prove that $f(x)=x$ for at least one $x \in I$.
lean statement:
theorem exercise_4_14 [topological_space I]
  [linear_order I] (f : I \<rightarrow> I) (hf : continuous f) :
  \<exists> (x : I), f x = x :=

codex statement:
theorem exists_fixed_point_of_continuous_on_closed_interval:
  fixes f::"real \<Rightarrow> real"
  assumes "continuous_on {0..1} f"
  shows "\<exists>x. x\<in>{0..1} \<and> f x = x"
Our comment on the codex statement: <almost correct, forgot range>
 *)
theorem exercise_4_14:
   fixes f::"real \<Rightarrow> real"
  assumes "continuous_on {0..1} f" and "range f = {0..1}"
  shows "\<exists>x. x\<in>{0..1} \<and> f x = x"

  oops

(*
problem_number:4_15
natural language statement:
Prove that every continuous open mapping of $R^{1}$ into $R^{1}$ is monotonic.
lean statement:
theorem exercise_4_15 {f : \<real> \<rightarrow> \<real>}
  (hf : continuous f) (hof : is_open_map f) :
  monotone f :=

codex statement:
theorem monotonic_of_continuous_open_mapping:
  fixes f::"real \<Rightarrow> real"
  assumes "continuous_on UNIV f" "open_mapping f"
  shows "mono f"
Our comment on the codex statement: < wrong: used the definition open_mapping which doesn't exist.
Also, mono in Isabelle means monotone increasing, while it can either be monotone increasing
or monotone decreasing>
 *)
theorem exercise_4_15:
   fixes f::"real \<Rightarrow> real"
  assumes "continuous_on UNIV f"  "open (f ` UNIV) "
  shows "mono f \<or> antimono f "

  oops

(*
problem_number:4_19
natural language statement:
Suppose $f$ is a real function with domain $R^{1}$ which has the intermediate value property.
If $f(a)<c<f(b)$, then $f(x)=c$ for some $x$ between $a$ and $b$. Suppose also, for every rational
$r$, that the set of all $x$ with $f(x)=r$ is closed. Prove that $f$ is continuous.
lean statement:
theorem exercise_4_19
  {f : \<real> \<rightarrow> \<real>} (hf : \<forall> a b c, a < b \<rightarrow> f a < c \<rightarrow> c < f b \<rightarrow> \<exists> x, a < x \<and> x < b \<and> f x = c)
  (hg : \<forall> r : \<rat>, is_closed {x | f x = r}) : continuous f :=

codex statement:
theorem continuous_of_intermediate_value_property_and_closed_set_of_rational_value:
  fixes f::"real \<Rightarrow> real"
  assumes "\<forall>a b c. a < b \<longrightarrow> f a < c \<longrightarrow> c < f b \<longrightarrow>
\<exists>x. a < x \<longrightarrow> x < b \<longrightarrow> f x = c"
    "\<forall>r. closed {x | x \<in> UNIV \<and> f x = r}"
  shows "continuous_on UNIV f"
Our comment on the codex statement: <wrong >
 *)
theorem exercise_4_19:
  fixes f::"real \<Rightarrow> real"
  assumes " \<forall> a b c. ( (f a < c \<and> c < f b )  \<longrightarrow>
(\<exists> x::real. (f x) =c \<and> ((x \<le> a \<and> x \<ge> b) \<or>(x \<le> b \<and> x \<ge> a))   ) )"
 and  "\<forall>r::rat. (closed {x. x \<in> UNIV \<and> f x = r})"
   shows "continuous_on UNIV f"
  oops

(*
problem_number:4_21a
natural language statement:
Suppose $K$ and $F$ are disjoint sets in a metric space $X, K$ is compact, $F$ is closed.
Prove that there exists $\delta>0$ such that $d(p, q)>\delta$ if $p \in K, q \in F$.
lean statement:
theorem exercise_4_21a {X : Type*} [metric_space X]
  (K F : set X) (hK : is_compact K) (hF : is_closed F) (hKF : disjoint K F) :
  \<exists> (δ : \<real>), δ > 0 \<and> \<forall> (p q : X), p \<in> K \<rightarrow> q \<in> F \<rightarrow> dist p q \<ge> δ :=

codex statement:
theorem exists_delta_of_disjoint_compact_closed:
  fixes K F::"'a::metric_space set"
  assumes "compact K" "closed F" "K ∩ F = {}"
  shows "\<exists>δ>0. \<forall>p\<in>K. \<forall>q\<in>F. dist p q > δ"
Our comment on the codex statement: <correct formalisation, my formulation slightly differs>
 *)
theorem exercise_4_21a:

  fixes X::"'a::metric_space set"
  assumes "K \<subseteq> X"  "F \<subseteq> X" "compact K" "closed F" "K ∩ F = {}"
  shows "\<exists> \<delta>>0. \<forall>p\<in>K. \<forall>q\<in>F. dist p q > \<delta>"
  oops

(*
problem_number:4_24
natural language statement:
Assume that $f$ is a continuous real function defined in $(a, b)$
such that $f\left(\frac{x+y}{2}\right) \leq \frac{f(x)+f(y)}{2}$ for all $x, y \in(a, b)$.
Prove that $f$ is convex.
lean statement:
theorem exercise_4_24 {f : \<real> \<rightarrow> \<real>}
  (hf : continuous f) (a b : \<real>) (hab : a < b)
  (h : \<forall> x y : \<real>, a < x \<rightarrow> x < b \<rightarrow> a < y \<rightarrow> y < b \<rightarrow> f ((x + y) / 2) \<le> (f x + f y) / 2) :
  convex_on \<real> (set.Ioo a b) f :=

codex statement:
theorem convex_of_continuous_and_ineq:
  fixes f::"real \<Rightarrow> real"
  assumes "continuous_on {a<..<b} f" "\<forall>x y. x \<in> {a<..<b} \<longrightarrow> y \<in> {a<..<b} \<longrightarrow> f ((x + y) / 2) \<le> (f x + f y) / 2"
  shows "convex_on {a<..<b} f"
Our comment on the codex statement: <close but not correct. Missed the absolute value.>
 *)
theorem exercise_4_24:
   fixes f::"real \<Rightarrow> real"
   assumes

 "continuous_on {a<..<b} f"
"\<forall>x y. (x  \<in> {a<..<b} \<and> y \<in> {a<..<b}
\<longrightarrow>  f (abs((x + y) / 2)) \<le> (f x + f y) / 2)"
  shows "convex_on {a<..<b} f"

  oops

(*
problem_number:4_26a
natural language statement:
Suppose $X, Y, Z$ are metric spaces, and $Y$ is compact.
Let $f$ map $X$ into $Y$, let $g$ be a continuous one-to-one mapping of $Y$ into $Z$,
and put $h(x)=g(f(x))$ for $x \in X$.
Prove that $f$ is uniformly continuous if $h$ is uniformly continuous.
lean statement:

codex statement:
theorem uniform_continuous_of_continuous_injective_uniform_continuous_comp:
  fixes f::"'a::metric_space \<Rightarrow> 'b::metric_space" and g::"'b::metric_space \<Rightarrow> 'c::metric_space"
  assumes "compact (UNIV::'b set)" "continuous_on UNIV g" "inj g" "uniformly_continuous_on UNIV (g ∘ f)"
  shows "uniformly_continuous_on UNIV f"
Our comment on the codex statement: <correct, I copy-paste it below>
 *)
theorem exercise_4_26a:

  fixes f::"'a::metric_space \<Rightarrow> 'b::metric_space"
and g::"'b::metric_space \<Rightarrow> 'c::metric_space"
assumes "compact (UNIV::'b set)" "continuous_on UNIV g"  "inj g"

"uniformly_continuous_on UNIV (g ∘ f)"
  shows "uniformly_continuous_on UNIV f"

  oops

(*
problem_number:5_1
natural language statement:
Let $f$ be defined for all real $x$, and suppose that $|f(x)-f(y)|
\leq(x-y)^{2}$for all real $x$ and $y$. Prove that $f$ is constant.
lean statement:
theorem exercise_5_1
  {f : \<real> \<rightarrow> \<real>} (hf : \<forall> x y : \<real>, | (f x - f y) | \<le> (x - y) ^ 2) :
  \<exists> c, f = \<lambda> x, c :=

codex statement:
theorem constant_of_diff_leq_square_diff:
  fixes f::"real \<Rightarrow> real"
  assumes "\<forall>x y. abs (f x - f y) \<le> (x - y)^2"
  shows "f constant_on UNIV"
Our comment on the codex statement: <correct, I copy-paste it below>
 *)
theorem exercise_5_1:
   fixes f::"real \<Rightarrow> real"
  assumes "\<forall>x y. abs (f x - f y) \<le> (x - y)^2"
  shows "f constant_on UNIV"
  oops

(*
problem_number:5_2
natural language statement:
Suppose $f^{\prime}(x)>0$ in $(a, b)$. Prove that $f$ is strictly
increasing in $(a, b)$, and let $g$ be its inverse function.
Prove that $g$ is differentiable, and that$g^{\prime}(f(x))=\frac{1}{f^{\prime}(x)} \quad(a<x<b)$
lean statement:
theorem exercise_5_2 {a b : \<real>}
  {f g : \<real> \<rightarrow> \<real>} (hf : \<forall> x \<in> set.Ioo a b, deriv f x > 0)
  (hg : g = inv f)
  (hg_diff : differentiable_on \<real> g (set.Ioo a b)) :
  differentiable_on \<real> g (set.Ioo a b) \<and>
  \<forall> x \<in> set.Ioo a b, deriv g x = 1 / deriv f x :=

codex statement:
theorem derivative_of_inverse_function:
  fixes f::"real \<Rightarrow> real" and g::"real \<Rightarrow> real"
  assumes "a < b" "continuous_on {a..b} f" "\<forall>x\<in>{a..b}. f differentiable (at x)"
"\<forall>x\<in>{a..b}. 0 < f' x"
  shows "\<forall>x\<in>{a..b}. g differentiable (at x)" "\<forall>x\<in>{a..b}. g' x = 1 / f' (g x)"
Our comment on the codex statement: <quite close but wrong deriv  notation, misses one assumption
and one concl. >*)

theorem exercise_5_2:
   fixes f::"real \<Rightarrow> real"  and g::"real \<Rightarrow> real"
   assumes "\<forall>x\<in>{a..b}. f differentiable (at x)"
"\<forall>x\<in>{a..b}. 0 < deriv f x"  and "\<forall> x\<in>{a..b} . g x = 1/ f x"

shows "mono f" "\<forall>x\<in>{a..b}. g differentiable (at x)"
"\<forall>x\<in>{a..b}. deriv g ( f x) = 1 / deriv f x"
  oops

(*
problem_number:5_3
natural language statement:
Suppose $g$ is a real function on $R^{1}$, with bounded derivative
(say $\left|g^{\prime}\right| \leq M$ ). Fix $\varepsilon>0$, and define $f(x)=x+\varepsilon g(x)$.
Prove that $f$ is one-to-one if $\varepsilon$ is small enough.
lean statement:
theorem exercise_5_3 {g : \<real> \<rightarrow> \<real>} (hg : continuous g)
  (hg' : \<exists> M : \<real>, \<forall> x : \<real>, | deriv g x | \<le> M) :
  \<exists> N, \<forall> \<epsilon> > 0, \<epsilon> < N \<rightarrow>
function.injective (\<lambda> x : \<real>, x + \<epsilon> * g x) :=

codex statement:
theorem injective_of_small_epsilon:
  fixes g::"real \<Rightarrow> real"
  assumes "\<forall>x. abs (g' x) \<le> M"
  shows "\<exists>\<epsilon>>0. \<forall>x y. abs (x - y) < \<epsilon> \<longrightarrow> g x \<noteq> g y"
Our comment on the codex statement: <wrong >
 *)
theorem exercise_5_3:
  fixes g::"real \<Rightarrow> real" and \<epsilon> K  M:: real and f::"real \<Rightarrow> real"
  assumes "\<forall>x. abs (deriv g x) \<le> M" and " \<forall> x. f x =x + \<epsilon> *( g x )"
  shows " \<epsilon> < K \<longrightarrow> inj f"

  oops

(*
problem_number:5_4
natural language statement:
If $C_{0}+\frac{C_{1}}{2}+\cdots+\frac{C_{n-1}}{n}+\frac{C_{n}}{n+1}=0,$ where $C_{0}, \ldots,
C_{n}$ are real constants, prove that the equation $C_{0}+C_{1} x+\cdots+C_{n-1} x^{n-1}+C_{n} x^{n}=0$
has at least one real root between 0 and 1 .
lean statement:
theorem exercise_5_4 {n : \<nat>}
  (C : \<nat> \<rightarrow> \<real>)
  (hC : \<Sum> i in (finset.range (n + 1)), (C i) / (i + 1) = 0) :
  \<exists> x, x \<in> (set.Icc (0 : \<real>) 1) \<and> \<Sum> i in finset.range (n + 1), (C i) * (x^i) = 0 :=

codex statement:
theorem exists_real_root_of_polynomial_of_sum_eq_zero:
  fixes C::"real \<Rightarrow> real"
  assumes "\<forall>n. C n = 0" "\<Sum>n. C n / (n+1) = 0"
  shows "\<exists>x. 0 < x \<and> x < 1 \<and> (\<Sum>n. C n * x^n) = 0"
Our comment on the codex statement: <YOU CAN LEAVE YOUR COMMENT HERE>
 *)
theorem exercise_5_4:
  undefined
  oops

(*
problem_number:5_5
natural language statement:
Suppose $f$ is defined and differentiable for every $x>0$,
 and $f^{\prime}(x) \rightarrow 0$ as $x \rightarrow+\infty$. Put $g(x)=f(x+1)-f(x)$.
Prove that $g(x) \rightarrow 0$ as $x \rightarrow+\infty$.
lean statement:
theorem exercise_5_5
  {f : \<real> \<rightarrow> \<real>}
  (hfd : differentiable \<real> f)
  (hf : tendsto (deriv f) at_top (𝓝 0)) :
  tendsto (\<lambda> x, f (x + 1) - f x) at_top at_top :=

codex statement:
theorem tendsto_zero_of_tendsto_zero_derivative:
  fixes f::"real \<Rightarrow> real"
  assumes "\<forall>x. 0 < x \<longrightarrow> f differentiable (at x)" "((\<lambda>x. f' x) ---> 0) at_top"
  shows "((\<lambda>x. f (x + 1) - f x) ---> 0) at_top"
Our comment on the codex statement: <several wrong symbols>
 *)
theorem exercise_5_5:
 fixes f::"real \<Rightarrow> real"  and g::"real \<Rightarrow> real"
 assumes "\<forall>x >0. f differentiable (at x)" "\<forall> x. g(x)=f(x+1)-f(x)"
"eventually ((λx. deriv f(x )) ⤏ 0) at_top"
  shows "eventually ((λx. deriv g(x )) ⤏ 0) at_top"
  oops
(*
problem_number:5_6
natural language statement:
Suppose (a) $f$ is continuous for $x \geq 0$,
(b) $f^{\prime}(x)$ exists for $x>0$, (c) $f(0)=0$,
(d) $f^{\prime}$ is monotonically increasing. Put $g(x)=\frac{f(x)}{x} \quad(x>0)$
and prove that $g$ is monotonically increasing.
lean statement:
theorem exercise_5_6
  {f : \<real> \<rightarrow> \<real>}
  (hf1 : continuous f)
  (hf2 : \<forall> x, differentiable_at \<real> f x)
  (hf3 : f 0 = 0)
  (hf4 : monotone (deriv f)) :
  monotone_on (\<lambda> x, f x / x) (set.Ioi 0) :=

codex statement:
theorem monotone_increasing_of_continuous_derivative_monotone_increasing:
  fixes f::"real \<Rightarrow> real"
  assumes "continuous_on {0..} f" "\<forall>x>0. (f has_real_derivative f' x) (at x)" "f 0 = 0" "mono f'"
  shows "mono (\<lambda>x. f x / x)"
Our comment on the codex statement: <correct, copy-pasted with slight change>
 *)
theorem exercise_5_6: fixes f::"real \<Rightarrow> real"
   assumes "continuous_on {0..} f"
"\<forall>x>0. (f has_real_derivative f' x) (at x)" "f 0 = 0" "mono f'"
"\<forall> x>0. g x = f x / x"
  shows "mono g"

  oops

(*
problem_number:5_7
natural language statement:
Suppose $f^{\prime}(x), g^{\prime}(x)$ exist, $g^{\prime}(x) \neq 0$,
and $f(x)=g(x)=0$. Prove that $\lim _{t \rightarrow x} \frac{f(t)}{g(t)}=\frac{f^{\prime}(x)}{g^{\prime}(x)}.$
lean statement:
theorem exercise_5_7
  {f g : \<real> \<rightarrow> \<real>} {x : \<real>}
  (hf' : differentiable_at \<real> f 0)
  (hg' : differentiable_at \<real> g 0)
  (hg'_ne_0 : deriv g 0 \<noteq> 0)
  (f0 : f 0 = 0) (g0 : g 0 = 0) :
  tendsto (\<lambda> x, f x / g x) (𝓝 x) (𝓝 (deriv f x / deriv g x)) :=

codex statement:
theorem lim_frac_of_derivative_eq_derivative_frac:
  fixes f g::"real \<Rightarrow> real"
  assumes "f differentiable (at x)" "g differentiable (at x)" "g x \<noteq> 0" "f x = g x = 0"
  shows "(f has_real_derivative (f' x)) (at x)" "(g has_real_derivative (g' x)) (at x)"
Our comment on the codex statement: <codex gives wrong assumptions and conclusions>
 *)
theorem exercise_5_7:
 (*  fixes f g::"real \<Rightarrow> real" assumes
  " (f has_real_derivative f' x) (at x)"
   " (g has_real_derivative g' x) (at x)"
 "g' x \<noteq> 0" " f x = g x" "f x = 0"
*)
undefined oops

(*
problem_number:5_15
natural language statement:
Suppose $a \in R^{1}, f$ is a twice-differentiable real function
on $(a, \infty)$, and $M_{0}, M_{1}, M_{2}$ are the least upper
bounds of $|f(x)|,\left|f^{\prime}(x)\right|,\left|f^{\prime \prime}(x)\right|$,
respectively, on $(a, \infty)$. Prove that $M_{1}^{2} \leq 4 M_{0} M_{2} .$
lean statement:
theorem exercise_5_15 {f : \<real> \<rightarrow> \<real>} (a M0 M1 M2 : \<real>)
  (hf' : differentiable_on \<real> f (set.Ici a))
  (hf'' : differentiable_on \<real> (deriv f) (set.Ici a))
  (hM0 : M0 = Sup {(| f x | )| x \<in> (set.Ici a)})
  (hM1 : M1 = Sup {(| deriv f x | )| x \<in> (set.Ici a)})
  (hM2 : M2 = Sup {(| deriv (deriv f) x | )| x \<in> (set.Ici a)}) :
  (M1 ^ 2) \<le> 4 * M0 * M2 :=

codex statement: (* TODO MISSING*)

Our comment on the codex statement: <YOU CAN LEAVE YOUR COMMENT HERE>
 *)
theorem exercise_5_15: undefined oops

(*
problem_number:5_17
natural language statement:
Suppose $f$ is a real, three times differentiable function on $[-1,1]$,
such that $f(-1)=0, \quad f(0)=0, \quad f(1)=1, \quad f^{\prime}(0)=0 .$
Prove that $f^{(3)}(x) \geq 3$ for some $x \in(-1,1)$.
lean statement:
theorem exercise_5_17
  {f : \<real> \<rightarrow> \<real>}
  (hf' : differentiable_on \<real> f (set.Icc (-1) 1))
  (hf'' : differentiable_on \<real> (deriv f) (set.Icc 1 1))
  (hf''' : differentiable_on \<real> (deriv (deriv f)) (set.Icc 1 1))
  (hf0 : f (-1) = 0)
  (hf1 : f 0 = 0)
  (hf2 : f 1 = 1)
  (hf3 : deriv f 0 = 0) :
  \<exists> x, x \<in> set.Ioo (-1 : \<real>) 1 \<and> deriv (deriv (deriv f)) x \<ge> 3 :=

codex statement:
theorem exists_x_in_interval_of_three_times_differentiable_function:
  fixes f::"real \<Rightarrow> real"
  assumes "\<forall>x. f differentiable (at x)" "\<forall>x. f differentiable (at x within {-1..1})" "\<forall>x. f differentiable (at x within {-1..1})" "f (-1) = 0" "f 0 = 0" "f 1 = 1" "f' 0 = 0"
  shows "\<exists>x\<in>{-1..1}. f''' x \<ge> 3"
Our comment on the codex statement: <YOU CAN LEAVE YOUR COMMENT HERE>
 *)
theorem exercise_5_17: undefined oops

(*
problem_number:6_1
natural language statement:
Suppose $\alpha$ increases on $[a, b],
a \leq x_{0} \leq b, \alpha$ is continuous at $x_{0}, f\left(x_{0}\right)=1$,
and $f(x)=0$ if $x \neq x_{0}$. Prove that $f \in \mathcal{R}(\alpha)$ and that $\int f d \alpha=0$.
lean statement:

codex statement:
theorem integral_of_continuous_function_eq_zero:
  fixes f::"real \<Rightarrow> real" and \<alpha>::"real \<Rightarrow> real"
  assumes "a \<le> x₀" "x₀ \<le> b" "continuous (at x₀) \<alpha>" "f x₀ = 1"
"f x = 0" "\<forall>x. a \<le> x \<and> x \<le> b \<longrightarrow> \<alpha> x \<le> \<alpha> x₀"
  shows "f \<in> borel_measurable \<alpha>" "integral \<alpha> f = 0"
Our comment on the codex statement: <YOU CAN LEAVE YOUR COMMENT HERE>
 *)
theorem exercise_6_1: undefined oops
(*TODO: note there are different kinds of integration, do we need Riemann here? *)

(*
problem_number:6_2
natural language statement:
Suppose $f \geq 0, f$ is continuous on $[a, b]$, and $\int_{a}^{b} f(x) d x=0$.
Prove that $f(x)=0$ for all $x \in[a, b]$.
lean statement:

codex statement:
theorem zero_integral_of_continuous_nonneg_implies_zero_function:
  fixes f::"real \<Rightarrow> real"
  assumes "continuous_on {a..b} f" "f \<ge> 0" "integral {a..b} f = 0"
  shows "\<forall>x\<in>{a..b}. f x = 0"
Our comment on the codex statement: <almost correct, but syntactical error in one of the assumptions.
 By the way: TODO  it is not
actually clear which kind of integral is required from the nat lang. statement. >
 *)
theorem exercise_6_2:
  fixes f::"real \<Rightarrow> real"
  assumes "continuous_on {a..b} f"  "\<forall> x \<in> UNIV. f x \<ge> 0" "integral {a..b} f = 0"
  shows  "\<forall>x\<in>{a..b}. f x = 0"
  oops

(*
problem_number:6_4
natural language statement:
If $f(x)=0$ for all irrational $x, f(x)=1$ for all rational $x$,
prove that $f \notin \mathcal{R}$ on $[a, b]$ for any $a<b$.
lean statement:

codex statement:
theorem not_Riemann_integrable_of_zero_for_irrational_one_for_rational:
  fixes f::"real \<Rightarrow> real"
  assumes "\<forall>x. irrational x \<longrightarrow> f x = 0" "\<forall>x. rational x \<longrightarrow> f x = 1"
  shows "\<forall>a b. a < b \<longrightarrow> ¬ (f integrable_on {a..b})"
Our comment on the codex statement: <uses nonexistent Isabelle defs like rational, irrational>
 *)
theorem exercise_6_4:
   fixes f::"real \<Rightarrow> real"
   assumes "\<forall>x. x \<notin> Rats \<longrightarrow> f x = 0"
"\<forall>x \<in> Rats.  f x = 1"
  shows "\<forall>a b. a < b \<longrightarrow> ¬ (f integrable_on {a..b})"
  oops
(*TODO: again note there are different kinds of integration, don't we need Riemann here? *)

(*
problem_number:6_6
natural language statement:
Let $P$ be the Cantor set. Let $f$ be a bounded real function on $[0,1]$
which is continuous at every point outside $P$. Prove that $f \in \mathcal{R}$ on $[0,1]$.
lean statement:
MISSING
codex statement:
theorem R_of_bounded_continuous_at_outside_Cantor:
  fixes f::"real \<Rightarrow> real"
  assumes "bounded (range f)" "\<forall>x\<in>{0..1} - cantor. continuous (at x) f"
  shows "f \<in> R {0..1}"
Our comment on the codex statement: <YOU CAN LEAVE YOUR COMMENT HERE>
 *)
theorem exercise_6_6:

 undefined oops

end


(*  Title:      CTT/CTT.thy
    Author:     Lawrence C Paulson, Cambridge University Computer Laboratory
    Copyright   1993  University of Cambridge
*)

theory CTT
imports Pure
begin

section \<open>Constructive Type Theory: axiomatic basis\<close>

ML_file \<open>~~/src/Provers/typedsimp.ML\<close>
setup Pure_Thy.old_appl_syntax_setup

typedecl i
typedecl t
typedecl o

consts
  \<comment> \<open>Judgments\<close>
  Type      :: "t \<Rightarrow> prop"          ("(_ type)" [10] 5)
  Eqtype    :: "[t,t]\<Rightarrow>prop"        ("(_ =/ _)" [10,10] 5)
  Elem      :: "[i, t]\<Rightarrow>prop"       ("(_ /: _)" [10,10] 5)
  Eqelem    :: "[i,i,t]\<Rightarrow>prop"      ("(_ =/ _ :/ _)" [10,10,10] 5)
  Reduce    :: "[i,i]\<Rightarrow>prop"        ("Reduce[_,_]")
  \<comment> \<open>Types for truth values\<close>
  F         :: "t"
  T         :: "t"          \<comment> \<open>\<open>F\<close> is empty, \<open>T\<close> contains one element\<close>
  contr     :: "i\<Rightarrow>i"
  tt        :: "i"
  \<comment> \<open>Natural numbers\<close>
  N         :: "t"
  Zero      :: "i"                  ("0")
  succ      :: "i\<Rightarrow>i"
  rec       :: "[i, i, [i,i]\<Rightarrow>i] \<Rightarrow> i"
  \<comment> \<open>Binary sum\<close>
  Plus      :: "[t,t]\<Rightarrow>t"           (infixr "+" 40)
  inl       :: "i\<Rightarrow>i"
  inr       :: "i\<Rightarrow>i"
  "when"    :: "[i, i\<Rightarrow>i, i\<Rightarrow>i]\<Rightarrow>i"
  \<comment> \<open>General sum and binary product\<close>
  Sum       :: "[t, i\<Rightarrow>t]\<Rightarrow>t"
  pair      :: "[i,i]\<Rightarrow>i"           ("(1<_,/_>)")
  fst       :: "i\<Rightarrow>i"
  snd       :: "i\<Rightarrow>i"
  split     :: "[i, [i,i]\<Rightarrow>i] \<Rightarrow>i"
  \<comment> \<open>General product and function space\<close>
  Prod      :: "[t, i\<Rightarrow>t]\<Rightarrow>t"
  lambda    :: "(i \<Rightarrow> i) \<Rightarrow> i"      (binder "\<^bold>\<lambda>" 10)
  app       :: "[i,i]\<Rightarrow>i"           (infixl "`" 60)
  \<comment> \<open>Equality type\<close>
  Eq        :: "[t,i,i]\<Rightarrow>t"
  eq        :: "i"

text \<open>Some inexplicable syntactic dependencies; in particular, "0"
 must be introduced after the judgment forms.\<close>

syntax
  "_PROD"   :: "[idt,t,t]\<Rightarrow>t"       ("(3\<Prod>_:_./ _)" 10)
  "_SUM"    :: "[idt,t,t]\<Rightarrow>t"       ("(3\<Sum>_:_./ _)" 10)
translations
  "\<Prod>x:A. B" \<rightleftharpoons> "CONST Prod(A, \<lambda>x. B)"
  "\<Sum>x:A. B" \<rightleftharpoons> "CONST Sum(A, \<lambda>x. B)"

abbreviation Arrow :: "[t,t]\<Rightarrow>t"  (infixr "\<longrightarrow>" 30)
  where "A \<longrightarrow> B \<equiv> \<Prod>_:A. B"

abbreviation Times :: "[t,t]\<Rightarrow>t"  (infixr "\<times>" 50)
  where "A \<times> B \<equiv> \<Sum>_:A. B"

text \<open>
  Reduction: a weaker notion than equality;  a hack for simplification.
  \<open>Reduce[a,b]\<close> means either that \<open>a = b : A\<close> for some \<open>A\<close> or else
    that \<open>a\<close> and \<open>b\<close> are textually identical.

  Does not verify \<open>a:A\<close>!  Sound because only \<open>trans_red\<close> uses a \<open>Reduce\<close>
  premise. No new theorems can be proved about the standard judgments.
\<close>
axiomatization
where
  refl_red: "\<And>a. Reduce[a,a]" and
  red_if_equal: "\<And>a b A. a = b : A \<Longrightarrow> Reduce[a,b]" and
  trans_red: "\<And>a b c A. \<lbrakk>a = b : A; Reduce[b,c]\<rbrakk> \<Longrightarrow> a = c : A" and

  \<comment> \<open>Reflexivity\<close>

  refl_type: "\<And>A. A type \<Longrightarrow> A = A" and
  refl_elem: "\<And>a A. a : A \<Longrightarrow> a = a : A" and

  \<comment> \<open>Symmetry\<close>

  sym_type:  "\<And>A B. A = B \<Longrightarrow> B = A" and
  sym_elem:  "\<And>a b A. a = b : A \<Longrightarrow> b = a : A" and

  \<comment> \<open>Transitivity\<close>

  trans_type:   "\<And>A B C. \<lbrakk>A = B; B = C\<rbrakk> \<Longrightarrow> A = C" and
  trans_elem:   "\<And>a b c A. \<lbrakk>a = b : A; b = c : A\<rbrakk> \<Longrightarrow> a = c : A" and

  equal_types:  "\<And>a A B. \<lbrakk>a : A; A = B\<rbrakk> \<Longrightarrow> a : B" and
  equal_typesL: "\<And>a b A B. \<lbrakk>a = b : A; A = B\<rbrakk> \<Longrightarrow> a = b : B" and

  \<comment> \<open>Substitution\<close>

  subst_type:   "\<And>a A B. \<lbrakk>a : A; \<And>z. z:A \<Longrightarrow> B(z) type\<rbrakk> \<Longrightarrow> B(a) type" and
  subst_typeL:  "\<And>a c A B D. \<lbrakk>a = c : A; \<And>z. z:A \<Longrightarrow> B(z) = D(z)\<rbrakk> \<Longrightarrow> B(a) = D(c)" and

  subst_elem:   "\<And>a b A B. \<lbrakk>a : A; \<And>z. z:A \<Longrightarrow> b(z):B(z)\<rbrakk> \<Longrightarrow> b(a):B(a)" and
  subst_elemL:
    "\<And>a b c d A B. \<lbrakk>a = c : A; \<And>z. z:A \<Longrightarrow> b(z)=d(z) : B(z)\<rbrakk> \<Longrightarrow> b(a)=d(c) : B(a)" and

  \<comment> \<open>The type \<open>N\<close> -- natural numbers\<close>

  NF: "N type" and
  NI0: "0 : N" and
  NI_succ: "\<And>a. a : N \<Longrightarrow> succ(a) : N" and
  NI_succL:  "\<And>a b. a = b : N \<Longrightarrow> succ(a) = succ(b) : N" and

  NE:
   "\<And>p a b C. \<lbrakk>p: N; a: C(0); \<And>u v. \<lbrakk>u: N; v: C(u)\<rbrakk> \<Longrightarrow> b(u,v): C(succ(u))\<rbrakk>
   \<Longrightarrow> rec(p, a, \<lambda>u v. b(u,v)) : C(p)" and

  NEL:
   "\<And>p q a b c d C. \<lbrakk>p = q : N; a = c : C(0);
      \<And>u v. \<lbrakk>u: N; v: C(u)\<rbrakk> \<Longrightarrow> b(u,v) = d(u,v): C(succ(u))\<rbrakk>
   \<Longrightarrow> rec(p, a, \<lambda>u v. b(u,v)) = rec(q,c,d) : C(p)" and

  NC0:
   "\<And>a b C. \<lbrakk>a: C(0); \<And>u v. \<lbrakk>u: N; v: C(u)\<rbrakk> \<Longrightarrow> b(u,v): C(succ(u))\<rbrakk>
   \<Longrightarrow> rec(0, a, \<lambda>u v. b(u,v)) = a : C(0)" and

  NC_succ:
   "\<And>p a b C. \<lbrakk>p: N;  a: C(0); \<And>u v. \<lbrakk>u: N; v: C(u)\<rbrakk> \<Longrightarrow> b(u,v): C(succ(u))\<rbrakk> \<Longrightarrow>
   rec(succ(p), a, \<lambda>u v. b(u,v)) = b(p, rec(p, a, \<lambda>u v. b(u,v))) : C(succ(p))" and

  \<comment> \<open>The fourth Peano axiom.  See page 91 of Martin-Löf's book.\<close>
  zero_ne_succ: "\<And>a. \<lbrakk>a: N; 0 = succ(a) : N\<rbrakk> \<Longrightarrow> 0: F" and

  \<comment> \<open>The Product of a family of types\<close>

  ProdF: "\<And>A B. \<lbrakk>A type; \<And>x. x:A \<Longrightarrow> B(x) type\<rbrakk> \<Longrightarrow> \<Prod>x:A. B(x) type" and

  ProdFL:
    "\<And>A B C D. \<lbrakk>A = C; \<And>x. x:A \<Longrightarrow> B(x) = D(x)\<rbrakk> \<Longrightarrow> \<Prod>x:A. B(x) = \<Prod>x:C. D(x)" and

  ProdI:
    "\<And>b A B. \<lbrakk>A type; \<And>x. x:A \<Longrightarrow> b(x):B(x)\<rbrakk> \<Longrightarrow> \<^bold>\<lambda>x. b(x) : \<Prod>x:A. B(x)" and

  ProdIL: "\<And>b c A B. \<lbrakk>A type; \<And>x. x:A \<Longrightarrow> b(x) = c(x) : B(x)\<rbrakk> \<Longrightarrow>
    \<^bold>\<lambda>x. b(x) = \<^bold>\<lambda>x. c(x) : \<Prod>x:A. B(x)" and

  ProdE:  "\<And>p a A B. \<lbrakk>p : \<Prod>x:A. B(x); a : A\<rbrakk> \<Longrightarrow> p`a : B(a)" and
  ProdEL: "\<And>p q a b A B. \<lbrakk>p = q: \<Prod>x:A. B(x); a = b : A\<rbrakk> \<Longrightarrow> p`a = q`b : B(a)" and

  ProdC: "\<And>a b A B. \<lbrakk>a : A; \<And>x. x:A \<Longrightarrow> b(x) : B(x)\<rbrakk> \<Longrightarrow> (\<^bold>\<lambda>x. b(x)) ` a = b(a) : B(a)" and

  ProdC2: "\<And>p A B. p : \<Prod>x:A. B(x) \<Longrightarrow> (\<^bold>\<lambda>x. p`x) = p : \<Prod>x:A. B(x)" and

  \<comment> \<open>The Sum of a family of types\<close>

  SumF:  "\<And>A B. \<lbrakk>A type; \<And>x. x:A \<Longrightarrow> B(x) type\<rbrakk> \<Longrightarrow> \<Sum>x:A. B(x) type" and
  SumFL: "\<And>A B C D. \<lbrakk>A = C; \<And>x. x:A \<Longrightarrow> B(x) = D(x)\<rbrakk> \<Longrightarrow> \<Sum>x:A. B(x) = \<Sum>x:C. D(x)" and

  SumI:  "\<And>a b A B. \<lbrakk>a : A; b : B(a)\<rbrakk> \<Longrightarrow> <a,b> : \<Sum>x:A. B(x)" and
  SumIL: "\<And>a b c d A B. \<lbrakk> a = c : A; b = d : B(a)\<rbrakk> \<Longrightarrow> <a,b> = <c,d> : \<Sum>x:A. B(x)" and

  SumE: "\<And>p c A B C. \<lbrakk>p: \<Sum>x:A. B(x); \<And>x y. \<lbrakk>x:A; y:B(x)\<rbrakk> \<Longrightarrow> c(x,y): C(<x,y>)\<rbrakk>
    \<Longrightarrow> split(p, \<lambda>x y. c(x,y)) : C(p)" and

  SumEL: "\<And>p q c d A B C. \<lbrakk>p = q : \<Sum>x:A. B(x);
      \<And>x y. \<lbrakk>x:A; y:B(x)\<rbrakk> \<Longrightarrow> c(x,y)=d(x,y): C(<x,y>)\<rbrakk>
    \<Longrightarrow> split(p, \<lambda>x y. c(x,y)) = split(q, \<lambda>x y. d(x,y)) : C(p)" and

  SumC: "\<And>a b c A B C. \<lbrakk>a: A;  b: B(a); \<And>x y. \<lbrakk>x:A; y:B(x)\<rbrakk> \<Longrightarrow> c(x,y): C(<x,y>)\<rbrakk>
    \<Longrightarrow> split(<a,b>, \<lambda>x y. c(x,y)) = c(a,b) : C(<a,b>)" and

  fst_def:   "\<And>a. fst(a) \<equiv> split(a, \<lambda>x y. x)" and
  snd_def:   "\<And>a. snd(a) \<equiv> split(a, \<lambda>x y. y)" and

  \<comment> \<open>The sum of two types\<close>

  PlusF: "\<And>A B. \<lbrakk>A type; B type\<rbrakk> \<Longrightarrow> A+B type" and
  PlusFL: "\<And>A B C D. \<lbrakk>A = C; B = D\<rbrakk> \<Longrightarrow> A+B = C+D" and

  PlusI_inl: "\<And>a A B. \<lbrakk>a : A; B type\<rbrakk> \<Longrightarrow> inl(a) : A+B" and
  PlusI_inlL: "\<And>a c A B. \<lbrakk>a = c : A; B type\<rbrakk> \<Longrightarrow> inl(a) = inl(c) : A+B" and

  PlusI_inr: "\<And>b A B. \<lbrakk>A type; b : B\<rbrakk> \<Longrightarrow> inr(b) : A+B" and
  PlusI_inrL: "\<And>b d A B. \<lbrakk>A type; b = d : B\<rbrakk> \<Longrightarrow> inr(b) = inr(d) : A+B" and

  PlusE:
    "\<And>p c d A B C. \<lbrakk>p: A+B;
      \<And>x. x:A \<Longrightarrow> c(x): C(inl(x));
      \<And>y. y:B \<Longrightarrow> d(y): C(inr(y)) \<rbrakk> \<Longrightarrow> when(p, \<lambda>x. c(x), \<lambda>y. d(y)) : C(p)" and

  PlusEL:
    "\<And>p q c d e f A B C. \<lbrakk>p = q : A+B;
      \<And>x. x: A \<Longrightarrow> c(x) = e(x) : C(inl(x));
      \<And>y. y: B \<Longrightarrow> d(y) = f(y) : C(inr(y))\<rbrakk>
    \<Longrightarrow> when(p, \<lambda>x. c(x), \<lambda>y. d(y)) = when(q, \<lambda>x. e(x), \<lambda>y. f(y)) : C(p)" and

  PlusC_inl:
    "\<And>a c d A B C. \<lbrakk>a: A;
      \<And>x. x:A \<Longrightarrow> c(x): C(inl(x));
      \<And>y. y:B \<Longrightarrow> d(y): C(inr(y)) \<rbrakk>
    \<Longrightarrow> when(inl(a), \<lambda>x. c(x), \<lambda>y. d(y)) = c(a) : C(inl(a))" and

  PlusC_inr:
    "\<And>b c d A B C. \<lbrakk>b: B;
      \<And>x. x:A \<Longrightarrow> c(x): C(inl(x));
      \<And>y. y:B \<Longrightarrow> d(y): C(inr(y))\<rbrakk>
    \<Longrightarrow> when(inr(b), \<lambda>x. c(x), \<lambda>y. d(y)) = d(b) : C(inr(b))" and

  \<comment> \<open>The type \<open>Eq\<close>\<close>

  EqF: "\<And>a b A. \<lbrakk>A type; a : A; b : A\<rbrakk> \<Longrightarrow> Eq(A,a,b) type" and
  EqFL: "\<And>a b c d A B. \<lbrakk>A = B; a = c : A; b = d : A\<rbrakk> \<Longrightarrow> Eq(A,a,b) = Eq(B,c,d)" and
  EqI: "\<And>a b A. a = b : A \<Longrightarrow> eq : Eq(A,a,b)" and
  EqE: "\<And>p a b A. p : Eq(A,a,b) \<Longrightarrow> a = b : A" and

  \<comment> \<open>By equality of types, can prove \<open>C(p)\<close> from \<open>C(eq)\<close>, an elimination rule\<close>
  EqC: "\<And>p a b A. p : Eq(A,a,b) \<Longrightarrow> p = eq : Eq(A,a,b)" and

  \<comment> \<open>The type \<open>F\<close>\<close>

  FF: "F type" and
  FE: "\<And>p C. \<lbrakk>p: F; C type\<rbrakk> \<Longrightarrow> contr(p) : C" and
  FEL: "\<And>p q C. \<lbrakk>p = q : F; C type\<rbrakk> \<Longrightarrow> contr(p) = contr(q) : C" and

  \<comment> \<open>The type T\<close>
  \<comment> \<open>Martin-Löf's book (page 68) discusses elimination and computation.
    Elimination can be derived by computation and equality of types,
    but with an extra premise \<open>C(x)\<close> type \<open>x:T\<close>.
    Also computation can be derived from elimination.\<close>

  TF: "T type" and
  TI: "tt : T" and
  TE: "\<And>p c C. \<lbrakk>p : T; c : C(tt)\<rbrakk> \<Longrightarrow> c : C(p)" and
  TEL: "\<And>p q c d C. \<lbrakk>p = q : T; c = d : C(tt)\<rbrakk> \<Longrightarrow> c = d : C(p)" and
  TC: "\<And>p. p : T \<Longrightarrow> p = tt : T"

subsection "Tactics and derived rules for Constructive Type Theory"

text \<open>Formation rules.\<close>
lemmas form_rls = NF ProdF SumF PlusF EqF FF TF
  and formL_rls = ProdFL SumFL PlusFL EqFL

text \<open>
  Introduction rules. OMITTED:
  \<^item> \<open>EqI\<close>, because its premise is an \<open>eqelem\<close>, not an \<open>elem\<close>.
\<close>
lemmas intr_rls = NI0 NI_succ ProdI SumI PlusI_inl PlusI_inr TI
  and intrL_rls = NI_succL ProdIL SumIL PlusI_inlL PlusI_inrL

text \<open>
  Elimination rules. OMITTED:
  \<^item> \<open>EqE\<close>, because its conclusion is an \<open>eqelem\<close>, not an \<open>elem\<close>
  \<^item> \<open>TE\<close>, because it does not involve a constructor.
\<close>
lemmas elim_rls = NE ProdE SumE PlusE FE
  and elimL_rls = NEL ProdEL SumEL PlusEL FEL

text \<open>OMITTED: \<open>eqC\<close> are \<open>TC\<close> because they make rewriting loop: \<open>p = un = un = \<dots>\<close>\<close>
lemmas comp_rls = NC0 NC_succ ProdC SumC PlusC_inl PlusC_inr

text \<open>Rules with conclusion \<open>a:A\<close>, an elem judgment.\<close>
lemmas element_rls = intr_rls elim_rls

text \<open>Definitions are (meta)equality axioms.\<close>
lemmas basic_defs = fst_def snd_def

text \<open>Compare with standard version: \<open>B\<close> is applied to UNSIMPLIFIED expression!\<close>
lemma SumIL2: "\<lbrakk>c = a : A; d = b : B(a)\<rbrakk> \<Longrightarrow> <c,d> = <a,b> : Sum(A,B)"
  by (rule sym_elem) (rule SumIL; rule sym_elem)

lemmas intrL2_rls = NI_succL ProdIL SumIL2 PlusI_inlL PlusI_inrL

text \<open>
  Exploit \<open>p:Prod(A,B)\<close> to create the assumption \<open>z:B(a)\<close>.
  A more natural form of product elimination.
\<close>
lemma subst_prodE:
  assumes "p: Prod(A,B)"
    and "a: A"
    and "\<And>z. z: B(a) \<Longrightarrow> c(z): C(z)"
  shows "c(p`a): C(p`a)"
  by (rule assms ProdE)+

subsection \<open>Tactics for type checking\<close>

ML \<open>
local

fun is_rigid_elem \<^Const_>\<open>Elem for a _\<close> = not(is_Var (head_of a))
  | is_rigid_elem \<^Const_>\<open>Eqelem for a _ _\<close> = not(is_Var (head_of a))
  | is_rigid_elem \<^Const_>\<open>Type for a\<close> = not(is_Var (head_of a))
  | is_rigid_elem _ = false

in

(*Try solving a:A or a=b:A by assumption provided a is rigid!*)
fun test_assume_tac ctxt = SUBGOAL (fn (prem, i) =>
  if is_rigid_elem (Logic.strip_assums_concl prem)
  then assume_tac ctxt i else no_tac)

fun ASSUME ctxt tf i = test_assume_tac ctxt i  ORELSE  tf i

end
\<close>

text \<open>
  For simplification: type formation and checking,
  but no equalities between terms.
\<close>
lemmas routine_rls = form_rls formL_rls refl_type element_rls

ML \<open>
fun routine_tac rls ctxt prems =
  ASSUME ctxt (filt_resolve_from_net_tac ctxt 4 (Tactic.build_net (prems @ rls)));

(*Solve all subgoals "A type" using formation rules. *)
val form_net = Tactic.build_net @{thms form_rls};
fun form_tac ctxt =
  REPEAT_FIRST (ASSUME ctxt (filt_resolve_from_net_tac ctxt 1 form_net));

(*Type checking: solve a:A (a rigid, A flexible) by intro and elim rules. *)
fun typechk_tac ctxt thms =
  let val tac =
    filt_resolve_from_net_tac ctxt 3
      (Tactic.build_net (thms @ @{thms form_rls} @ @{thms element_rls}))
  in  REPEAT_FIRST (ASSUME ctxt tac)  end

(*Solve a:A (a flexible, A rigid) by introduction rules.
  Cannot use stringtrees (filt_resolve_tac) since
  goals like ?a:SUM(A,B) have a trivial head-string *)
fun intr_tac ctxt thms =
  let val tac =
    filt_resolve_from_net_tac ctxt 1
      (Tactic.build_net (thms @ @{thms form_rls} @ @{thms intr_rls}))
  in  REPEAT_FIRST (ASSUME ctxt tac)  end

(*Equality proving: solve a=b:A (where a is rigid) by long rules. *)
fun equal_tac ctxt thms =
  REPEAT_FIRST
    (ASSUME ctxt
      (filt_resolve_from_net_tac ctxt 3
        (Tactic.build_net (thms @ @{thms form_rls element_rls intrL_rls elimL_rls refl_elem}))))
\<close>

method_setup form = \<open>Scan.succeed (fn ctxt => SIMPLE_METHOD (form_tac ctxt))\<close>
method_setup typechk = \<open>Attrib.thms >> (fn ths => fn ctxt => SIMPLE_METHOD (typechk_tac ctxt ths))\<close>
method_setup intr = \<open>Attrib.thms >> (fn ths => fn ctxt => SIMPLE_METHOD (intr_tac ctxt ths))\<close>
method_setup equal = \<open>Attrib.thms >> (fn ths => fn ctxt => SIMPLE_METHOD (equal_tac ctxt ths))\<close>

subsection \<open>Simplification\<close>

text \<open>To simplify the type in a goal.\<close>
lemma replace_type: "\<lbrakk>B = A; a : A\<rbrakk> \<Longrightarrow> a : B"
  apply (rule equal_types)
   apply (rule_tac [2] sym_type)
   apply assumption+
  done

text \<open>Simplify the parameter of a unary type operator.\<close>
lemma subst_eqtyparg:
  assumes 1: "a=c : A"
    and 2: "\<And>z. z:A \<Longrightarrow> B(z) type"
  shows "B(a) = B(c)"
  apply (rule subst_typeL)
   apply (rule_tac [2] refl_type)
   apply (rule 1)
  apply (erule 2)
  done

text \<open>Simplification rules for Constructive Type Theory.\<close>
lemmas reduction_rls = comp_rls [THEN trans_elem]

ML \<open>
(*Converts each goal "e : Eq(A,a,b)" into "a=b:A" for simplification.
  Uses other intro rules to avoid changing flexible goals.*)
val eqintr_net = Tactic.build_net @{thms EqI intr_rls}
fun eqintr_tac ctxt =
  REPEAT_FIRST (ASSUME ctxt (filt_resolve_from_net_tac ctxt 1 eqintr_net))

(** Tactics that instantiate CTT-rules.
    Vars in the given terms will be incremented!
    The (rtac EqE i) lets them apply to equality judgments. **)

fun NE_tac ctxt sp i =
  TRY (resolve_tac ctxt @{thms EqE} i) THEN
  Rule_Insts.res_inst_tac ctxt [((("p", 0), Position.none), sp)] [] @{thm NE} i

fun SumE_tac ctxt sp i =
  TRY (resolve_tac ctxt @{thms EqE} i) THEN
  Rule_Insts.res_inst_tac ctxt [((("p", 0), Position.none), sp)] [] @{thm SumE} i

fun PlusE_tac ctxt sp i =
  TRY (resolve_tac ctxt @{thms EqE} i) THEN
  Rule_Insts.res_inst_tac ctxt [((("p", 0), Position.none), sp)] [] @{thm PlusE} i

(** Predicate logic reasoning, WITH THINNING!!  Procedures adapted from NJ. **)

(*Finds f:Prod(A,B) and a:A in the assumptions, concludes there is z:B(a) *)
fun add_mp_tac ctxt i =
  resolve_tac ctxt @{thms subst_prodE} i  THEN  assume_tac ctxt i  THEN  assume_tac ctxt i

(*Finds P\<longrightarrow>Q and P in the assumptions, replaces implication by Q *)
fun mp_tac ctxt i = eresolve_tac ctxt @{thms subst_prodE} i  THEN  assume_tac ctxt i

(*"safe" when regarded as predicate calculus rules*)
val safe_brls = sort (make_ord lessb)
    [ (true, @{thm FE}), (true,asm_rl),
      (false, @{thm ProdI}), (true, @{thm SumE}), (true, @{thm PlusE}) ]

val unsafe_brls =
    [ (false, @{thm PlusI_inl}), (false, @{thm PlusI_inr}), (false, @{thm SumI}),
      (true, @{thm subst_prodE}) ]

(*0 subgoals vs 1 or more*)
val (safe0_brls, safep_brls) =
    List.partition (curry (op =) 0 o subgoals_of_brl) safe_brls

fun safestep_tac ctxt thms i =
    form_tac ctxt ORELSE
    resolve_tac ctxt thms i  ORELSE
    biresolve_tac ctxt safe0_brls i  ORELSE  mp_tac ctxt i  ORELSE
    DETERM (biresolve_tac ctxt safep_brls i)

fun safe_tac ctxt thms i = DEPTH_SOLVE_1 (safestep_tac ctxt thms i)

fun step_tac ctxt thms = safestep_tac ctxt thms  ORELSE'  biresolve_tac ctxt unsafe_brls

(*Fails unless it solves the goal!*)
fun pc_tac ctxt thms = DEPTH_SOLVE_1 o (step_tac ctxt thms)
\<close>

method_setup eqintr = \<open>Scan.succeed (SIMPLE_METHOD o eqintr_tac)\<close>
method_setup NE = \<open>
  Scan.lift Parse.embedded_inner_syntax >> (fn s => fn ctxt => SIMPLE_METHOD' (NE_tac ctxt s))
\<close>
method_setup pc = \<open>Attrib.thms >> (fn ths => fn ctxt => SIMPLE_METHOD' (pc_tac ctxt ths))\<close>
method_setup add_mp = \<open>Scan.succeed (SIMPLE_METHOD' o add_mp_tac)\<close>

ML_file \<open>rew.ML\<close>
method_setup rew = \<open>Attrib.thms >> (fn ths => fn ctxt => SIMPLE_METHOD (rew_tac ctxt ths))\<close>
method_setup hyp_rew = \<open>Attrib.thms >> (fn ths => fn ctxt => SIMPLE_METHOD (hyp_rew_tac ctxt ths))\<close>

subsection \<open>The elimination rules for fst/snd\<close>

lemma SumE_fst: "p : Sum(A,B) \<Longrightarrow> fst(p) : A"
  unfolding basic_defs
  apply (erule SumE)
  apply assumption
  done

text \<open>The first premise must be \<open>p:Sum(A,B)\<close>!!.\<close>
lemma SumE_snd:
  assumes major: "p: Sum(A,B)"
    and "A type"
    and "\<And>x. x:A \<Longrightarrow> B(x) type"
  shows "snd(p) : B(fst(p))"
  unfolding basic_defs
  apply (rule major [THEN SumE])
  apply (rule SumC [THEN subst_eqtyparg, THEN replace_type])
      apply (typechk assms)
  done

section \<open>The two-element type (booleans and conditionals)\<close>

definition Bool :: "t"
  where "Bool \<equiv> T+T"

definition true :: "i"
  where "true \<equiv> inl(tt)"

definition false :: "i"
  where "false \<equiv> inr(tt)"

definition cond :: "[i,i,i]\<Rightarrow>i"
  where "cond(a,b,c) \<equiv> when(a, \<lambda>_. b, \<lambda>_. c)"

lemmas bool_defs = Bool_def true_def false_def cond_def

subsection \<open>Derivation of rules for the type \<open>Bool\<close>\<close>

text \<open>Formation rule.\<close>
lemma boolF: "Bool type"
  unfolding bool_defs by typechk

text \<open>Introduction rules for \<open>true\<close>, \<open>false\<close>.\<close>

lemma boolI_true: "true : Bool"
  unfolding bool_defs by typechk

lemma boolI_false: "false : Bool"
  unfolding bool_defs by typechk

text \<open>Elimination rule: typing of \<open>cond\<close>.\<close>
lemma boolE: "\<lbrakk>p:Bool; a : C(true); b : C(false)\<rbrakk> \<Longrightarrow> cond(p,a,b) : C(p)"
  unfolding bool_defs
  apply (typechk; erule TE)
   apply typechk
  done

lemma boolEL: "\<lbrakk>p = q : Bool; a = c : C(true); b = d : C(false)\<rbrakk>
  \<Longrightarrow> cond(p,a,b) = cond(q,c,d) : C(p)"
  unfolding bool_defs
  apply (rule PlusEL)
    apply (erule asm_rl refl_elem [THEN TEL])+
  done

text \<open>Computation rules for \<open>true\<close>, \<open>false\<close>.\<close>

lemma boolC_true: "\<lbrakk>a : C(true); b : C(false)\<rbrakk> \<Longrightarrow> cond(true,a,b) = a : C(true)"
  unfolding bool_defs
  apply (rule comp_rls)
    apply typechk
   apply (erule_tac [!] TE)
   apply typechk
  done

lemma boolC_false: "\<lbrakk>a : C(true); b : C(false)\<rbrakk> \<Longrightarrow> cond(false,a,b) = b : C(false)"
  unfolding bool_defs
  apply (rule comp_rls)
    apply typechk
   apply (erule_tac [!] TE)
   apply typechk
  done

section \<open>Elementary arithmetic\<close>

subsection \<open>Arithmetic operators and their definitions\<close>

definition add :: "[i,i]\<Rightarrow>i"   (infixr "#+" 65)
  where "a#+b \<equiv> rec(a, b, \<lambda>u v. succ(v))"

definition diff :: "[i,i]\<Rightarrow>i"   (infixr "-" 65)
  where "a-b \<equiv> rec(b, a, \<lambda>u v. rec(v, 0, \<lambda>x y. x))"

definition absdiff :: "[i,i]\<Rightarrow>i"   (infixr "|-|" 65)
  where "a|-|b \<equiv> (a-b) #+ (b-a)"

definition mult :: "[i,i]\<Rightarrow>i"   (infixr "#*" 70)
  where "a#*b \<equiv> rec(a, 0, \<lambda>u v. b #+ v)"

definition mod :: "[i,i]\<Rightarrow>i"   (infixr "mod" 70)
  where "a mod b \<equiv> rec(a, 0, \<lambda>u v. rec(succ(v) |-| b, 0, \<lambda>x y. succ(v)))"

definition div :: "[i,i]\<Rightarrow>i"   (infixr "div" 70)
  where "a div b \<equiv> rec(a, 0, \<lambda>u v. rec(succ(u) mod b, succ(v), \<lambda>x y. v))"

lemmas arith_defs = add_def diff_def absdiff_def mult_def mod_def div_def

subsection \<open>Proofs about elementary arithmetic: addition, multiplication, etc.\<close>

subsubsection \<open>Addition\<close>

text \<open>Typing of \<open>add\<close>: short and long versions.\<close>

lemma add_typing: "\<lbrakk>a:N; b:N\<rbrakk> \<Longrightarrow> a #+ b : N"
  unfolding arith_defs by typechk

lemma add_typingL: "\<lbrakk>a = c:N; b = d:N\<rbrakk> \<Longrightarrow> a #+ b = c #+ d : N"
  unfolding arith_defs by equal

text \<open>Computation for \<open>add\<close>: 0 and successor cases.\<close>

lemma addC0: "b:N \<Longrightarrow> 0 #+ b = b : N"
  unfolding arith_defs by rew

lemma addC_succ: "\<lbrakk>a:N; b:N\<rbrakk> \<Longrightarrow> succ(a) #+ b = succ(a #+ b) : N"
  unfolding arith_defs by rew

subsubsection \<open>Multiplication\<close>

text \<open>Typing of \<open>mult\<close>: short and long versions.\<close>

lemma mult_typing: "\<lbrakk>a:N; b:N\<rbrakk> \<Longrightarrow> a #* b : N"
  unfolding arith_defs by (typechk add_typing)

lemma mult_typingL: "\<lbrakk>a = c:N; b = d:N\<rbrakk> \<Longrightarrow> a #* b = c #* d : N"
  unfolding arith_defs by (equal add_typingL)

text \<open>Computation for \<open>mult\<close>: 0 and successor cases.\<close>

lemma multC0: "b:N \<Longrightarrow> 0 #* b = 0 : N"
  unfolding arith_defs by rew

lemma multC_succ: "\<lbrakk>a:N; b:N\<rbrakk> \<Longrightarrow> succ(a) #* b = b #+ (a #* b) : N"
  unfolding arith_defs by rew

subsubsection \<open>Difference\<close>

text \<open>Typing of difference.\<close>

lemma diff_typing: "\<lbrakk>a:N; b:N\<rbrakk> \<Longrightarrow> a - b : N"
  unfolding arith_defs by typechk

lemma diff_typingL: "\<lbrakk>a = c:N; b = d:N\<rbrakk> \<Longrightarrow> a - b = c - d : N"
  unfolding arith_defs by equal

text \<open>Computation for difference: 0 and successor cases.\<close>

lemma diffC0: "a:N \<Longrightarrow> a - 0 = a : N"
  unfolding arith_defs by rew

text \<open>Note: \<open>rec(a, 0, \<lambda>z w.z)\<close> is \<open>pred(a).\<close>\<close>

lemma diff_0_eq_0: "b:N \<Longrightarrow> 0 - b = 0 : N"
  unfolding arith_defs
  by (NE b) hyp_rew

text \<open>
  Essential to simplify FIRST!!  (Else we get a critical pair)
  \<open>succ(a) - succ(b)\<close> rewrites to \<open>pred(succ(a) - b)\<close>.
\<close>
lemma diff_succ_succ: "\<lbrakk>a:N; b:N\<rbrakk> \<Longrightarrow> succ(a) - succ(b) = a - b : N"
  unfolding arith_defs
  apply hyp_rew
  apply (NE b)
    apply hyp_rew
  done

subsection \<open>Simplification\<close>

lemmas arith_typing_rls = add_typing mult_typing diff_typing
  and arith_congr_rls = add_typingL mult_typingL diff_typingL

lemmas congr_rls = arith_congr_rls intrL2_rls elimL_rls

lemmas arithC_rls =
  addC0 addC_succ
  multC0 multC_succ
  diffC0 diff_0_eq_0 diff_succ_succ

ML \<open>
  structure Arith_simp = TSimpFun(
    val refl = @{thm refl_elem}
    val sym = @{thm sym_elem}
    val trans = @{thm trans_elem}
    val refl_red = @{thm refl_red}
    val trans_red = @{thm trans_red}
    val red_if_equal = @{thm red_if_equal}
    val default_rls = @{thms arithC_rls comp_rls}
    val routine_tac = routine_tac @{thms arith_typing_rls routine_rls}
  )

  fun arith_rew_tac ctxt prems =
    make_rew_tac ctxt (Arith_simp.norm_tac ctxt (@{thms congr_rls}, prems))

  fun hyp_arith_rew_tac ctxt prems =
    make_rew_tac ctxt
      (Arith_simp.cond_norm_tac ctxt (prove_cond_tac ctxt, @{thms congr_rls}, prems))
\<close>

method_setup arith_rew = \<open>
  Attrib.thms >> (fn ths => fn ctxt => SIMPLE_METHOD (arith_rew_tac ctxt ths))
\<close>

method_setup hyp_arith_rew = \<open>
  Attrib.thms >> (fn ths => fn ctxt => SIMPLE_METHOD (hyp_arith_rew_tac ctxt ths))
\<close>

subsection \<open>Addition\<close>

text \<open>Associative law for addition.\<close>

text \<open>Commutative law for addition.  Can be proved using three inductions.
  Must simplify after first induction!  Orientation of rewrites is delicate.\<close>
lemma add_commute: "\<lbrakk>a:N; b:N\<rbrakk> \<Longrightarrow> a #+ b = b #+ a : N"
  apply (NE a)
    apply hyp_arith_rew
   apply (rule sym_elem)
   prefer 2
   apply (NE b)
     prefer 4
     apply (NE b)
       apply hyp_arith_rew
  done

subsection \<open>Multiplication\<close>

text \<open>Right annihilation in product.\<close>
lemma mult_0_right: "a:N \<Longrightarrow> a #* 0 = 0 : N"
  apply (NE a)
    apply hyp_arith_rew
  done

text \<open>Right successor law for multiplication.\<close>
lemma mult_succ_right: "\<lbrakk>a:N; b:N\<rbrakk> \<Longrightarrow> a #* succ(b) = a #+ (a #* b) : N"
  apply (NE a)
    apply (hyp_arith_rew add_assoc [THEN sym_elem])
  apply (assumption | rule add_commute mult_typingL add_typingL intrL_rls refl_elem)+
  done

text \<open>Commutative law for multiplication.\<close>
lemma mult_commute: "\<lbrakk>a:N; b:N\<rbrakk> \<Longrightarrow> a #* b = b #* a : N"
  apply (NE a)
    apply (hyp_arith_rew mult_0_right mult_succ_right)
  done

text \<open>Addition distributes over multiplication.\<close>
lemma add_mult_distrib: "\<lbrakk>a:N; b:N; c:N\<rbrakk> \<Longrightarrow> (a #+ b) #* c = (a #* c) #+ (b #* c) : N"
  apply (NE a)
    apply (hyp_arith_rew add_assoc [THEN sym_elem])
  done

text \<open>Associative law for multiplication.\<close>
lemma mult_assoc: "\<lbrakk>a:N; b:N; c:N\<rbrakk> \<Longrightarrow> (a #* b) #* c = a #* (b #* c) : N"
  apply (NE a)
    apply (hyp_arith_rew add_mult_distrib)
  done

subsection \<open>Difference\<close>

text \<open>
  Difference on natural numbers, without negative numbers
  \<^item> \<open>a - b = 0\<close>  iff  \<open>a \<le> b\<close>
  \<^item> \<open>a - b = succ(c)\<close> iff \<open>a > b\<close>
\<close>

lemma diff_self_eq_0: "a:N \<Longrightarrow> a - a = 0 : N"
  apply (NE a)
    apply hyp_arith_rew
  done

lemma add_0_right: "\<lbrakk>c : N; 0 : N; c : N\<rbrakk> \<Longrightarrow> c #+ 0 = c : N"
  by (rule addC0 [THEN [3] add_commute [THEN trans_elem]])

text \<open>
  Addition is the inverse of subtraction: if \<open>b \<le> x\<close> then \<open>b #+ (x - b) = x\<close>.
  An example of induction over a quantified formula (a product).
  Uses rewriting with a quantified, implicative inductive hypothesis.
\<close>
schematic_goal add_diff_inverse_lemma:
  "b:N \<Longrightarrow> ?a : \<Prod>x:N. Eq(N, b-x, 0) \<longrightarrow> Eq(N, b #+ (x-b), x)"
  apply (NE b)
    \<comment> \<open>strip one "universal quantifier" but not the "implication"\<close>
    apply (rule_tac [3] intr_rls)
    \<comment> \<open>case analysis on \<open>x\<close> in \<open>succ(u) \<le> x \<longrightarrow> succ(u) #+ (x - succ(u)) = x\<close>\<close>
     prefer 4
     apply (NE x)
       apply assumption
    \<comment> \<open>Prepare for simplification of types -- the antecedent \<open>succ(u) \<le> x\<close>\<close>
      apply (rule_tac [2] replace_type)
       apply (rule_tac [1] replace_type)
        apply arith_rew
    \<comment> \<open>Solves first 0 goal, simplifies others.  Two sugbgoals remain.
    Both follow by rewriting, (2) using quantified induction hyp.\<close>
   apply intr \<comment> \<open>strips remaining \<open>\<Prod>\<close>s\<close>
    apply (hyp_arith_rew add_0_right)
  apply assumption
  done

text \<open>
  Version of above with premise \<open>b - a = 0\<close> i.e. \<open>a \<ge> b\<close>.
  Using @{thm ProdE} does not work -- for \<open>?B(?a)\<close> is ambiguous.
  Instead, @{thm add_diff_inverse_lemma} states the desired induction scheme;
  the use of \<open>THEN\<close> below instantiates Vars in @{thm ProdE} automatically.
\<close>
lemma add_diff_inverse: "\<lbrakk>a:N; b:N; b - a = 0 : N\<rbrakk> \<Longrightarrow> b #+ (a-b) = a : N"
  apply (rule EqE)
  apply (rule add_diff_inverse_lemma [THEN ProdE, THEN ProdE])
    apply (assumption | rule EqI)+
  done

subsection \<open>Absolute difference\<close>

text \<open>Typing of absolute difference: short and long versions.\<close>

lemma absdiff_typing: "\<lbrakk>a:N; b:N\<rbrakk> \<Longrightarrow> a |-| b : N"
  unfolding arith_defs by typechk

lemma absdiff_typingL: "\<lbrakk>a = c:N; b = d:N\<rbrakk> \<Longrightarrow> a |-| b = c |-| d : N"
  unfolding arith_defs by equal

lemma absdiff_self_eq_0: "a:N \<Longrightarrow> a |-| a = 0 : N"
  unfolding absdiff_def by (arith_rew diff_self_eq_0)

lemma absdiffC0: "a:N \<Longrightarrow> 0 |-| a = a : N"
  unfolding absdiff_def by hyp_arith_rew

lemma absdiff_succ_succ: "\<lbrakk>a:N; b:N\<rbrakk> \<Longrightarrow> succ(a) |-| succ(b)  =  a |-| b : N"
  unfolding absdiff_def by hyp_arith_rew

text \<open>Note how easy using commutative laws can be?  ...not always...\<close>
lemma absdiff_commute: "\<lbrakk>a:N; b:N\<rbrakk> \<Longrightarrow> a |-| b = b |-| a : N"
  unfolding absdiff_def
  by (rule add_commute) (typechk diff_typing)

text \<open>If \<open>a + b = 0\<close> then \<open>a = 0\<close>. Surprisingly tedious.\<close>
schematic_goal add_eq0_lemma: "\<lbrakk>a:N; b:N\<rbrakk> \<Longrightarrow> ?c : Eq(N,a#+b,0) \<longrightarrow> Eq(N,a,0)"
  apply (NE a)
    apply (rule_tac [3] replace_type)
     apply arith_rew
  apply intr  \<comment> \<open>strips remaining \<open>\<Prod>\<close>s\<close>
   apply (rule_tac [2] zero_ne_succ [THEN FE])
     apply (erule_tac [3] EqE [THEN sym_elem])
    apply (typechk add_typing)
  done

text \<open>
  Version of above with the premise \<open>a + b = 0\<close>.
  Again, resolution instantiates variables in @{thm ProdE}.
\<close>
lemma add_eq0: "\<lbrakk>a:N; b:N; a #+ b = 0 : N\<rbrakk> \<Longrightarrow> a = 0 : N"
  apply (rule EqE)
  apply (rule add_eq0_lemma [THEN ProdE])
    apply (rule_tac [3] EqI)
    apply typechk
  done

text \<open>Here is a lemma to infer \<open>a - b = 0\<close> and \<open>b - a = 0\<close> from \<open>a |-| b = 0\<close>, below.\<close>
schematic_goal absdiff_eq0_lem:
  "\<lbrakk>a:N; b:N; a |-| b = 0 : N\<rbrakk> \<Longrightarrow> ?a : Eq(N, a-b, 0) \<times> Eq(N, b-a, 0)"
  unfolding absdiff_def
  apply intr
   apply eqintr
   apply (rule_tac [2] add_eq0)
     apply (rule add_eq0)
       apply (rule_tac [6] add_commute [THEN trans_elem])
         apply (typechk diff_typing)
  done

text \<open>If \<open>a |-| b = 0\<close> then \<open>a = b\<close>
  proof: \<open>a - b = 0\<close> and \<open>b - a = 0\<close>, so \<open>b = a + (b - a) = a + 0 = a\<close>.
\<close>
lemma absdiff_eq0: "\<lbrakk>a |-| b = 0 : N; a:N; b:N\<rbrakk> \<Longrightarrow> a = b : N"
  apply (rule EqE)
  apply (rule absdiff_eq0_lem [THEN SumE])
     apply eqintr
  apply (rule add_diff_inverse [THEN sym_elem, THEN trans_elem])
     apply (erule_tac [3] EqE)
    apply (hyp_arith_rew add_0_right)
  done

subsection \<open>Remainder and Quotient\<close>

text \<open>Typing of remainder: short and long versions.\<close>

lemma mod_typing: "\<lbrakk>a:N; b:N\<rbrakk> \<Longrightarrow> a mod b : N"
  unfolding mod_def by (typechk absdiff_typing)

lemma mod_typingL: "\<lbrakk>a = c:N; b = d:N\<rbrakk> \<Longrightarrow> a mod b = c mod d : N"
  unfolding mod_def by (equal absdiff_typingL)

text \<open>Computation for \<open>mod\<close>: 0 and successor cases.\<close>

lemma modC0: "b:N \<Longrightarrow> 0 mod b = 0 : N"
  unfolding mod_def by (rew absdiff_typing)

lemma modC_succ: "\<lbrakk>a:N; b:N\<rbrakk> \<Longrightarrow>
  succ(a) mod b = rec(succ(a mod b) |-| b, 0, \<lambda>x y. succ(a mod b)) : N"
  unfolding mod_def by (rew absdiff_typing)

text \<open>Typing of quotient: short and long versions.\<close>

lemma div_typing: "\<lbrakk>a:N; b:N\<rbrakk> \<Longrightarrow> a div b : N"
  unfolding div_def by (typechk absdiff_typing mod_typing)

lemma div_typingL: "\<lbrakk>a = c:N; b = d:N\<rbrakk> \<Longrightarrow> a div b = c div d : N"
  unfolding div_def by (equal absdiff_typingL mod_typingL)

lemmas div_typing_rls = mod_typing div_typing absdiff_typing

text \<open>Computation for quotient: 0 and successor cases.\<close>

lemma divC0: "b:N \<Longrightarrow> 0 div b = 0 : N"
  unfolding div_def by (rew mod_typing absdiff_typing)

lemma divC_succ: "\<lbrakk>a:N; b:N\<rbrakk> \<Longrightarrow>
  succ(a) div b = rec(succ(a) mod b, succ(a div b), \<lambda>x y. a div b) : N"
  unfolding div_def by (rew mod_typing)

text \<open>Version of above with same condition as the \<open>mod\<close> one.\<close>
lemma divC_succ2: "\<lbrakk>a:N; b:N\<rbrakk> \<Longrightarrow>
  succ(a) div b =rec(succ(a mod b) |-| b, succ(a div b), \<lambda>x y. a div b) : N"
  apply (rule divC_succ [THEN trans_elem])
    apply (rew div_typing_rls modC_succ)
  apply (NE "succ (a mod b) |-|b")
    apply (rew mod_typing div_typing absdiff_typing)
  done

text \<open>For case analysis on whether a number is 0 or a successor.\<close>
lemma iszero_decidable: "a:N \<Longrightarrow> rec(a, inl(eq), \<lambda>ka kb. inr(<ka, eq>)) :
  Eq(N,a,0) + (\<Sum>x:N. Eq(N,a, succ(x)))"
  apply (NE a)
    apply (rule_tac [3] PlusI_inr)
     apply (rule_tac [2] PlusI_inl)
      apply eqintr
     apply equal
  done

text \<open>Main Result. Holds when \<open>b\<close> is 0 since \<open>a mod 0 = a\<close> and \<open>a div 0 = 0\<close>.\<close>
lemma mod_div_equality: "\<lbrakk>a:N; b:N\<rbrakk> \<Longrightarrow> a mod b #+ (a div b) #* b = a : N"
  apply (NE a)
    apply (arith_rew div_typing_rls modC0 modC_succ divC0 divC_succ2)
  apply (rule EqE)
    \<comment> \<open>case analysis on \<open>succ(u mod b) |-| b\<close>\<close>
  apply (rule_tac a1 = "succ (u mod b) |-| b" in iszero_decidable [THEN PlusE])
    apply (erule_tac [3] SumE)
    apply (hyp_arith_rew div_typing_rls modC0 modC_succ divC0 divC_succ2)
    \<comment> \<open>Replace one occurrence of \<open>b\<close> by \<open>succ(u mod b)\<close>. Clumsy!\<close>
  apply (rule add_typingL [THEN trans_elem])
    apply (erule EqE [THEN absdiff_eq0, THEN sym_elem])
     apply (rule_tac [3] refl_elem)
     apply (hyp_arith_rew div_typing_rls)
  done

end


(*
 * Copyright 2020, Data61, CSIRO (ABN 41 687 119 230)
 *
 * SPDX-License-Identifier: BSD-2-Clause
 *)

(* Title: Adaptation of example from HOL/Hoare/Separation
   Author: Gerwin Klein, 2012
   Maintainers: Gerwin Klein <kleing at cse.unsw.edu.au>
                Rafal Kolanski <rafal.kolanski at nicta.com.au>
*)

chapter "Example from HOL/Hoare/Separation"

theory Simple_Separation_Example
imports
  "HOL-Hoare.Hoare_Logic_Abort"
  "../Sep_Heap_Instance"
  "../Sep_Tactics"
begin

declare [[syntax_ambiguity_warning = false]]

type_synonym heap = "(nat \<Rightarrow> nat option)"

(* This syntax isn't ideal, but this is what is used in the original *)
definition maps_to:: "nat \<Rightarrow> nat \<Rightarrow> heap \<Rightarrow> bool" ("_ \<mapsto> _" [56,51] 56)
  where "x \<mapsto> y \<equiv> \<lambda>h. h = [x \<mapsto> y]"

(* If you don't mind syntax ambiguity: *)
notation pred_ex  (binder "\<exists>" 10)

(* could be generated automatically *)
definition maps_to_ex :: "nat \<Rightarrow> heap \<Rightarrow> bool" ("_ \<mapsto> -" [56] 56)
  where "x \<mapsto> - \<equiv> \<exists>y. x \<mapsto> y"

(* could be generated automatically *)
lemma maps_to_maps_to_ex [elim!]:
  "(p \<mapsto> v) s \<Longrightarrow> (p \<mapsto> -) s"
  by (auto simp: maps_to_ex_def)

(* The basic properties of maps_to: *)
lemma maps_to_write:
  "(p \<mapsto> - ** P) H \<Longrightarrow> (p \<mapsto> v ** P) (H (p \<mapsto> v))"
  apply (clarsimp simp: sep_conj_def maps_to_def maps_to_ex_def split: option.splits)
  apply (rule_tac x=y in exI)
  apply (auto simp: sep_disj_fun_def map_convs map_add_def split: option.splits)
  done

lemma points_to:
  "(p \<mapsto> v ** P) H \<Longrightarrow> the (H p) = v"
  by (auto elim!: sep_conjE
           simp: sep_disj_fun_def maps_to_def map_convs map_add_def
           split: option.splits)

(* This differs from the original and uses separation logic for the definition. *)
primrec
  list :: "nat \<Rightarrow> nat list \<Rightarrow> heap \<Rightarrow> bool"
where
  "list i [] = (\<langle>i=0\<rangle> and \<box>)"
| "list i (x#xs) = (\<langle>i=x \<and> i\<noteq>0\<rangle> and (EXS j. i \<mapsto> j ** list j xs))"

lemma list_empty [simp]:
  shows "list 0 xs = (\<lambda>s. xs = [] \<and> \<box> s)"
  by (cases xs) auto

(* The examples from Hoare/Separation.thy *)
lemma "VARS x y z w h
 {(x \<mapsto> y ** z \<mapsto> w) h}
 SKIP
 {x \<noteq> z}"
  apply vcg
  apply(auto elim!: sep_conjE simp: maps_to_def sep_disj_fun_def domain_conv)
done

lemma "VARS H x y z w
 {(P ** Q) H}
 SKIP
 {(Q ** P) H}"
  apply vcg
  apply(simp add: sep_conj_commute)
done

lemma "VARS H
 {p\<noteq>0 \<and> (p \<mapsto> - ** list q qs) H}
 H := H(p \<mapsto> q)
 {list p (p#qs) H}"
  apply vcg
  apply (auto intro: maps_to_write)
done

text \<open>First a proof without using tactics\<close>
lemma "VARS H p q r
  {(list p Ps ** list q Qs) H}
  WHILE p \<noteq> 0
  INV {\<exists>ps qs. (list p ps ** list q qs) H \<and> rev ps @ qs = rev Ps @ Qs}
  DO r := p; p := the(H p); H := H(r \<mapsto> q); q := r OD
  {list q (rev Ps @ Qs) H}"
  apply vcg
    apply fastforce
   apply clarsimp
   apply (case_tac ps, simp)
   apply (rename_tac p ps')
   apply (rule_tac x = "ps'" in exI)
   apply (rule_tac x = "p # qs" in exI)
   apply clarsimp
   apply (clarsimp simp: sep_conj_exists sep_conj_ac)
   apply (rule_tac x = "q" in exI)
   thm points_to
   apply (subst (asm) sep_conj_ac)
   apply (subst (asm) sep_conj_commute)
   apply (simp add: sep_conj_assoc)
   apply (frule points_to)
   apply simp
   thm maps_to_write
   apply (subst sep_conj_assoc[symmetric])
   apply (subst sep_conj_commute)
   apply (simp add: sep_conj_assoc)
   apply (rule maps_to_write)
   thm maps_to_maps_to_ex
   apply (drule sep_conj_impl1[rotated])
    apply (erule maps_to_maps_to_ex)
   apply (rule sep_conj_impl1[rotated])
    apply (subst sep_conj_ac, assumption)
   apply assumption
  apply clarsimp
  done

text \<open>Now with tactics\<close>
lemma "VARS H p q r
  {(list p Ps ** list q Qs) H}
  WHILE p \<noteq> 0
  INV {\<exists>ps qs. (list p ps ** list q qs) H \<and> rev ps @ qs = rev Ps @ Qs}
  DO r := p; p := the(H p); H := H(r \<mapsto> q); q := r OD
  {list q (rev Ps @ Qs) H}"
  apply vcg
    apply fastforce
   apply clarsimp
   apply (case_tac ps, simp)
   apply (rename_tac p ps')
   apply (clarsimp simp: sep_conj_exists sep_conj_ac)
   apply (subst points_to, sep_solve)
   apply (rule_tac x = "ps'" in exI)
   apply (rule_tac x = "p # qs" in exI)
   apply (simp add: sep_conj_exists sep_conj_ac)
   apply (rule exI)
   apply (sep_rule (direct) maps_to_write) \<comment> \<open>note: demonstrates computation\<close>
   apply (sep_solve add: maps_to_maps_to_ex)
  apply clarsimp
  done

end