(* License: LGPL *)
(* Author: Julian Parsert *)

theory PMF_Composition
  imports
    "HOL-Probability.Probability"
begin

section \<open> Composition of Probability Mass functions \<close>

definition mix_pmf :: "real \<Rightarrow> 'a pmf \<Rightarrow> 'a pmf \<Rightarrow> 'a pmf" where
  "mix_pmf \<alpha> p q = (bernoulli_pmf \<alpha>)\<bind> (\<lambda>X. if X then p else q)"

lemma pmf_mix: "a \<in> {0..1} \<Longrightarrow> pmf (mix_pmf a p q) x = a * pmf p x + (1 - a) * pmf q x"
  by (simp add: mix_pmf_def pmf_bind)

lemma pmf_mix_deeper: "a \<in> {0..1} \<Longrightarrow> pmf (mix_pmf a p q) x = a * pmf p x + pmf q x - a * pmf q x"
  by (simp add: left_diff_distrib' pmf_mix)

lemma bernoulli_pmf_0 [simp]: "bernoulli_pmf 0 = return_pmf False"
  by (intro pmf_eqI) (auto simp: bernoulli_pmf.rep_eq)

lemma bernoulli_pmf_1 [simp]: "bernoulli_pmf 1 = return_pmf True"
  by (intro pmf_eqI) (auto simp: bernoulli_pmf.rep_eq)

lemma pmf_mix_0 [simp]: "mix_pmf 0 p q = q"
  by (simp add: mix_pmf_def bind_return_pmf)

lemma pmf_mix_1 [simp]: "mix_pmf 1 p q = p"
  by (simp add: mix_pmf_def bind_return_pmf)

lemma set_pmf_mix: "a \<in> {0<..<1} \<Longrightarrow> set_pmf (mix_pmf a p q) = set_pmf p \<union> set_pmf q"
  by (auto simp add: mix_pmf_def split: if_splits)

lemma set_pmf_mix_eq: "a \<in> {0..1} \<Longrightarrow> mix_pmf a p p = p"
  by (simp add: mix_pmf_def)

lemma pmf_equiv_intro[intro]:
  assumes "\<And>e. e \<in> set_pmf p \<Longrightarrow> pmf p e = pmf q e"
  assumes "\<And>e. e \<in> set_pmf q \<Longrightarrow> pmf q e = pmf p e"
  shows "p = q"
  by (metis assms(2) less_irrefl pmf_neq_exists_less pmf_not_neg set_pmf_iff)

lemma pmf_equiv_intro1[intro]:
  assumes "\<And>e. e \<in> set_pmf p \<Longrightarrow> pmf p e = pmf q e"
  shows "p = q"
  by (standard, auto simp: assms, metis assms set_pmf_iff assms
      linorder_not_le order_refl pmf_neq_exists_less pmf_not_neg set_pmf_iff)

lemma pmf_inverse_switch_eqals:
  assumes "a \<in> {0..1}"
  shows "mix_pmf a p q = mix_pmf (1-a) q p"
proof -
  have fst: "\<forall>x \<in> set_pmf p. pmf (mix_pmf a p q) x = pmf (mix_pmf (1-a) q p) x"
  proof
    fix x
    assume "x \<in> set_pmf p"
    have "pmf (mix_pmf a p q) x = a * pmf p x + (1 - a) * pmf q x"
      using pmf_mix[of a p q x] assms by blast
    also have "... = a * pmf p x +  pmf q x - a * pmf q x"
      by (simp add: left_diff_distrib)
    from pmf_mix[of "1-a" q p x] assms
    have "pmf (mix_pmf (1 - a) q p) x = (1 - a) * pmf q x + (1 - (1 - a)) * pmf p x"
      by auto
    then show "pmf (mix_pmf a p q) x = pmf (mix_pmf (1 - a) q p) x"
      using calculation by auto
  qed
  have "\<forall>x \<in> set_pmf q. pmf (mix_pmf a p q) x =  pmf (mix_pmf (1-a) q p) x"
  proof
    fix x
    assume "x \<in> set_pmf q"
    have "pmf (mix_pmf a p q) x = a * pmf p x + (1 - a) * pmf q x"
      using pmf_mix[of a p q x] assms by blast
    also have "... = a * pmf p x +  pmf q x - a * pmf q x"
      by (simp add: left_diff_distrib)
    from pmf_mix[of "1-a" q p x] assms
    show "pmf (mix_pmf a p q) x = pmf (mix_pmf (1 - a) q p) x"
      using calculation by auto
  qed
  then have "\<forall>x \<in> set_pmf (mix_pmf a p q). pmf (mix_pmf a p q) x =  pmf (mix_pmf (1-a) q p) x"
    by (metis (no_types) fst add_0_left assms mult_eq_0_iff pmf_mix set_pmf_iff)
  thus ?thesis
    by (simp add: pmf_equiv_intro1)
qed

lemma mix_pmf_comp_left_div:
  assumes "\<alpha> \<in> {0..(1::real)}"
    and "\<beta> \<in> {0..(1::real)}"
  assumes "\<alpha> > \<beta>"
  shows "pmf (mix_pmf (\<beta>/\<alpha>) (mix_pmf \<alpha> p q) q) e = \<beta> * pmf p e + pmf q e - \<beta> * pmf q e"
proof-
  let ?l = "(mix_pmf (\<beta>/\<alpha>) (mix_pmf \<alpha> p q) q)"
  have fst: "pmf ?l e = (\<beta>/\<alpha>) * pmf (mix_pmf \<alpha> p q) e + (1-\<beta>/\<alpha>) * pmf q e"
    by (meson assms(1) assms(2) assms(3) atLeastAtMost_iff less_divide_eq_1
        less_eq_real_def not_less pmf_mix zero_le_divide_iff)
  then have "pmf (mix_pmf \<alpha> p q) e = \<alpha> * pmf p e + (1 - \<alpha>) * pmf q e"
    using pmf_mix[of "\<alpha>" p q] assms(2) assms(3) assms(1) by blast
  have "pmf ?l e = (\<beta>/\<alpha>) * (\<alpha> * pmf p e + (1 - \<alpha>) * pmf q e) + (1-\<beta>/\<alpha>) * pmf q e"
    using fst assms(1) pmf_mix by fastforce
  then have "pmf ?l e = ((\<beta>/\<alpha>) *\<alpha> * pmf p e + (\<beta>/\<alpha>) *(1 - \<alpha>) * pmf q e) + (1-\<beta>/\<alpha>) * pmf q e"
    using fst assms(1) by (metis  mult.assoc  ring_class.ring_distribs(1))
  then have *: "pmf ?l e = (\<beta> * pmf p e + (\<beta>/\<alpha>) *(1 - \<alpha>) * pmf q e) + (1-\<beta>/\<alpha>) * pmf q e"
    using fst assms(1) assms(2) assms(3) by auto
  then have "pmf ?l e = (\<beta> * pmf p e + ((\<beta>/\<alpha>) - (\<beta>/\<alpha>)*\<alpha>) * pmf q e) + (1-\<beta>/\<alpha>) * pmf q e"
    using fst assms(1) assms(2) assms(3) by (simp add: * diff_divide_distrib right_diff_distrib')
  then have "pmf ?l e = (\<beta> * pmf p e + ((\<beta>/\<alpha>) - \<beta>) * pmf q e) + (1-\<beta>/\<alpha>) * pmf q e"
    using fst assms(1) assms(2) assms(3) by auto
  then have "pmf ?l e = (\<beta> * pmf p e + (\<beta>/\<alpha>) * pmf q e - \<beta> * pmf q e) + 1* pmf q e-\<beta>/\<alpha>* pmf q e"
    by (simp add: left_diff_distrib)
  thus ?thesis
    by linarith
qed

lemma mix_pmf_comp_with_dif_equiv:
  assumes "\<alpha> \<in> {0..(1::real)}"
    and "\<beta> \<in> {0..(1::real)}"
  assumes "\<alpha> > \<beta>"
  shows "mix_pmf (\<beta>/\<alpha>) (mix_pmf \<alpha> p q) q = mix_pmf \<beta> p q" (is "?l = ?r")
proof (rule pmf_equiv_intro1[symmetric])
  fix e
  assume a: "e \<in> set_pmf ?r"
  have "e \<in> set_pmf ?l"
    using a pmf_mix_deeper by (metis assms(1) assms(2) assms(3) mix_pmf_comp_left_div pmf_eq_0_set_pmf)
  then have "pmf ?l e = \<beta> * pmf p e - \<beta> * pmf q e + pmf q e"
    using pmf_mix_deeper[of "\<beta>/\<alpha>" p q e] mix_pmf_comp_left_div[of \<alpha> \<beta> p q e] assms by auto
  then show "pmf (mix_pmf \<beta> p q) e = pmf (mix_pmf (\<beta> / \<alpha>) (mix_pmf \<alpha> p q) q) e"
    by (metis (full_types) assms(1) assms(2) assms(3) mix_pmf_comp_left_div pmf_mix_deeper)
qed

lemma product_mix_pmf_prob_distrib:
  assumes "a \<in> {0..1}"
    and "b \<in> {0..1}"
  shows "mix_pmf a (mix_pmf b p q) q = mix_pmf (a*b) p q"
proof -
  define \<gamma> where g: "\<gamma> = (a * b)"
  define l where l: "l = (mix_pmf b p q)"
  define r where r: "r =  mix_pmf (a*b) p q"
  have y: "\<gamma> \<in> {0..1}"
    using assms(2) mult_le_one assms g by auto
  have alt_: "\<forall>e \<in> set_pmf l. pmf r e = \<gamma> * pmf p e + pmf q e - \<gamma> * pmf q e"
  proof
    fix e
    have "pmf r e = \<gamma> * pmf p e + (1-\<gamma>) * pmf q e"
      using \<open>\<gamma> \<in> {0..1}\<close> g pmf_mix r by fastforce
    moreover have "... = \<gamma> * pmf p e + 1 * pmf q e - \<gamma> * pmf q e"
      by (simp add: algebra_simps)
    moreover have "... = pmf (mix_pmf \<gamma> p q) e"
      using calculation g r by auto
    moreover have "... = \<gamma>  * pmf p e + pmf q e - \<gamma> * pmf q e"
      using calculation by auto
    ultimately show "pmf r e = \<gamma> * pmf p e + pmf q e - \<gamma> * pmf q e"
      by auto
  qed
  have "\<forall>e \<in> set_pmf r. pmf l e = b * pmf p e + pmf q e - b * pmf q e"
    using allI pmf_mix_deeper assms(2) l by fastforce
  have "mix_pmf a (mix_pmf b p q) q = mix_pmf (a * b) p q"
  proof (rule ccontr)
    assume neg:"\<not>mix_pmf a (mix_pmf b p q) q = mix_pmf (a * b) p q"
    then have b: "b \<noteq> 0"
      by (metis (no_types) assms(1) mult_cancel_right2 pmf_mix_0 set_pmf_mix_eq)
    have f3: "b - (a * b) > 0 \<longrightarrow> mix_pmf a (mix_pmf b p q) q = mix_pmf (a * b) p q"
      by (metis assms(2) diff_le_0_iff_le g mix_pmf_comp_with_dif_equiv mult_eq_0_iff
          nonzero_mult_div_cancel_right not_le order_refl y)
    thus False
      using b neg assms(1) assms(2) by auto
  qed
  then show ?thesis by auto
qed

lemma mix_pmf_subset_of_original:
  assumes "a \<in> {0..1}"
  shows "(set_pmf (mix_pmf a p q)) \<subseteq> set_pmf p \<union> set_pmf q"
proof -
  have "a \<in> {0<..<1} \<Longrightarrow> ?thesis"
    by (simp add: set_pmf_mix)
  moreover have "a = 1 \<Longrightarrow> ?thesis"
    by simp
  moreover have "a = 0 \<Longrightarrow> ?thesis"
    by simp
  ultimately show ?thesis
    using assms less_eq_real_def by auto
qed

lemma mix_pmf_preserves_finite_support:
  assumes "a \<in> {0..1}"
  assumes "finite (set_pmf p)"
    and "finite (set_pmf q)"
  shows "finite (set_pmf (mix_pmf a p q))"
  by (meson assms(1) assms(2) assms(3) finite_Un finite_subset mix_pmf_subset_of_original)

lemma ex_certain_iff_singleton_support:
  shows "(\<exists>x. pmf p x = 1) \<longleftrightarrow> card (set_pmf p) = 1"
proof (rule iffI, goal_cases)
  case 1
  show ?case
  proof (rule ccontr)
    assume neg: "\<not> card (set_pmf p) = 1"
    then have "card (set_pmf p) \<noteq> 1"
      by blast
    have "finite (set_pmf p)"
      by (metis "1" empty_iff finite.emptyI finite_insert insert_iff
          not_le pmf_le_1 pmf_neq_exists_less pmf_nonneg set_pmf_iff set_return_pmf)
    then have sumeq_1: "(\<Sum>i \<in> set_pmf p. pmf p i) = 1"
      using sum_pmf_eq_1[of "set_pmf p" p] by auto
    have set_pmf_nemtpy: "set_pmf p \<noteq> {}"
      by (simp add: set_pmf_not_empty)
    then have g1: "card (set_pmf p) > 1"
      by (metis card_0_eq less_one nat_neq_iff neg sum.infinite sumeq_1 zero_neq_one)
    have "card (set_pmf p) > 1 \<longrightarrow> (\<Sum>i \<in> set_pmf p. pmf p i) > 1"
    proof
      assume "card (set_pmf p) > 1"
      have "\<exists>x y. pmf p x = 1 \<and> y \<noteq> x \<and> y \<in> set_pmf p"
        using  set_pmf_nemtpy is_singletonI' is_singleton_altdef
        by (metis "1" neg)
      then show "(\<Sum>i \<in> set_pmf p. pmf p i) > 1"
        by (metis AE_measure_pmf_iff UNIV_I empty_iff insert_iff
            measure_pmf.prob_eq_1 pmf.rep_eq sets_measure_pmf)
    qed
    then have "card (set_pmf p) < 1"
      using sumeq_1 neg by linarith
    then show False
      using g1 by linarith
  qed
qed (metis card_1_singletonE less_numeral_extra(1) pmf.rep_eq subset_eq
    sum_pmf_eq_1[of "set_pmf p" p]  card_gt_0_iff[of "set_pmf p"]
    measure_measure_pmf_finite[of "set_pmf p"])

text \<open> We thank Manuel Eberl for suggesting the following two lemmas. \<close>

lemma mix_pmf_partition:
  fixes p :: "'a pmf"
  assumes "y \<in> set_pmf p" "set_pmf p - {y} \<noteq> {}"
  obtains a q where "a \<in> {0<..<1}" "set_pmf q = set_pmf p - {y}"
    "p = mix_pmf a q (return_pmf y)"
proof -
  from assms obtain x where x: "x \<in> set_pmf p - {y}" by auto
  define a where "a = 1 - pmf p y"
  have a_n1:"a \<noteq> 1"
    by (simp add: a_def assms(1) pmf_eq_0_set_pmf)
  have "pmf p y \<noteq> 1"
    using ex_certain_iff_singleton_support by (metis (full_types)
        Diff_cancel assms(1) assms(2) card_1_singletonE singletonD)
  hence y: "pmf p y < 1" using pmf_le_1[of p y] unfolding a_def by linarith
  hence a: "a > 0" by (simp add: a_def)
  define q where "q = embed_pmf (\<lambda>z. if z = y then 0 else pmf p z / a)"
  have q: "pmf q z = (if z = y then 0 else pmf p z / a)" for z
    unfolding q_def
  proof (rule pmf_embed_pmf)
    have "1 = (\<integral>\<^sup>+ x. ennreal (pmf p x) \<partial>count_space UNIV)"
      by (rule nn_integral_pmf_eq_1 [symmetric])
    also have "\<dots> = (\<integral>\<^sup>+ x. ennreal (pmf p x) * indicator {y} x +
                      ennreal (pmf p x) * indicator (-{y}) x \<partial>count_space UNIV)"
      by (intro nn_integral_cong) (auto simp: indicator_def)
    also have "\<dots> = (\<integral>\<^sup>+ x. ennreal (pmf p x) * indicator {y} x \<partial>count_space UNIV) +
                    (\<integral>\<^sup>+ x. ennreal (pmf p x) * indicator (-{y}) x \<partial>count_space UNIV)"
      by (subst nn_integral_add) auto
    also have "(\<integral>\<^sup>+ x. ennreal (pmf p x) * indicator {y} x \<partial>count_space UNIV) = pmf p y"
      by (subst nn_integral_indicator_finite) auto
    also have "ennreal (pmf p y) + (\<integral>\<^sup>+ x. ennreal (pmf p x) * indicator (-{y}) x \<partial>count_space UNIV)
                 - ennreal (pmf p y) = (\<integral>\<^sup>+ x. ennreal (pmf p x) * indicator (-{y}) x \<partial>count_space UNIV)"
      by simp
    also have "1 - ennreal (pmf p y) = ennreal (1 - pmf p y)"
      by (subst ennreal_1 [symmetric], subst ennreal_minus) auto
    finally have eq: "(\<integral>\<^sup>+x\<in>-{y}. ennreal (pmf p x)\<partial>count_space UNIV) = 1 - pmf p y" ..
    have "(\<integral>\<^sup>+ x. ennreal (if x = y then 0 else pmf p x / a) \<partial>count_space UNIV) =
            (\<integral>\<^sup>+ x. inverse a * (ennreal (pmf p x) * indicator (-{y}) x) \<partial>count_space UNIV)"
      using a by (intro nn_integral_cong) (auto simp: divide_simps ennreal_mult' [symmetric])
    also have "\<dots> = inverse a * (\<integral>\<^sup>+ x\<in>-{y}. ennreal (pmf p x) \<partial>count_space UNIV)"
      using a by (subst nn_integral_cmult [symmetric]) (auto simp: ennreal_mult')
    also note eq
    also have "ennreal (inverse a) * ennreal (1 - pmf p y) = ennreal ((1 - pmf p y) / a)"
      using a by (subst ennreal_mult' [symmetric]) (auto simp: field_simps)
    also have "(1 - pmf p y) / a = 1" using y by (simp add: a_def)
    finally show "(\<integral>\<^sup>+ x. ennreal (if x = y then 0 else pmf p x / a) \<partial>count_space UNIV) = 1"
      by simp
  qed (insert a, auto)
  have "mix_pmf (1 - pmf p y) q (return_pmf y) = p"
    using y by (intro pmf_eqI) (auto simp: q pmf_mix pmf_le_1 a_def)
  moreover have "set_pmf q = set_pmf p - {y}"
    using y by (auto simp: q set_pmf_eq a_def)
  ultimately show ?thesis using that[of "1 - pmf p y" q] y assms by (auto simp: set_pmf_eq)
qed

lemma pmf_mix_induct [consumes 2, case_names degenerate mix]:
  assumes "finite A" "set_pmf p \<subseteq> A"
  assumes degenerate: "\<And>x. x \<in> A \<Longrightarrow> P (return_pmf x)"
  assumes mix:        "\<And>p a y. set_pmf p \<subseteq> A \<Longrightarrow> a \<in> {0<..<1} \<Longrightarrow> y \<in> A \<Longrightarrow>
                         P p \<Longrightarrow> P (mix_pmf a p (return_pmf y))"
  shows "P p"
proof -
  have "finite (set_pmf p)" "set_pmf p \<noteq> {}" "set_pmf p \<subseteq> A"
    using assms(1,2) by (auto simp: set_pmf_not_empty dest: finite_subset)
  thus ?thesis
  proof (induction "set_pmf p" arbitrary: p rule: finite_ne_induct)
    case (singleton x p)
    hence "p = return_pmf x" using set_pmf_subset_singleton[of p x] by auto
    thus ?case using singleton by (auto intro: degenerate)
  next
    case (insert x B p)
    from insert.hyps have "x \<in> set_pmf p" "set_pmf p - {x} \<noteq> {}" by auto
    from mix_pmf_partition[OF this] obtain a q
      where decomp: "a \<in> {0<..<1}" "set_pmf q = set_pmf p - {x}"
        "p = mix_pmf a q (return_pmf x)" by blast
    have "P (mix_pmf a q (return_pmf x))"
      using insert.prems decomp(1) insert.hyps
      by (intro mix insert) (auto simp: decomp(2))
    with decomp(3) show ?case by simp
  qed
qed

lemma pmf_mix_induct' [consumes 2, case_names degenerate mix]:
  assumes "finite A" "set_pmf p \<subseteq> A"
  assumes degenerate: "\<And>x. x \<in> A \<Longrightarrow> P (return_pmf x)"
  assumes mix:        "\<And>p q a. set_pmf p \<subseteq> A \<Longrightarrow> set_pmf q \<subseteq> A \<Longrightarrow> a \<in> {0<..<1} \<Longrightarrow>
                         P p \<Longrightarrow> P q \<Longrightarrow> P (mix_pmf a p q)"
  shows "P p"
  using assms by (induct p rule: pmf_mix_induct)(auto)+

lemma distribute_alpha_over_sum:
  shows "(\<Sum>i\<in>set_pmf T. a * pmf p i * f i) = a * (\<Sum>i\<in>set_pmf T. pmf p i * f i)"
  by (metis (mono_tags, lifting) semiring_normalization_rules(18) sum.cong sum_distrib_left)

lemma sum_over_subset_pmf_support:
  assumes "finite T"
  assumes "set_pmf p \<subseteq> T"
  shows "(\<Sum>i\<in>T. a * pmf p i * f i) = (\<Sum>i\<in>set_pmf p. a * pmf p i * f i)"
proof -
  consider (eq) "set_pmf p = T" | (sub) "set_pmf p \<subset> T"
    using assms by blast
  then show ?thesis
  proof (cases)
  next
    case sub
    define A where "A = T - (set_pmf p)"
    have "finite (set_pmf p)"
      using assms(1) assms(2) finite_subset by auto
    moreover have "finite A"
      using A_def assms(1) by blast
    moreover have "A \<inter> set_pmf p = {}"
      using A_def assms(1) by blast
    ultimately have *: "(\<Sum>i\<in>T. a * pmf p i * f i) = (\<Sum>i\<in>set_pmf p. a * pmf p i * f i) + (\<Sum>i\<in>A. a * pmf p i * f i)"
      using sum.union_disjoint by (metis (no_types) A_def Un_Diff_cancel2
          Un_absorb2 assms(2) inf.commute inf_sup_aci(5) sum.union_disjoint)
    have "\<forall>e \<in> A. pmf p e = 0"
      by (simp add: A_def pmf_eq_0_set_pmf)
    hence "(\<Sum>i\<in>A. a * pmf p i * f i) = 0"
      by simp
    then show ?thesis
      by (simp add: "*")
  qed (auto)
qed

lemma expected_value_mix_pmf_distrib:
  assumes "finite (set_pmf p)"
    and "finite (set_pmf q)"
  assumes "a \<in> {0<..<1}"
  shows "measure_pmf.expectation (mix_pmf a p q) f = a * measure_pmf.expectation p f + (1-a) * measure_pmf.expectation q f"
proof -
  have fn: "finite (set_pmf (mix_pmf a p q))"
    using mix_pmf_preserves_finite_support assms less_eq_real_def  by auto
  have subsets: "set_pmf p \<subseteq> set_pmf (mix_pmf a p q)" "set_pmf q \<subseteq> set_pmf (mix_pmf a p q)"
    using assms assms set_pmf_mix by(fastforce)+
  have *: "(\<Sum>i \<in> set_pmf (mix_pmf a p q). a * pmf p i * f i) = a * (\<Sum>i \<in> set_pmf (mix_pmf a p q). pmf p i * f i)"
    by (metis (mono_tags, lifting) mult.assoc sum.cong sum_distrib_left)
  have **: "(\<Sum>i \<in> set_pmf (mix_pmf a p q). (1-a) * pmf q i * f i) = (1-a) * (\<Sum>i \<in> set_pmf (mix_pmf a p q). pmf q i * f i)"
    using distribute_alpha_over_sum[of "(1 - a)" q f "(mix_pmf a p q)"] by auto
  have ***: "measure_pmf.expectation (mix_pmf a p q) f = (\<Sum>i \<in> set_pmf (mix_pmf a p q). pmf (mix_pmf a p q) i * f i)"
    by (metis fn pmf_integral_code_unfold pmf_integral_pmf_set_integral
        pmf_set_integral_code_alt_finite)
  also have g: "... = (\<Sum>i \<in> set_pmf (mix_pmf a p q). (a * pmf p i + (1-a) * pmf q i) * f i)"
    using pmf_mix[of a p q] assms(3) by auto
  also have ****: "... =  (\<Sum>i \<in> set_pmf (mix_pmf a p q). a * pmf p i * f i + (1-a) * pmf q i * f i)"
    by (simp add: mult.commute ring_class.ring_distribs(1))
  also have f: "... = (\<Sum>i \<in> set_pmf (mix_pmf a p q). a * pmf p i * f i) + (\<Sum>i \<in> set_pmf (mix_pmf a p q). (1-a) * pmf q i * f i)"
    by (simp add: sum.distrib)
  also have "... = a * (\<Sum>i \<in> set_pmf (mix_pmf a p q). pmf p i * f i) + (1-a) * (\<Sum>i \<in> set_pmf (mix_pmf a p q). pmf q i * f i)"
    using * ** by simp
  also have h: "... =  a * (\<Sum>i \<in> set_pmf p. pmf p i * f i) + (1-a) * (\<Sum>i \<in> set_pmf q. pmf q i * f i)"
  proof -
    have "(\<Sum>i \<in> set_pmf (mix_pmf a p q). pmf p i * f i) = (\<Sum>i \<in> set_pmf p. pmf p i * f i)"
      using subsets sum_over_subset_pmf_support[of "(mix_pmf a p q)" p 1 f] fn by auto
    moreover have "(\<Sum>i \<in> set_pmf (mix_pmf a p q). pmf q i * f i) = (\<Sum>i \<in> set_pmf q. pmf q i * f i)"
      using subsets sum_over_subset_pmf_support[of "(mix_pmf a p q)" q 1 f] fn by auto
    ultimately show ?thesis
      by (simp)
  qed
  finally show ?thesis
  proof -
    have "(\<Sum>i\<in>set_pmf q. pmf q i * f i) = measure_pmf.expectation q f"
      by (metis (full_types) assms(2) pmf_integral_code_unfold pmf_integral_pmf_set_integral pmf_set_integral_code_alt_finite)
    moreover have "(\<Sum>i\<in>set_pmf p. pmf p i * f i) = measure_pmf.expectation p f"
      by (metis (full_types) assms(1) pmf_integral_code_unfold pmf_integral_pmf_set_integral pmf_set_integral_code_alt_finite)
    ultimately show ?thesis
      by (simp add: "*" "**" "***" "****" f g h)
  qed
qed

lemma expected_value_mix_pmf:
  assumes "finite (set_pmf p)"
    and "finite (set_pmf q)"
  assumes "a \<in> {0..1}"
  shows "measure_pmf.expectation (mix_pmf a p q) f = a * measure_pmf.expectation p f + (1-a) * measure_pmf.expectation q f"
proof -
  consider (0) "a = 0" | (b) "a \<in> {0<..<1}" | (1) "a = 1"
    using assms(3) less_eq_real_def by auto
  then show ?thesis
  proof (cases)
    case 0
    have "(mix_pmf a p q) = q"
      using 0 pmf_mix_0 by blast
    have "measure_pmf.expectation q f = (1-a) * measure_pmf.expectation q f"
      by (simp add: 0)
    show ?thesis
      using 0 by auto
  next
    case b
    show ?thesis
      using assms(1) assms(2) b expected_value_mix_pmf_distrib by blast
  next
    case 1
    have "(mix_pmf a p q) = p"
      using 1 pmf_mix_0 by simp
    then show ?thesis
      by (simp add: "1")
  qed
qed

end


(*  Title:      HOL/Complete_Partial_Order.thy
    Author:     Brian Huffman, Portland State University
    Author:     Alexander Krauss, TU Muenchen
*)

section \<open>Chain-complete partial orders and their fixpoints\<close>

theory Complete_Partial_Order
  imports Product_Type
begin

subsection \<open>Chains\<close>

text \<open>
  A chain is a totally-ordered set. Chains are parameterized over
  the order for maximal flexibility, since type classes are not enough.
\<close>

definition chain :: "('a \<Rightarrow> 'a \<Rightarrow> bool) \<Rightarrow> 'a set \<Rightarrow> bool"
  where "chain ord S \<longleftrightarrow> (\<forall>x\<in>S. \<forall>y\<in>S. ord x y \<or> ord y x)"

lemma chainI:
  assumes "\<And>x y. x \<in> S \<Longrightarrow> y \<in> S \<Longrightarrow> ord x y \<or> ord y x"
  shows "chain ord S"
  using assms unfolding chain_def by fast

lemma chainD:
  assumes "chain ord S" and "x \<in> S" and "y \<in> S"
  shows "ord x y \<or> ord y x"
  using assms unfolding chain_def by fast

lemma chainE:
  assumes "chain ord S" and "x \<in> S" and "y \<in> S"
  obtains "ord x y" | "ord y x"
  using assms unfolding chain_def by fast

lemma chain_empty: "chain ord {}"
  by (simp add: chain_def)

lemma chain_equality: "chain (=) A \<longleftrightarrow> (\<forall>x\<in>A. \<forall>y\<in>A. x = y)"
  by (auto simp add: chain_def)

lemma chain_subset: "chain ord A \<Longrightarrow> B \<subseteq> A \<Longrightarrow> chain ord B"
  by (rule chainI) (blast dest: chainD)

lemma chain_imageI:
  assumes chain: "chain le_a Y"
    and mono: "\<And>x y. x \<in> Y \<Longrightarrow> y \<in> Y \<Longrightarrow> le_a x y \<Longrightarrow> le_b (f x) (f y)"
  shows "chain le_b (f ` Y)"
  by (blast intro: chainI dest: chainD[OF chain] mono)

subsection \<open>Chain-complete partial orders\<close>

text \<open>
  A \<open>ccpo\<close> has a least upper bound for any chain.  In particular, the
  empty set is a chain, so every \<open>ccpo\<close> must have a bottom element.
\<close>

class ccpo = order + Sup +
  assumes ccpo_Sup_upper: "chain (\<le>) A \<Longrightarrow> x \<in> A \<Longrightarrow> x \<le> Sup A"
  assumes ccpo_Sup_least: "chain (\<le>) A \<Longrightarrow> (\<And>x. x \<in> A \<Longrightarrow> x \<le> z) \<Longrightarrow> Sup A \<le> z"
begin

lemma chain_singleton: "Complete_Partial_Order.chain (\<le>) {x}"
  by (rule chainI) simp

lemma ccpo_Sup_singleton [simp]: "\<Squnion>{x} = x"
  by (rule order.antisym) (auto intro: ccpo_Sup_least ccpo_Sup_upper simp add: chain_singleton)

subsection \<open>Transfinite iteration of a function\<close>

context notes [[inductive_internals]]
begin

inductive_set iterates :: "('a \<Rightarrow> 'a) \<Rightarrow> 'a set"
  for f :: "'a \<Rightarrow> 'a"
  where
    step: "x \<in> iterates f \<Longrightarrow> f x \<in> iterates f"
  | Sup: "chain (\<le>) M \<Longrightarrow> \<forall>x\<in>M. x \<in> iterates f \<Longrightarrow> Sup M \<in> iterates f"

end

lemma iterates_le_f: "x \<in> iterates f \<Longrightarrow> monotone (\<le>) (\<le>) f \<Longrightarrow> x \<le> f x"
  by (induct x rule: iterates.induct)
    (force dest: monotoneD intro!: ccpo_Sup_upper ccpo_Sup_least)+

lemma chain_iterates:
  assumes f: "monotone (\<le>) (\<le>) f"
  shows "chain (\<le>) (iterates f)" (is "chain _ ?C")
proof (rule chainI)
  fix x y
  assume "x \<in> ?C" "y \<in> ?C"
  then show "x \<le> y \<or> y \<le> x"
  proof (induct x arbitrary: y rule: iterates.induct)
    fix x y
    assume y: "y \<in> ?C"
      and IH: "\<And>z. z \<in> ?C \<Longrightarrow> x \<le> z \<or> z \<le> x"
    from y show "f x \<le> y \<or> y \<le> f x"
    proof (induct y rule: iterates.induct)
      case (step y)
      with IH f show ?case by (auto dest: monotoneD)
    next
      case (Sup M)
      then have chM: "chain (\<le>) M"
        and IH': "\<And>z. z \<in> M \<Longrightarrow> f x \<le> z \<or> z \<le> f x" by auto
      show "f x \<le> Sup M \<or> Sup M \<le> f x"
      proof (cases "\<exists>z\<in>M. f x \<le> z")
        case True
        then have "f x \<le> Sup M"
          by (blast intro: ccpo_Sup_upper[OF chM] order_trans)
        then show ?thesis ..
      next
        case False
        with IH' show ?thesis
          by (auto intro: ccpo_Sup_least[OF chM])
      qed
    qed
  next
    case (Sup M y)
    show ?case
    proof (cases "\<exists>x\<in>M. y \<le> x")
      case True
      then have "y \<le> Sup M"
        by (blast intro: ccpo_Sup_upper[OF Sup(1)] order_trans)
      then show ?thesis ..
    next
      case False with Sup
      show ?thesis by (auto intro: ccpo_Sup_least)
    qed
  qed
qed

lemma bot_in_iterates: "Sup {} \<in> iterates f"
  by (auto intro: iterates.Sup simp add: chain_empty)

subsection \<open>Fixpoint combinator\<close>

definition fixp :: "('a \<Rightarrow> 'a) \<Rightarrow> 'a"
  where "fixp f = Sup (iterates f)"

lemma iterates_fixp:
  assumes f: "monotone (\<le>) (\<le>) f"
  shows "fixp f \<in> iterates f"
  unfolding fixp_def
  by (simp add: iterates.Sup chain_iterates f)

lemma fixp_unfold:
  assumes f: "monotone (\<le>) (\<le>) f"
  shows "fixp f = f (fixp f)"
proof (rule order.antisym)
  show "fixp f \<le> f (fixp f)"
    by (intro iterates_le_f iterates_fixp f)
  have "f (fixp f) \<le> Sup (iterates f)"
    by (intro ccpo_Sup_upper chain_iterates f iterates.step iterates_fixp)
  then show "f (fixp f) \<le> fixp f"
    by (simp only: fixp_def)
qed

lemma fixp_lowerbound:
  assumes f: "monotone (\<le>) (\<le>) f"
    and z: "f z \<le> z"
  shows "fixp f \<le> z"
  unfolding fixp_def
proof (rule ccpo_Sup_least[OF chain_iterates[OF f]])
  fix x
  assume "x \<in> iterates f"
  then show "x \<le> z"
  proof (induct x rule: iterates.induct)
    case (step x)
    from f \<open>x \<le> z\<close> have "f x \<le> f z" by (rule monotoneD)
    also note z
    finally show "f x \<le> z" .
  next
    case (Sup M)
    then show ?case
      by (auto intro: ccpo_Sup_least)
  qed
qed

end

subsection \<open>Fixpoint induction\<close>

setup \<open>Sign.map_naming (Name_Space.mandatory_path "ccpo")\<close>

definition admissible :: "('a set \<Rightarrow> 'a) \<Rightarrow> ('a \<Rightarrow> 'a \<Rightarrow> bool) \<Rightarrow> ('a \<Rightarrow> bool) \<Rightarrow> bool"
  where "admissible lub ord P \<longleftrightarrow> (\<forall>A. chain ord A \<longrightarrow> A \<noteq> {} \<longrightarrow> (\<forall>x\<in>A. P x) \<longrightarrow> P (lub A))"

lemma admissibleI:
  assumes "\<And>A. chain ord A \<Longrightarrow> A \<noteq> {} \<Longrightarrow> \<forall>x\<in>A. P x \<Longrightarrow> P (lub A)"
  shows "ccpo.admissible lub ord P"
  using assms unfolding ccpo.admissible_def by fast

lemma admissibleD:
  assumes "ccpo.admissible lub ord P"
  assumes "chain ord A"
  assumes "A \<noteq> {}"
  assumes "\<And>x. x \<in> A \<Longrightarrow> P x"
  shows "P (lub A)"
  using assms by (auto simp: ccpo.admissible_def)

setup \<open>Sign.map_naming Name_Space.parent_path\<close>

lemma (in ccpo) fixp_induct:
  assumes adm: "ccpo.admissible Sup (\<le>) P"
  assumes mono: "monotone (\<le>) (\<le>) f"
  assumes bot: "P (Sup {})"
  assumes step: "\<And>x. P x \<Longrightarrow> P (f x)"
  shows "P (fixp f)"
  unfolding fixp_def
  using adm chain_iterates[OF mono]
proof (rule ccpo.admissibleD)
  show "iterates f \<noteq> {}"
    using bot_in_iterates by auto
next
  fix x
  assume "x \<in> iterates f"
  then show "P x"
  proof (induct rule: iterates.induct)
    case prems: (step x)
    from this(2) show ?case by (rule step)
  next
    case (Sup M)
    then show ?case by (cases "M = {}") (auto intro: step bot ccpo.admissibleD adm)
  qed
qed

lemma admissible_True: "ccpo.admissible lub ord (\<lambda>x. True)"
  unfolding ccpo.admissible_def by simp

(*lemma admissible_False: "\<not> ccpo.admissible lub ord (\<lambda>x. False)"
unfolding ccpo.admissible_def chain_def by simp
*)
lemma admissible_const: "ccpo.admissible lub ord (\<lambda>x. t)"
  by (auto intro: ccpo.admissibleI)

lemma admissible_conj:
  assumes "ccpo.admissible lub ord (\<lambda>x. P x)"
  assumes "ccpo.admissible lub ord (\<lambda>x. Q x)"
  shows "ccpo.admissible lub ord (\<lambda>x. P x \<and> Q x)"
  using assms unfolding ccpo.admissible_def by simp

lemma admissible_all:
  assumes "\<And>y. ccpo.admissible lub ord (\<lambda>x. P x y)"
  shows "ccpo.admissible lub ord (\<lambda>x. \<forall>y. P x y)"
  using assms unfolding ccpo.admissible_def by fast

lemma admissible_ball:
  assumes "\<And>y. y \<in> A \<Longrightarrow> ccpo.admissible lub ord (\<lambda>x. P x y)"
  shows "ccpo.admissible lub ord (\<lambda>x. \<forall>y\<in>A. P x y)"
  using assms unfolding ccpo.admissible_def by fast

lemma chain_compr: "chain ord A \<Longrightarrow> chain ord {x \<in> A. P x}"
  unfolding chain_def by fast

context ccpo
begin

lemma admissible_disj:
  fixes P Q :: "'a \<Rightarrow> bool"
  assumes P: "ccpo.admissible Sup (\<le>) (\<lambda>x. P x)"
  assumes Q: "ccpo.admissible Sup (\<le>) (\<lambda>x. Q x)"
  shows "ccpo.admissible Sup (\<le>) (\<lambda>x. P x \<or> Q x)"
proof (rule ccpo.admissibleI)
  fix A :: "'a set"
  assume chain: "chain (\<le>) A"
  assume A: "A \<noteq> {}" and P_Q: "\<forall>x\<in>A. P x \<or> Q x"
  have "(\<exists>x\<in>A. P x) \<and> (\<forall>x\<in>A. \<exists>y\<in>A. x \<le> y \<and> P y) \<or> (\<exists>x\<in>A. Q x) \<and> (\<forall>x\<in>A. \<exists>y\<in>A. x \<le> y \<and> Q y)"
    (is "?P \<or> ?Q" is "?P1 \<and> ?P2 \<or> _")
  proof (rule disjCI)
    assume "\<not> ?Q"
    then consider "\<forall>x\<in>A. \<not> Q x" | a where "a \<in> A" "\<forall>y\<in>A. a \<le> y \<longrightarrow> \<not> Q y"
      by blast
    then show ?P
    proof cases
      case 1
      with P_Q have "\<forall>x\<in>A. P x" by blast
      with A show ?P by blast
    next
      case 2
      note a = \<open>a \<in> A\<close>
      show ?P
      proof
        from P_Q 2 have *: "\<forall>y\<in>A. a \<le> y \<longrightarrow> P y" by blast
        with a have "P a" by blast
        with a show ?P1 by blast
        show ?P2
        proof
          fix x
          assume x: "x \<in> A"
          with chain a show "\<exists>y\<in>A. x \<le> y \<and> P y"
          proof (rule chainE)
            assume le: "a \<le> x"
            with * a x have "P x" by blast
            with x le show ?thesis by blast
          next
            assume "a \<ge> x"
            with a \<open>P a\<close> show ?thesis by blast
          qed
        qed
      qed
    qed
  qed
  moreover
  have "Sup A = Sup {x \<in> A. P x}" if "\<And>x. x\<in>A \<Longrightarrow> \<exists>y\<in>A. x \<le> y \<and> P y" for P
  proof (rule order.antisym)
    have chain_P: "chain (\<le>) {x \<in> A. P x}"
      by (rule chain_compr [OF chain])
    show "Sup A \<le> Sup {x \<in> A. P x}"
    proof (rule ccpo_Sup_least [OF chain])
      show "\<And>x. x \<in> A \<Longrightarrow> x \<le> \<Squnion> {x \<in> A. P x}"
          by (blast intro: ccpo_Sup_upper[OF chain_P] order_trans dest: that)
      qed
    show "Sup {x \<in> A. P x} \<le> Sup A"
      apply (rule ccpo_Sup_least [OF chain_P])
      apply (simp add: ccpo_Sup_upper [OF chain])
      done
  qed
  ultimately
  consider "\<exists>x. x \<in> A \<and> P x" "Sup A = Sup {x \<in> A. P x}"
    | "\<exists>x. x \<in> A \<and> Q x" "Sup A = Sup {x \<in> A. Q x}"
    by blast
  then show "P (Sup A) \<or> Q (Sup A)"
  proof cases
    case 1
    then show ?thesis
      using ccpo.admissibleD [OF P chain_compr [OF chain]] by force
  next
    case 2
    then show ?thesis
      using ccpo.admissibleD [OF Q chain_compr [OF chain]] by force
  qed
qed

end

instance complete_lattice \<subseteq> ccpo
  by standard (fast intro: Sup_upper Sup_least)+

lemma lfp_eq_fixp:
  assumes mono: "mono f"
  shows "lfp f = fixp f"
proof (rule order.antisym)
  from mono have f': "monotone (\<le>) (\<le>) f"
    unfolding mono_def monotone_def .
  show "lfp f \<le> fixp f"
    by (rule lfp_lowerbound, subst fixp_unfold [OF f'], rule order_refl)
  show "fixp f \<le> lfp f"
    by (rule fixp_lowerbound [OF f']) (simp add: lfp_fixpoint [OF mono])
qed

hide_const (open) iterates fixp

end


(*  Title:      HOL/ex/Adhoc_Overloading_Examples.thy
    Author:     Christian Sternagel
*)

section {* Ad Hoc Overloading *}

theory Adhoc_Overloading_Examples
imports
  Main
  "~~/src/Tools/Adhoc_Overloading"
  "~~/src/HOL/Library/Infinite_Set"
begin

text {*Adhoc overloading allows to overload a constant depending on
its type. Typically this involves to introduce an uninterpreted
constant (used for input and output) and then add some variants (used
internally).*}

subsection {* Plain Ad Hoc Overloading *}

text {*Consider the type of first-order terms.*}
datatype ('a, 'b) "term" =
  Var 'b |
  Fun 'a "('a, 'b) term list"

text {*The set of variables of a term might be computed as follows.*}
fun term_vars :: "('a, 'b) term \<Rightarrow> 'b set" where
  "term_vars (Var x) = {x}" |
  "term_vars (Fun f ts) = \<Union>set (map term_vars ts)"

text {*However, also for \emph{rules} (i.e., pairs of terms) and term
rewrite systems (i.e., sets of rules), the set of variables makes
sense. Thus we introduce an unspecified constant @{text vars}.*}

consts vars :: "'a \<Rightarrow> 'b set"

text {*Which is then overloaded with variants for terms, rules, and TRSs.*}
adhoc_overloading
  vars term_vars

value "vars (Fun ''f'' [Var 0, Var 1])"

fun rule_vars :: "('a, 'b) term \<times> ('a, 'b) term \<Rightarrow> 'b set" where
  "rule_vars (l, r) = vars l \<union> vars r"

adhoc_overloading
  vars rule_vars

value "vars (Var 1, Var 0)"

definition trs_vars :: "(('a, 'b) term \<times> ('a, 'b) term) set \<Rightarrow> 'b set" where
  "trs_vars R = \<Union>(rule_vars ` R)"

adhoc_overloading
  vars trs_vars

value "vars {(Var 1, Var 0)}"

text {*Sometimes it is necessary to add explicit type constraints
before a variant can be determined.*}
(*value "vars R" (*has multiple instances*)*)
value "vars (R :: (('a, 'b) term \<times> ('a, 'b) term) set)"

text {*It is also possible to remove variants.*}
no_adhoc_overloading
  vars term_vars rule_vars

(*value "vars (Var 1)" (*does not have an instance*)*)

text {*As stated earlier, the overloaded constant is only used for
input and output. Internally, always a variant is used, as can be
observed by the configuration option @{text show_variants}.*}

adhoc_overloading
  vars term_vars

declare [[show_variants]]

term "vars (Var 1)" (*which yields: "term_vars (Var 1)"*)

subsection {* Adhoc Overloading inside Locales *}

text {*As example we use permutations that are parametrized over an
atom type @{typ "'a"}.*}

definition perms :: "('a \<Rightarrow> 'a) set" where
  "perms = {f. bij f \<and> finite {x. f x \<noteq> x}}"

typedef 'a perm = "perms :: ('a \<Rightarrow> 'a) set"
  by (default) (auto simp: perms_def)

text {*First we need some auxiliary lemmas.*}
lemma permsI [Pure.intro]:
  assumes "bij f" and "MOST x. f x = x"
  shows "f \<in> perms"
  using assms by (auto simp: perms_def) (metis MOST_iff_finiteNeg)

lemma perms_imp_bij:
  "f \<in> perms \<Longrightarrow> bij f"
  by (simp add: perms_def)

lemma perms_imp_MOST_eq:
  "f \<in> perms \<Longrightarrow> MOST x. f x = x"
  by (simp add: perms_def) (metis MOST_iff_finiteNeg)

lemma id_perms [simp]:
  "id \<in> perms"
  "(\<lambda>x. x) \<in> perms"
  by (auto simp: perms_def bij_def)

lemma perms_comp [simp]:
  assumes f: "f \<in> perms" and g: "g \<in> perms"
  shows "(f \<circ> g) \<in> perms"
  apply (intro permsI bij_comp)
  apply (rule perms_imp_bij [OF g])
  apply (rule perms_imp_bij [OF f])
  apply (rule MOST_rev_mp [OF perms_imp_MOST_eq [OF g]])
  apply (rule MOST_rev_mp [OF perms_imp_MOST_eq [OF f]])
  by simp

lemma perms_inv:
  assumes f: "f \<in> perms"
  shows "inv f \<in> perms"
  apply (rule permsI)
  apply (rule bij_imp_bij_inv)
  apply (rule perms_imp_bij [OF f])
  apply (rule MOST_mono [OF perms_imp_MOST_eq [OF f]])
  apply (erule subst, rule inv_f_f)
  apply (rule bij_is_inj [OF perms_imp_bij [OF f]])
  done

lemma bij_Rep_perm: "bij (Rep_perm p)"
  using Rep_perm [of p] unfolding perms_def by simp

instantiation perm :: (type) group_add
begin

definition "0 = Abs_perm id"
definition "- p = Abs_perm (inv (Rep_perm p))"
definition "p + q = Abs_perm (Rep_perm p \<circ> Rep_perm q)"
definition "(p1::'a perm) - p2 = p1 + - p2"

lemma Rep_perm_0: "Rep_perm 0 = id"
  unfolding zero_perm_def by (simp add: Abs_perm_inverse)

lemma Rep_perm_add:
  "Rep_perm (p1 + p2) = Rep_perm p1 \<circ> Rep_perm p2"
  unfolding plus_perm_def by (simp add: Abs_perm_inverse Rep_perm)

lemma Rep_perm_uminus:
  "Rep_perm (- p) = inv (Rep_perm p)"
  unfolding uminus_perm_def by (simp add: Abs_perm_inverse perms_inv Rep_perm)

instance
  apply default
  unfolding Rep_perm_inject [symmetric]
  unfolding minus_perm_def
  unfolding Rep_perm_add
  unfolding Rep_perm_uminus
  unfolding Rep_perm_0
  by (simp_all add: o_assoc inv_o_cancel [OF bij_is_inj [OF bij_Rep_perm]])

end

lemmas Rep_perm_simps =
  Rep_perm_0
  Rep_perm_add
  Rep_perm_uminus

section {* Permutation Types *}

text {*We want to be able to apply permutations to arbitrary types. To
this end we introduce a constant @{text PERMUTE} together with
convenient infix syntax.*}

consts PERMUTE :: "'a perm \<Rightarrow> 'b \<Rightarrow> 'b" (infixr "\<bullet>" 75)

text {*Then we add a locale for types @{typ 'b} that support
appliciation of permutations.*}
locale permute =
  fixes permute :: "'a perm \<Rightarrow> 'b \<Rightarrow> 'b"
  assumes permute_zero [simp]: "permute 0 x = x"
    and permute_plus [simp]: "permute (p + q) x = permute p (permute q x)"
begin

adhoc_overloading
  PERMUTE permute

end

text {*Permuting atoms.*}
definition permute_atom :: "'a perm \<Rightarrow> 'a \<Rightarrow> 'a" where
  "permute_atom p a = (Rep_perm p) a"

adhoc_overloading
  PERMUTE permute_atom

interpretation atom_permute: permute permute_atom
  by (default) (simp add: permute_atom_def Rep_perm_simps)+

text {*Permuting permutations.*}
definition permute_perm :: "'a perm \<Rightarrow> 'a perm \<Rightarrow> 'a perm" where
  "permute_perm p q = p + q - p"

adhoc_overloading
  PERMUTE permute_perm

interpretation perm_permute: permute permute_perm
  apply default
  unfolding permute_perm_def
  apply simp
  apply (simp only: diff_conv_add_uminus minus_add add.assoc)
  done

text {*Permuting functions.*}
locale fun_permute =
  dom: permute perm1 + ran: permute perm2
  for perm1 :: "'a perm \<Rightarrow> 'b \<Rightarrow> 'b"
  and perm2 :: "'a perm \<Rightarrow> 'c \<Rightarrow> 'c"
begin

adhoc_overloading
  PERMUTE perm1 perm2

definition permute_fun :: "'a perm \<Rightarrow> ('b \<Rightarrow> 'c) \<Rightarrow> ('b \<Rightarrow> 'c)" where
  "permute_fun p f = (\<lambda>x. p \<bullet> (f (-p \<bullet> x)))"

adhoc_overloading
  PERMUTE permute_fun

end

sublocale fun_permute \<subseteq> permute permute_fun
  by (unfold_locales, auto simp: permute_fun_def)
     (metis dom.permute_plus minus_add)

lemma "(Abs_perm id :: nat perm) \<bullet> Suc 0 = Suc 0"
  unfolding permute_atom_def
  by (metis Rep_perm_0 id_apply zero_perm_def)

interpretation atom_fun_permute: fun_permute permute_atom permute_atom
  by (unfold_locales)

adhoc_overloading
  PERMUTE atom_fun_permute.permute_fun

lemma "(Abs_perm id :: 'a perm) \<bullet> id = id"
  unfolding atom_fun_permute.permute_fun_def
  unfolding permute_atom_def
  by (metis Rep_perm_0 id_def inj_imp_inv_eq inj_on_id uminus_perm_def zero_perm_def)

end