src/HOL/Library/Multiset.thy
author kuncar
Tue Feb 18 23:03:50 2014 +0100 (2014-02-18)
changeset 55565 f663fc1e653b
parent 55467 a5c9002bc54d
child 55808 488c3e8282c8
permissions -rw-r--r--
simplify proofs because of the stronger reflexivity prover
     1 (*  Title:      HOL/Library/Multiset.thy
     2     Author:     Tobias Nipkow, Markus Wenzel, Lawrence C Paulson, Norbert Voelker
     3     Author:     Andrei Popescu, TU Muenchen
     4 *)
     5 
     6 header {* (Finite) multisets *}
     7 
     8 theory Multiset
     9 imports Main
    10 begin
    11 
    12 subsection {* The type of multisets *}
    13 
    14 definition "multiset = {f :: 'a => nat. finite {x. f x > 0}}"
    15 
    16 typedef 'a multiset = "multiset :: ('a => nat) set"
    17   morphisms count Abs_multiset
    18   unfolding multiset_def
    19 proof
    20   show "(\<lambda>x. 0::nat) \<in> {f. finite {x. f x > 0}}" by simp
    21 qed
    22 
    23 setup_lifting type_definition_multiset
    24 
    25 abbreviation Melem :: "'a => 'a multiset => bool"  ("(_/ :# _)" [50, 51] 50) where
    26   "a :# M == 0 < count M a"
    27 
    28 notation (xsymbols)
    29   Melem (infix "\<in>#" 50)
    30 
    31 lemma multiset_eq_iff:
    32   "M = N \<longleftrightarrow> (\<forall>a. count M a = count N a)"
    33   by (simp only: count_inject [symmetric] fun_eq_iff)
    34 
    35 lemma multiset_eqI:
    36   "(\<And>x. count A x = count B x) \<Longrightarrow> A = B"
    37   using multiset_eq_iff by auto
    38 
    39 text {*
    40  \medskip Preservation of the representing set @{term multiset}.
    41 *}
    42 
    43 lemma const0_in_multiset:
    44   "(\<lambda>a. 0) \<in> multiset"
    45   by (simp add: multiset_def)
    46 
    47 lemma only1_in_multiset:
    48   "(\<lambda>b. if b = a then n else 0) \<in> multiset"
    49   by (simp add: multiset_def)
    50 
    51 lemma union_preserves_multiset:
    52   "M \<in> multiset \<Longrightarrow> N \<in> multiset \<Longrightarrow> (\<lambda>a. M a + N a) \<in> multiset"
    53   by (simp add: multiset_def)
    54 
    55 lemma diff_preserves_multiset:
    56   assumes "M \<in> multiset"
    57   shows "(\<lambda>a. M a - N a) \<in> multiset"
    58 proof -
    59   have "{x. N x < M x} \<subseteq> {x. 0 < M x}"
    60     by auto
    61   with assms show ?thesis
    62     by (auto simp add: multiset_def intro: finite_subset)
    63 qed
    64 
    65 lemma filter_preserves_multiset:
    66   assumes "M \<in> multiset"
    67   shows "(\<lambda>x. if P x then M x else 0) \<in> multiset"
    68 proof -
    69   have "{x. (P x \<longrightarrow> 0 < M x) \<and> P x} \<subseteq> {x. 0 < M x}"
    70     by auto
    71   with assms show ?thesis
    72     by (auto simp add: multiset_def intro: finite_subset)
    73 qed
    74 
    75 lemmas in_multiset = const0_in_multiset only1_in_multiset
    76   union_preserves_multiset diff_preserves_multiset filter_preserves_multiset
    77 
    78 
    79 subsection {* Representing multisets *}
    80 
    81 text {* Multiset enumeration *}
    82 
    83 instantiation multiset :: (type) cancel_comm_monoid_add
    84 begin
    85 
    86 lift_definition zero_multiset :: "'a multiset" is "\<lambda>a. 0"
    87 by (rule const0_in_multiset)
    88 
    89 abbreviation Mempty :: "'a multiset" ("{#}") where
    90   "Mempty \<equiv> 0"
    91 
    92 lift_definition plus_multiset :: "'a multiset => 'a multiset => 'a multiset" is "\<lambda>M N. (\<lambda>a. M a + N a)"
    93 by (rule union_preserves_multiset)
    94 
    95 instance
    96 by default (transfer, simp add: fun_eq_iff)+
    97 
    98 end
    99 
   100 lift_definition single :: "'a => 'a multiset" is "\<lambda>a b. if b = a then 1 else 0"
   101 by (rule only1_in_multiset)
   102 
   103 syntax
   104   "_multiset" :: "args => 'a multiset"    ("{#(_)#}")
   105 translations
   106   "{#x, xs#}" == "{#x#} + {#xs#}"
   107   "{#x#}" == "CONST single x"
   108 
   109 lemma count_empty [simp]: "count {#} a = 0"
   110   by (simp add: zero_multiset.rep_eq)
   111 
   112 lemma count_single [simp]: "count {#b#} a = (if b = a then 1 else 0)"
   113   by (simp add: single.rep_eq)
   114 
   115 
   116 subsection {* Basic operations *}
   117 
   118 subsubsection {* Union *}
   119 
   120 lemma count_union [simp]: "count (M + N) a = count M a + count N a"
   121   by (simp add: plus_multiset.rep_eq)
   122 
   123 
   124 subsubsection {* Difference *}
   125 
   126 instantiation multiset :: (type) comm_monoid_diff
   127 begin
   128 
   129 lift_definition minus_multiset :: "'a multiset => 'a multiset => 'a multiset" is "\<lambda> M N. \<lambda>a. M a - N a"
   130 by (rule diff_preserves_multiset)
   131  
   132 instance
   133 by default (transfer, simp add: fun_eq_iff)+
   134 
   135 end
   136 
   137 lemma count_diff [simp]: "count (M - N) a = count M a - count N a"
   138   by (simp add: minus_multiset.rep_eq)
   139 
   140 lemma diff_empty [simp]: "M - {#} = M \<and> {#} - M = {#}"
   141   by rule (fact Groups.diff_zero, fact Groups.zero_diff)
   142 
   143 lemma diff_cancel[simp]: "A - A = {#}"
   144   by (fact Groups.diff_cancel)
   145 
   146 lemma diff_union_cancelR [simp]: "M + N - N = (M::'a multiset)"
   147   by (fact add_diff_cancel_right')
   148 
   149 lemma diff_union_cancelL [simp]: "N + M - N = (M::'a multiset)"
   150   by (fact add_diff_cancel_left')
   151 
   152 lemma diff_right_commute:
   153   "(M::'a multiset) - N - Q = M - Q - N"
   154   by (fact diff_right_commute)
   155 
   156 lemma diff_add:
   157   "(M::'a multiset) - (N + Q) = M - N - Q"
   158   by (rule sym) (fact diff_diff_add)
   159   
   160 lemma insert_DiffM:
   161   "x \<in># M \<Longrightarrow> {#x#} + (M - {#x#}) = M"
   162   by (clarsimp simp: multiset_eq_iff)
   163 
   164 lemma insert_DiffM2 [simp]:
   165   "x \<in># M \<Longrightarrow> M - {#x#} + {#x#} = M"
   166   by (clarsimp simp: multiset_eq_iff)
   167 
   168 lemma diff_union_swap:
   169   "a \<noteq> b \<Longrightarrow> M - {#a#} + {#b#} = M + {#b#} - {#a#}"
   170   by (auto simp add: multiset_eq_iff)
   171 
   172 lemma diff_union_single_conv:
   173   "a \<in># J \<Longrightarrow> I + J - {#a#} = I + (J - {#a#})"
   174   by (simp add: multiset_eq_iff)
   175 
   176 
   177 subsubsection {* Equality of multisets *}
   178 
   179 lemma single_not_empty [simp]: "{#a#} \<noteq> {#} \<and> {#} \<noteq> {#a#}"
   180   by (simp add: multiset_eq_iff)
   181 
   182 lemma single_eq_single [simp]: "{#a#} = {#b#} \<longleftrightarrow> a = b"
   183   by (auto simp add: multiset_eq_iff)
   184 
   185 lemma union_eq_empty [iff]: "M + N = {#} \<longleftrightarrow> M = {#} \<and> N = {#}"
   186   by (auto simp add: multiset_eq_iff)
   187 
   188 lemma empty_eq_union [iff]: "{#} = M + N \<longleftrightarrow> M = {#} \<and> N = {#}"
   189   by (auto simp add: multiset_eq_iff)
   190 
   191 lemma multi_self_add_other_not_self [simp]: "M = M + {#x#} \<longleftrightarrow> False"
   192   by (auto simp add: multiset_eq_iff)
   193 
   194 lemma diff_single_trivial:
   195   "\<not> x \<in># M \<Longrightarrow> M - {#x#} = M"
   196   by (auto simp add: multiset_eq_iff)
   197 
   198 lemma diff_single_eq_union:
   199   "x \<in># M \<Longrightarrow> M - {#x#} = N \<longleftrightarrow> M = N + {#x#}"
   200   by auto
   201 
   202 lemma union_single_eq_diff:
   203   "M + {#x#} = N \<Longrightarrow> M = N - {#x#}"
   204   by (auto dest: sym)
   205 
   206 lemma union_single_eq_member:
   207   "M + {#x#} = N \<Longrightarrow> x \<in># N"
   208   by auto
   209 
   210 lemma union_is_single:
   211   "M + N = {#a#} \<longleftrightarrow> M = {#a#} \<and> N={#} \<or> M = {#} \<and> N = {#a#}" (is "?lhs = ?rhs")
   212 proof
   213   assume ?rhs then show ?lhs by auto
   214 next
   215   assume ?lhs then show ?rhs
   216     by (simp add: multiset_eq_iff split:if_splits) (metis add_is_1)
   217 qed
   218 
   219 lemma single_is_union:
   220   "{#a#} = M + N \<longleftrightarrow> {#a#} = M \<and> N = {#} \<or> M = {#} \<and> {#a#} = N"
   221   by (auto simp add: eq_commute [of "{#a#}" "M + N"] union_is_single)
   222 
   223 lemma add_eq_conv_diff:
   224   "M + {#a#} = N + {#b#} \<longleftrightarrow> M = N \<and> a = b \<or> M = N - {#a#} + {#b#} \<and> N = M - {#b#} + {#a#}"  (is "?lhs = ?rhs")
   225 (* shorter: by (simp add: multiset_eq_iff) fastforce *)
   226 proof
   227   assume ?rhs then show ?lhs
   228   by (auto simp add: add_assoc add_commute [of "{#b#}"])
   229     (drule sym, simp add: add_assoc [symmetric])
   230 next
   231   assume ?lhs
   232   show ?rhs
   233   proof (cases "a = b")
   234     case True with `?lhs` show ?thesis by simp
   235   next
   236     case False
   237     from `?lhs` have "a \<in># N + {#b#}" by (rule union_single_eq_member)
   238     with False have "a \<in># N" by auto
   239     moreover from `?lhs` have "M = N + {#b#} - {#a#}" by (rule union_single_eq_diff)
   240     moreover note False
   241     ultimately show ?thesis by (auto simp add: diff_right_commute [of _ "{#a#}"] diff_union_swap)
   242   qed
   243 qed
   244 
   245 lemma insert_noteq_member: 
   246   assumes BC: "B + {#b#} = C + {#c#}"
   247    and bnotc: "b \<noteq> c"
   248   shows "c \<in># B"
   249 proof -
   250   have "c \<in># C + {#c#}" by simp
   251   have nc: "\<not> c \<in># {#b#}" using bnotc by simp
   252   then have "c \<in># B + {#b#}" using BC by simp
   253   then show "c \<in># B" using nc by simp
   254 qed
   255 
   256 lemma add_eq_conv_ex:
   257   "(M + {#a#} = N + {#b#}) =
   258     (M = N \<and> a = b \<or> (\<exists>K. M = K + {#b#} \<and> N = K + {#a#}))"
   259   by (auto simp add: add_eq_conv_diff)
   260 
   261 lemma multi_member_split:
   262   "x \<in># M \<Longrightarrow> \<exists>A. M = A + {#x#}"
   263   by (rule_tac x = "M - {#x#}" in exI, simp)
   264 
   265 
   266 subsubsection {* Pointwise ordering induced by count *}
   267 
   268 instantiation multiset :: (type) ordered_ab_semigroup_add_imp_le
   269 begin
   270 
   271 lift_definition less_eq_multiset :: "'a multiset \<Rightarrow> 'a multiset \<Rightarrow> bool" is "\<lambda> A B. (\<forall>a. A a \<le> B a)" .
   272 
   273 lemmas mset_le_def = less_eq_multiset_def
   274 
   275 definition less_multiset :: "'a multiset \<Rightarrow> 'a multiset \<Rightarrow> bool" where
   276   mset_less_def: "(A::'a multiset) < B \<longleftrightarrow> A \<le> B \<and> A \<noteq> B"
   277 
   278 instance
   279   by default (auto simp add: mset_le_def mset_less_def multiset_eq_iff intro: order_trans antisym)
   280 
   281 end
   282 
   283 lemma mset_less_eqI:
   284   "(\<And>x. count A x \<le> count B x) \<Longrightarrow> A \<le> B"
   285   by (simp add: mset_le_def)
   286 
   287 lemma mset_le_exists_conv:
   288   "(A::'a multiset) \<le> B \<longleftrightarrow> (\<exists>C. B = A + C)"
   289 apply (unfold mset_le_def, rule iffI, rule_tac x = "B - A" in exI)
   290 apply (auto intro: multiset_eq_iff [THEN iffD2])
   291 done
   292 
   293 instance multiset :: (type) ordered_cancel_comm_monoid_diff
   294   by default (simp, fact mset_le_exists_conv)
   295 
   296 lemma mset_le_mono_add_right_cancel [simp]:
   297   "(A::'a multiset) + C \<le> B + C \<longleftrightarrow> A \<le> B"
   298   by (fact add_le_cancel_right)
   299 
   300 lemma mset_le_mono_add_left_cancel [simp]:
   301   "C + (A::'a multiset) \<le> C + B \<longleftrightarrow> A \<le> B"
   302   by (fact add_le_cancel_left)
   303 
   304 lemma mset_le_mono_add:
   305   "(A::'a multiset) \<le> B \<Longrightarrow> C \<le> D \<Longrightarrow> A + C \<le> B + D"
   306   by (fact add_mono)
   307 
   308 lemma mset_le_add_left [simp]:
   309   "(A::'a multiset) \<le> A + B"
   310   unfolding mset_le_def by auto
   311 
   312 lemma mset_le_add_right [simp]:
   313   "B \<le> (A::'a multiset) + B"
   314   unfolding mset_le_def by auto
   315 
   316 lemma mset_le_single:
   317   "a :# B \<Longrightarrow> {#a#} \<le> B"
   318   by (simp add: mset_le_def)
   319 
   320 lemma multiset_diff_union_assoc:
   321   "C \<le> B \<Longrightarrow> (A::'a multiset) + B - C = A + (B - C)"
   322   by (simp add: multiset_eq_iff mset_le_def)
   323 
   324 lemma mset_le_multiset_union_diff_commute:
   325   "B \<le> A \<Longrightarrow> (A::'a multiset) - B + C = A + C - B"
   326 by (simp add: multiset_eq_iff mset_le_def)
   327 
   328 lemma diff_le_self[simp]: "(M::'a multiset) - N \<le> M"
   329 by(simp add: mset_le_def)
   330 
   331 lemma mset_lessD: "A < B \<Longrightarrow> x \<in># A \<Longrightarrow> x \<in># B"
   332 apply (clarsimp simp: mset_le_def mset_less_def)
   333 apply (erule_tac x=x in allE)
   334 apply auto
   335 done
   336 
   337 lemma mset_leD: "A \<le> B \<Longrightarrow> x \<in># A \<Longrightarrow> x \<in># B"
   338 apply (clarsimp simp: mset_le_def mset_less_def)
   339 apply (erule_tac x = x in allE)
   340 apply auto
   341 done
   342   
   343 lemma mset_less_insertD: "(A + {#x#} < B) \<Longrightarrow> (x \<in># B \<and> A < B)"
   344 apply (rule conjI)
   345  apply (simp add: mset_lessD)
   346 apply (clarsimp simp: mset_le_def mset_less_def)
   347 apply safe
   348  apply (erule_tac x = a in allE)
   349  apply (auto split: split_if_asm)
   350 done
   351 
   352 lemma mset_le_insertD: "(A + {#x#} \<le> B) \<Longrightarrow> (x \<in># B \<and> A \<le> B)"
   353 apply (rule conjI)
   354  apply (simp add: mset_leD)
   355 apply (force simp: mset_le_def mset_less_def split: split_if_asm)
   356 done
   357 
   358 lemma mset_less_of_empty[simp]: "A < {#} \<longleftrightarrow> False"
   359   by (auto simp add: mset_less_def mset_le_def multiset_eq_iff)
   360 
   361 lemma multi_psub_of_add_self[simp]: "A < A + {#x#}"
   362   by (auto simp: mset_le_def mset_less_def)
   363 
   364 lemma multi_psub_self[simp]: "(A::'a multiset) < A = False"
   365   by simp
   366 
   367 lemma mset_less_add_bothsides:
   368   "T + {#x#} < S + {#x#} \<Longrightarrow> T < S"
   369   by (fact add_less_imp_less_right)
   370 
   371 lemma mset_less_empty_nonempty:
   372   "{#} < S \<longleftrightarrow> S \<noteq> {#}"
   373   by (auto simp: mset_le_def mset_less_def)
   374 
   375 lemma mset_less_diff_self:
   376   "c \<in># B \<Longrightarrow> B - {#c#} < B"
   377   by (auto simp: mset_le_def mset_less_def multiset_eq_iff)
   378 
   379 
   380 subsubsection {* Intersection *}
   381 
   382 instantiation multiset :: (type) semilattice_inf
   383 begin
   384 
   385 definition inf_multiset :: "'a multiset \<Rightarrow> 'a multiset \<Rightarrow> 'a multiset" where
   386   multiset_inter_def: "inf_multiset A B = A - (A - B)"
   387 
   388 instance
   389 proof -
   390   have aux: "\<And>m n q :: nat. m \<le> n \<Longrightarrow> m \<le> q \<Longrightarrow> m \<le> n - (n - q)" by arith
   391   show "OFCLASS('a multiset, semilattice_inf_class)"
   392     by default (auto simp add: multiset_inter_def mset_le_def aux)
   393 qed
   394 
   395 end
   396 
   397 abbreviation multiset_inter :: "'a multiset \<Rightarrow> 'a multiset \<Rightarrow> 'a multiset" (infixl "#\<inter>" 70) where
   398   "multiset_inter \<equiv> inf"
   399 
   400 lemma multiset_inter_count [simp]:
   401   "count (A #\<inter> B) x = min (count A x) (count B x)"
   402   by (simp add: multiset_inter_def)
   403 
   404 lemma multiset_inter_single: "a \<noteq> b \<Longrightarrow> {#a#} #\<inter> {#b#} = {#}"
   405   by (rule multiset_eqI) auto
   406 
   407 lemma multiset_union_diff_commute:
   408   assumes "B #\<inter> C = {#}"
   409   shows "A + B - C = A - C + B"
   410 proof (rule multiset_eqI)
   411   fix x
   412   from assms have "min (count B x) (count C x) = 0"
   413     by (auto simp add: multiset_eq_iff)
   414   then have "count B x = 0 \<or> count C x = 0"
   415     by auto
   416   then show "count (A + B - C) x = count (A - C + B) x"
   417     by auto
   418 qed
   419 
   420 lemma empty_inter [simp]:
   421   "{#} #\<inter> M = {#}"
   422   by (simp add: multiset_eq_iff)
   423 
   424 lemma inter_empty [simp]:
   425   "M #\<inter> {#} = {#}"
   426   by (simp add: multiset_eq_iff)
   427 
   428 lemma inter_add_left1:
   429   "\<not> x \<in># N \<Longrightarrow> (M + {#x#}) #\<inter> N = M #\<inter> N"
   430   by (simp add: multiset_eq_iff)
   431 
   432 lemma inter_add_left2:
   433   "x \<in># N \<Longrightarrow> (M + {#x#}) #\<inter> N = (M #\<inter> (N - {#x#})) + {#x#}"
   434   by (simp add: multiset_eq_iff)
   435 
   436 lemma inter_add_right1:
   437   "\<not> x \<in># N \<Longrightarrow> N #\<inter> (M + {#x#}) = N #\<inter> M"
   438   by (simp add: multiset_eq_iff)
   439 
   440 lemma inter_add_right2:
   441   "x \<in># N \<Longrightarrow> N #\<inter> (M + {#x#}) = ((N - {#x#}) #\<inter> M) + {#x#}"
   442   by (simp add: multiset_eq_iff)
   443 
   444 
   445 subsubsection {* Bounded union *}
   446 
   447 instantiation multiset :: (type) semilattice_sup
   448 begin
   449 
   450 definition sup_multiset :: "'a multiset \<Rightarrow> 'a multiset \<Rightarrow> 'a multiset" where
   451   "sup_multiset A B = A + (B - A)"
   452 
   453 instance
   454 proof -
   455   have aux: "\<And>m n q :: nat. m \<le> n \<Longrightarrow> q \<le> n \<Longrightarrow> m + (q - m) \<le> n" by arith
   456   show "OFCLASS('a multiset, semilattice_sup_class)"
   457     by default (auto simp add: sup_multiset_def mset_le_def aux)
   458 qed
   459 
   460 end
   461 
   462 abbreviation sup_multiset :: "'a multiset \<Rightarrow> 'a multiset \<Rightarrow> 'a multiset" (infixl "#\<union>" 70) where
   463   "sup_multiset \<equiv> sup"
   464 
   465 lemma sup_multiset_count [simp]:
   466   "count (A #\<union> B) x = max (count A x) (count B x)"
   467   by (simp add: sup_multiset_def)
   468 
   469 lemma empty_sup [simp]:
   470   "{#} #\<union> M = M"
   471   by (simp add: multiset_eq_iff)
   472 
   473 lemma sup_empty [simp]:
   474   "M #\<union> {#} = M"
   475   by (simp add: multiset_eq_iff)
   476 
   477 lemma sup_add_left1:
   478   "\<not> x \<in># N \<Longrightarrow> (M + {#x#}) #\<union> N = (M #\<union> N) + {#x#}"
   479   by (simp add: multiset_eq_iff)
   480 
   481 lemma sup_add_left2:
   482   "x \<in># N \<Longrightarrow> (M + {#x#}) #\<union> N = (M #\<union> (N - {#x#})) + {#x#}"
   483   by (simp add: multiset_eq_iff)
   484 
   485 lemma sup_add_right1:
   486   "\<not> x \<in># N \<Longrightarrow> N #\<union> (M + {#x#}) = (N #\<union> M) + {#x#}"
   487   by (simp add: multiset_eq_iff)
   488 
   489 lemma sup_add_right2:
   490   "x \<in># N \<Longrightarrow> N #\<union> (M + {#x#}) = ((N - {#x#}) #\<union> M) + {#x#}"
   491   by (simp add: multiset_eq_iff)
   492 
   493 
   494 subsubsection {* Filter (with comprehension syntax) *}
   495 
   496 text {* Multiset comprehension *}
   497 
   498 lift_definition filter :: "('a \<Rightarrow> bool) \<Rightarrow> 'a multiset \<Rightarrow> 'a multiset" is "\<lambda>P M. \<lambda>x. if P x then M x else 0"
   499 by (rule filter_preserves_multiset)
   500 
   501 hide_const (open) filter
   502 
   503 lemma count_filter [simp]:
   504   "count (Multiset.filter P M) a = (if P a then count M a else 0)"
   505   by (simp add: filter.rep_eq)
   506 
   507 lemma filter_empty [simp]:
   508   "Multiset.filter P {#} = {#}"
   509   by (rule multiset_eqI) simp
   510 
   511 lemma filter_single [simp]:
   512   "Multiset.filter P {#x#} = (if P x then {#x#} else {#})"
   513   by (rule multiset_eqI) simp
   514 
   515 lemma filter_union [simp]:
   516   "Multiset.filter P (M + N) = Multiset.filter P M + Multiset.filter P N"
   517   by (rule multiset_eqI) simp
   518 
   519 lemma filter_diff [simp]:
   520   "Multiset.filter P (M - N) = Multiset.filter P M - Multiset.filter P N"
   521   by (rule multiset_eqI) simp
   522 
   523 lemma filter_inter [simp]:
   524   "Multiset.filter P (M #\<inter> N) = Multiset.filter P M #\<inter> Multiset.filter P N"
   525   by (rule multiset_eqI) simp
   526 
   527 syntax
   528   "_MCollect" :: "pttrn \<Rightarrow> 'a multiset \<Rightarrow> bool \<Rightarrow> 'a multiset"    ("(1{# _ :# _./ _#})")
   529 syntax (xsymbol)
   530   "_MCollect" :: "pttrn \<Rightarrow> 'a multiset \<Rightarrow> bool \<Rightarrow> 'a multiset"    ("(1{# _ \<in># _./ _#})")
   531 translations
   532   "{#x \<in># M. P#}" == "CONST Multiset.filter (\<lambda>x. P) M"
   533 
   534 
   535 subsubsection {* Set of elements *}
   536 
   537 definition set_of :: "'a multiset => 'a set" where
   538   "set_of M = {x. x :# M}"
   539 
   540 lemma set_of_empty [simp]: "set_of {#} = {}"
   541 by (simp add: set_of_def)
   542 
   543 lemma set_of_single [simp]: "set_of {#b#} = {b}"
   544 by (simp add: set_of_def)
   545 
   546 lemma set_of_union [simp]: "set_of (M + N) = set_of M \<union> set_of N"
   547 by (auto simp add: set_of_def)
   548 
   549 lemma set_of_eq_empty_iff [simp]: "(set_of M = {}) = (M = {#})"
   550 by (auto simp add: set_of_def multiset_eq_iff)
   551 
   552 lemma mem_set_of_iff [simp]: "(x \<in> set_of M) = (x :# M)"
   553 by (auto simp add: set_of_def)
   554 
   555 lemma set_of_filter [simp]: "set_of {# x:#M. P x #} = set_of M \<inter> {x. P x}"
   556 by (auto simp add: set_of_def)
   557 
   558 lemma finite_set_of [iff]: "finite (set_of M)"
   559   using count [of M] by (simp add: multiset_def set_of_def)
   560 
   561 lemma finite_Collect_mem [iff]: "finite {x. x :# M}"
   562   unfolding set_of_def[symmetric] by simp
   563 
   564 subsubsection {* Size *}
   565 
   566 instantiation multiset :: (type) size
   567 begin
   568 
   569 definition size_def:
   570   "size M = setsum (count M) (set_of M)"
   571 
   572 instance ..
   573 
   574 end
   575 
   576 lemma size_empty [simp]: "size {#} = 0"
   577 by (simp add: size_def)
   578 
   579 lemma size_single [simp]: "size {#b#} = 1"
   580 by (simp add: size_def)
   581 
   582 lemma setsum_count_Int:
   583   "finite A ==> setsum (count N) (A \<inter> set_of N) = setsum (count N) A"
   584 apply (induct rule: finite_induct)
   585  apply simp
   586 apply (simp add: Int_insert_left set_of_def)
   587 done
   588 
   589 lemma size_union [simp]: "size (M + N::'a multiset) = size M + size N"
   590 apply (unfold size_def)
   591 apply (subgoal_tac "count (M + N) = (\<lambda>a. count M a + count N a)")
   592  prefer 2
   593  apply (rule ext, simp)
   594 apply (simp (no_asm_simp) add: setsum_Un_nat setsum_addf setsum_count_Int)
   595 apply (subst Int_commute)
   596 apply (simp (no_asm_simp) add: setsum_count_Int)
   597 done
   598 
   599 lemma size_eq_0_iff_empty [iff]: "(size M = 0) = (M = {#})"
   600 by (auto simp add: size_def multiset_eq_iff)
   601 
   602 lemma nonempty_has_size: "(S \<noteq> {#}) = (0 < size S)"
   603 by (metis gr0I gr_implies_not0 size_empty size_eq_0_iff_empty)
   604 
   605 lemma size_eq_Suc_imp_elem: "size M = Suc n ==> \<exists>a. a :# M"
   606 apply (unfold size_def)
   607 apply (drule setsum_SucD)
   608 apply auto
   609 done
   610 
   611 lemma size_eq_Suc_imp_eq_union:
   612   assumes "size M = Suc n"
   613   shows "\<exists>a N. M = N + {#a#}"
   614 proof -
   615   from assms obtain a where "a \<in># M"
   616     by (erule size_eq_Suc_imp_elem [THEN exE])
   617   then have "M = M - {#a#} + {#a#}" by simp
   618   then show ?thesis by blast
   619 qed
   620 
   621 
   622 subsection {* Induction and case splits *}
   623 
   624 theorem multiset_induct [case_names empty add, induct type: multiset]:
   625   assumes empty: "P {#}"
   626   assumes add: "\<And>M x. P M \<Longrightarrow> P (M + {#x#})"
   627   shows "P M"
   628 proof (induct n \<equiv> "size M" arbitrary: M)
   629   case 0 thus "P M" by (simp add: empty)
   630 next
   631   case (Suc k)
   632   obtain N x where "M = N + {#x#}"
   633     using `Suc k = size M` [symmetric]
   634     using size_eq_Suc_imp_eq_union by fast
   635   with Suc add show "P M" by simp
   636 qed
   637 
   638 lemma multi_nonempty_split: "M \<noteq> {#} \<Longrightarrow> \<exists>A a. M = A + {#a#}"
   639 by (induct M) auto
   640 
   641 lemma multiset_cases [cases type, case_names empty add]:
   642 assumes em:  "M = {#} \<Longrightarrow> P"
   643 assumes add: "\<And>N x. M = N + {#x#} \<Longrightarrow> P"
   644 shows "P"
   645 using assms by (induct M) simp_all
   646 
   647 lemma multi_drop_mem_not_eq: "c \<in># B \<Longrightarrow> B - {#c#} \<noteq> B"
   648 by (cases "B = {#}") (auto dest: multi_member_split)
   649 
   650 lemma multiset_partition: "M = {# x:#M. P x #} + {# x:#M. \<not> P x #}"
   651 apply (subst multiset_eq_iff)
   652 apply auto
   653 done
   654 
   655 lemma mset_less_size: "(A::'a multiset) < B \<Longrightarrow> size A < size B"
   656 proof (induct A arbitrary: B)
   657   case (empty M)
   658   then have "M \<noteq> {#}" by (simp add: mset_less_empty_nonempty)
   659   then obtain M' x where "M = M' + {#x#}" 
   660     by (blast dest: multi_nonempty_split)
   661   then show ?case by simp
   662 next
   663   case (add S x T)
   664   have IH: "\<And>B. S < B \<Longrightarrow> size S < size B" by fact
   665   have SxsubT: "S + {#x#} < T" by fact
   666   then have "x \<in># T" and "S < T" by (auto dest: mset_less_insertD)
   667   then obtain T' where T: "T = T' + {#x#}" 
   668     by (blast dest: multi_member_split)
   669   then have "S < T'" using SxsubT 
   670     by (blast intro: mset_less_add_bothsides)
   671   then have "size S < size T'" using IH by simp
   672   then show ?case using T by simp
   673 qed
   674 
   675 
   676 subsubsection {* Strong induction and subset induction for multisets *}
   677 
   678 text {* Well-foundedness of proper subset operator: *}
   679 
   680 text {* proper multiset subset *}
   681 
   682 definition
   683   mset_less_rel :: "('a multiset * 'a multiset) set" where
   684   "mset_less_rel = {(A,B). A < B}"
   685 
   686 lemma multiset_add_sub_el_shuffle: 
   687   assumes "c \<in># B" and "b \<noteq> c" 
   688   shows "B - {#c#} + {#b#} = B + {#b#} - {#c#}"
   689 proof -
   690   from `c \<in># B` obtain A where B: "B = A + {#c#}" 
   691     by (blast dest: multi_member_split)
   692   have "A + {#b#} = A + {#b#} + {#c#} - {#c#}" by simp
   693   then have "A + {#b#} = A + {#c#} + {#b#} - {#c#}" 
   694     by (simp add: add_ac)
   695   then show ?thesis using B by simp
   696 qed
   697 
   698 lemma wf_mset_less_rel: "wf mset_less_rel"
   699 apply (unfold mset_less_rel_def)
   700 apply (rule wf_measure [THEN wf_subset, where f1=size])
   701 apply (clarsimp simp: measure_def inv_image_def mset_less_size)
   702 done
   703 
   704 text {* The induction rules: *}
   705 
   706 lemma full_multiset_induct [case_names less]:
   707 assumes ih: "\<And>B. \<forall>(A::'a multiset). A < B \<longrightarrow> P A \<Longrightarrow> P B"
   708 shows "P B"
   709 apply (rule wf_mset_less_rel [THEN wf_induct])
   710 apply (rule ih, auto simp: mset_less_rel_def)
   711 done
   712 
   713 lemma multi_subset_induct [consumes 2, case_names empty add]:
   714 assumes "F \<le> A"
   715   and empty: "P {#}"
   716   and insert: "\<And>a F. a \<in># A \<Longrightarrow> P F \<Longrightarrow> P (F + {#a#})"
   717 shows "P F"
   718 proof -
   719   from `F \<le> A`
   720   show ?thesis
   721   proof (induct F)
   722     show "P {#}" by fact
   723   next
   724     fix x F
   725     assume P: "F \<le> A \<Longrightarrow> P F" and i: "F + {#x#} \<le> A"
   726     show "P (F + {#x#})"
   727     proof (rule insert)
   728       from i show "x \<in># A" by (auto dest: mset_le_insertD)
   729       from i have "F \<le> A" by (auto dest: mset_le_insertD)
   730       with P show "P F" .
   731     qed
   732   qed
   733 qed
   734 
   735 
   736 subsection {* The fold combinator *}
   737 
   738 definition fold :: "('a \<Rightarrow> 'b \<Rightarrow> 'b) \<Rightarrow> 'b \<Rightarrow> 'a multiset \<Rightarrow> 'b"
   739 where
   740   "fold f s M = Finite_Set.fold (\<lambda>x. f x ^^ count M x) s (set_of M)"
   741 
   742 lemma fold_mset_empty [simp]:
   743   "fold f s {#} = s"
   744   by (simp add: fold_def)
   745 
   746 context comp_fun_commute
   747 begin
   748 
   749 lemma fold_mset_insert:
   750   "fold f s (M + {#x#}) = f x (fold f s M)"
   751 proof -
   752   interpret mset: comp_fun_commute "\<lambda>y. f y ^^ count M y"
   753     by (fact comp_fun_commute_funpow)
   754   interpret mset_union: comp_fun_commute "\<lambda>y. f y ^^ count (M + {#x#}) y"
   755     by (fact comp_fun_commute_funpow)
   756   show ?thesis
   757   proof (cases "x \<in> set_of M")
   758     case False
   759     then have *: "count (M + {#x#}) x = 1" by simp
   760     from False have "Finite_Set.fold (\<lambda>y. f y ^^ count (M + {#x#}) y) s (set_of M) =
   761       Finite_Set.fold (\<lambda>y. f y ^^ count M y) s (set_of M)"
   762       by (auto intro!: Finite_Set.fold_cong comp_fun_commute_funpow)
   763     with False * show ?thesis
   764       by (simp add: fold_def del: count_union)
   765   next
   766     case True
   767     def N \<equiv> "set_of M - {x}"
   768     from N_def True have *: "set_of M = insert x N" "x \<notin> N" "finite N" by auto
   769     then have "Finite_Set.fold (\<lambda>y. f y ^^ count (M + {#x#}) y) s N =
   770       Finite_Set.fold (\<lambda>y. f y ^^ count M y) s N"
   771       by (auto intro!: Finite_Set.fold_cong comp_fun_commute_funpow)
   772     with * show ?thesis by (simp add: fold_def del: count_union) simp
   773   qed
   774 qed
   775 
   776 corollary fold_mset_single [simp]:
   777   "fold f s {#x#} = f x s"
   778 proof -
   779   have "fold f s ({#} + {#x#}) = f x s" by (simp only: fold_mset_insert) simp
   780   then show ?thesis by simp
   781 qed
   782 
   783 lemma fold_mset_fun_left_comm:
   784   "f x (fold f s M) = fold f (f x s) M"
   785   by (induct M) (simp_all add: fold_mset_insert fun_left_comm)
   786 
   787 lemma fold_mset_union [simp]:
   788   "fold f s (M + N) = fold f (fold f s M) N"
   789 proof (induct M)
   790   case empty then show ?case by simp
   791 next
   792   case (add M x)
   793   have "M + {#x#} + N = (M + N) + {#x#}"
   794     by (simp add: add_ac)
   795   with add show ?case by (simp add: fold_mset_insert fold_mset_fun_left_comm)
   796 qed
   797 
   798 lemma fold_mset_fusion:
   799   assumes "comp_fun_commute g"
   800   shows "(\<And>x y. h (g x y) = f x (h y)) \<Longrightarrow> h (fold g w A) = fold f (h w) A" (is "PROP ?P")
   801 proof -
   802   interpret comp_fun_commute g by (fact assms)
   803   show "PROP ?P" by (induct A) auto
   804 qed
   805 
   806 end
   807 
   808 text {*
   809   A note on code generation: When defining some function containing a
   810   subterm @{term "fold F"}, code generation is not automatic. When
   811   interpreting locale @{text left_commutative} with @{text F}, the
   812   would be code thms for @{const fold} become thms like
   813   @{term "fold F z {#} = z"} where @{text F} is not a pattern but
   814   contains defined symbols, i.e.\ is not a code thm. Hence a separate
   815   constant with its own code thms needs to be introduced for @{text
   816   F}. See the image operator below.
   817 *}
   818 
   819 
   820 subsection {* Image *}
   821 
   822 definition image_mset :: "('a \<Rightarrow> 'b) \<Rightarrow> 'a multiset \<Rightarrow> 'b multiset" where
   823   "image_mset f = fold (plus o single o f) {#}"
   824 
   825 lemma comp_fun_commute_mset_image:
   826   "comp_fun_commute (plus o single o f)"
   827 proof
   828 qed (simp add: add_ac fun_eq_iff)
   829 
   830 lemma image_mset_empty [simp]: "image_mset f {#} = {#}"
   831   by (simp add: image_mset_def)
   832 
   833 lemma image_mset_single [simp]: "image_mset f {#x#} = {#f x#}"
   834 proof -
   835   interpret comp_fun_commute "plus o single o f"
   836     by (fact comp_fun_commute_mset_image)
   837   show ?thesis by (simp add: image_mset_def)
   838 qed
   839 
   840 lemma image_mset_union [simp]:
   841   "image_mset f (M + N) = image_mset f M + image_mset f N"
   842 proof -
   843   interpret comp_fun_commute "plus o single o f"
   844     by (fact comp_fun_commute_mset_image)
   845   show ?thesis by (induct N) (simp_all add: image_mset_def add_ac)
   846 qed
   847 
   848 corollary image_mset_insert:
   849   "image_mset f (M + {#a#}) = image_mset f M + {#f a#}"
   850   by simp
   851 
   852 lemma set_of_image_mset [simp]:
   853   "set_of (image_mset f M) = image f (set_of M)"
   854   by (induct M) simp_all
   855 
   856 lemma size_image_mset [simp]:
   857   "size (image_mset f M) = size M"
   858   by (induct M) simp_all
   859 
   860 lemma image_mset_is_empty_iff [simp]:
   861   "image_mset f M = {#} \<longleftrightarrow> M = {#}"
   862   by (cases M) auto
   863 
   864 syntax
   865   "_comprehension1_mset" :: "'a \<Rightarrow> 'b \<Rightarrow> 'b multiset \<Rightarrow> 'a multiset"
   866       ("({#_/. _ :# _#})")
   867 translations
   868   "{#e. x:#M#}" == "CONST image_mset (%x. e) M"
   869 
   870 syntax
   871   "_comprehension2_mset" :: "'a \<Rightarrow> 'b \<Rightarrow> 'b multiset \<Rightarrow> bool \<Rightarrow> 'a multiset"
   872       ("({#_/ | _ :# _./ _#})")
   873 translations
   874   "{#e | x:#M. P#}" => "{#e. x :# {# x:#M. P#}#}"
   875 
   876 text {*
   877   This allows to write not just filters like @{term "{#x:#M. x<c#}"}
   878   but also images like @{term "{#x+x. x:#M #}"} and @{term [source]
   879   "{#x+x|x:#M. x<c#}"}, where the latter is currently displayed as
   880   @{term "{#x+x|x:#M. x<c#}"}.
   881 *}
   882 
   883 functor image_mset: image_mset
   884 proof -
   885   fix f g show "image_mset f \<circ> image_mset g = image_mset (f \<circ> g)"
   886   proof
   887     fix A
   888     show "(image_mset f \<circ> image_mset g) A = image_mset (f \<circ> g) A"
   889       by (induct A) simp_all
   890   qed
   891   show "image_mset id = id"
   892   proof
   893     fix A
   894     show "image_mset id A = id A"
   895       by (induct A) simp_all
   896   qed
   897 qed
   898 
   899 declare image_mset.identity [simp]
   900 
   901 
   902 subsection {* Further conversions *}
   903 
   904 primrec multiset_of :: "'a list \<Rightarrow> 'a multiset" where
   905   "multiset_of [] = {#}" |
   906   "multiset_of (a # x) = multiset_of x + {# a #}"
   907 
   908 lemma in_multiset_in_set:
   909   "x \<in># multiset_of xs \<longleftrightarrow> x \<in> set xs"
   910   by (induct xs) simp_all
   911 
   912 lemma count_multiset_of:
   913   "count (multiset_of xs) x = length (filter (\<lambda>y. x = y) xs)"
   914   by (induct xs) simp_all
   915 
   916 lemma multiset_of_zero_iff[simp]: "(multiset_of x = {#}) = (x = [])"
   917 by (induct x) auto
   918 
   919 lemma multiset_of_zero_iff_right[simp]: "({#} = multiset_of x) = (x = [])"
   920 by (induct x) auto
   921 
   922 lemma set_of_multiset_of[simp]: "set_of (multiset_of x) = set x"
   923 by (induct x) auto
   924 
   925 lemma mem_set_multiset_eq: "x \<in> set xs = (x :# multiset_of xs)"
   926 by (induct xs) auto
   927 
   928 lemma size_multiset_of [simp]: "size (multiset_of xs) = length xs"
   929   by (induct xs) simp_all
   930 
   931 lemma multiset_of_append [simp]:
   932   "multiset_of (xs @ ys) = multiset_of xs + multiset_of ys"
   933   by (induct xs arbitrary: ys) (auto simp: add_ac)
   934 
   935 lemma multiset_of_filter:
   936   "multiset_of (filter P xs) = {#x :# multiset_of xs. P x #}"
   937   by (induct xs) simp_all
   938 
   939 lemma multiset_of_rev [simp]:
   940   "multiset_of (rev xs) = multiset_of xs"
   941   by (induct xs) simp_all
   942 
   943 lemma surj_multiset_of: "surj multiset_of"
   944 apply (unfold surj_def)
   945 apply (rule allI)
   946 apply (rule_tac M = y in multiset_induct)
   947  apply auto
   948 apply (rule_tac x = "x # xa" in exI)
   949 apply auto
   950 done
   951 
   952 lemma set_count_greater_0: "set x = {a. count (multiset_of x) a > 0}"
   953 by (induct x) auto
   954 
   955 lemma distinct_count_atmost_1:
   956   "distinct x = (! a. count (multiset_of x) a = (if a \<in> set x then 1 else 0))"
   957 apply (induct x, simp, rule iffI, simp_all)
   958 apply (rename_tac a b)
   959 apply (rule conjI)
   960 apply (simp_all add: set_of_multiset_of [THEN sym] del: set_of_multiset_of)
   961 apply (erule_tac x = a in allE, simp, clarify)
   962 apply (erule_tac x = aa in allE, simp)
   963 done
   964 
   965 lemma multiset_of_eq_setD:
   966   "multiset_of xs = multiset_of ys \<Longrightarrow> set xs = set ys"
   967 by (rule) (auto simp add:multiset_eq_iff set_count_greater_0)
   968 
   969 lemma set_eq_iff_multiset_of_eq_distinct:
   970   "distinct x \<Longrightarrow> distinct y \<Longrightarrow>
   971     (set x = set y) = (multiset_of x = multiset_of y)"
   972 by (auto simp: multiset_eq_iff distinct_count_atmost_1)
   973 
   974 lemma set_eq_iff_multiset_of_remdups_eq:
   975    "(set x = set y) = (multiset_of (remdups x) = multiset_of (remdups y))"
   976 apply (rule iffI)
   977 apply (simp add: set_eq_iff_multiset_of_eq_distinct[THEN iffD1])
   978 apply (drule distinct_remdups [THEN distinct_remdups
   979       [THEN set_eq_iff_multiset_of_eq_distinct [THEN iffD2]]])
   980 apply simp
   981 done
   982 
   983 lemma multiset_of_compl_union [simp]:
   984   "multiset_of [x\<leftarrow>xs. P x] + multiset_of [x\<leftarrow>xs. \<not>P x] = multiset_of xs"
   985   by (induct xs) (auto simp: add_ac)
   986 
   987 lemma count_multiset_of_length_filter:
   988   "count (multiset_of xs) x = length (filter (\<lambda>y. x = y) xs)"
   989   by (induct xs) auto
   990 
   991 lemma nth_mem_multiset_of: "i < length ls \<Longrightarrow> (ls ! i) :# multiset_of ls"
   992 apply (induct ls arbitrary: i)
   993  apply simp
   994 apply (case_tac i)
   995  apply auto
   996 done
   997 
   998 lemma multiset_of_remove1[simp]:
   999   "multiset_of (remove1 a xs) = multiset_of xs - {#a#}"
  1000 by (induct xs) (auto simp add: multiset_eq_iff)
  1001 
  1002 lemma multiset_of_eq_length:
  1003   assumes "multiset_of xs = multiset_of ys"
  1004   shows "length xs = length ys"
  1005   using assms by (metis size_multiset_of)
  1006 
  1007 lemma multiset_of_eq_length_filter:
  1008   assumes "multiset_of xs = multiset_of ys"
  1009   shows "length (filter (\<lambda>x. z = x) xs) = length (filter (\<lambda>y. z = y) ys)"
  1010   using assms by (metis count_multiset_of)
  1011 
  1012 lemma fold_multiset_equiv:
  1013   assumes f: "\<And>x y. x \<in> set xs \<Longrightarrow> y \<in> set xs \<Longrightarrow> f x \<circ> f y = f y \<circ> f x"
  1014     and equiv: "multiset_of xs = multiset_of ys"
  1015   shows "List.fold f xs = List.fold f ys"
  1016 using f equiv [symmetric]
  1017 proof (induct xs arbitrary: ys)
  1018   case Nil then show ?case by simp
  1019 next
  1020   case (Cons x xs)
  1021   then have *: "set ys = set (x # xs)" by (blast dest: multiset_of_eq_setD)
  1022   have "\<And>x y. x \<in> set ys \<Longrightarrow> y \<in> set ys \<Longrightarrow> f x \<circ> f y = f y \<circ> f x" 
  1023     by (rule Cons.prems(1)) (simp_all add: *)
  1024   moreover from * have "x \<in> set ys" by simp
  1025   ultimately have "List.fold f ys = List.fold f (remove1 x ys) \<circ> f x" by (fact fold_remove1_split)
  1026   moreover from Cons.prems have "List.fold f xs = List.fold f (remove1 x ys)" by (auto intro: Cons.hyps)
  1027   ultimately show ?case by simp
  1028 qed
  1029 
  1030 lemma multiset_of_insort [simp]:
  1031   "multiset_of (insort x xs) = multiset_of xs + {#x#}"
  1032   by (induct xs) (simp_all add: ac_simps)
  1033 
  1034 lemma in_multiset_of:
  1035   "x \<in># multiset_of xs \<longleftrightarrow> x \<in> set xs"
  1036   by (induct xs) simp_all
  1037 
  1038 lemma multiset_of_map:
  1039   "multiset_of (map f xs) = image_mset f (multiset_of xs)"
  1040   by (induct xs) simp_all
  1041 
  1042 definition multiset_of_set :: "'a set \<Rightarrow> 'a multiset"
  1043 where
  1044   "multiset_of_set = folding.F (\<lambda>x M. {#x#} + M) {#}"
  1045 
  1046 interpretation multiset_of_set!: folding "\<lambda>x M. {#x#} + M" "{#}"
  1047 where
  1048   "folding.F (\<lambda>x M. {#x#} + M) {#} = multiset_of_set"
  1049 proof -
  1050   interpret comp_fun_commute "\<lambda>x M. {#x#} + M" by default (simp add: fun_eq_iff ac_simps)
  1051   show "folding (\<lambda>x M. {#x#} + M)" by default (fact comp_fun_commute)
  1052   from multiset_of_set_def show "folding.F (\<lambda>x M. {#x#} + M) {#} = multiset_of_set" ..
  1053 qed
  1054 
  1055 lemma count_multiset_of_set [simp]:
  1056   "finite A \<Longrightarrow> x \<in> A \<Longrightarrow> count (multiset_of_set A) x = 1" (is "PROP ?P")
  1057   "\<not> finite A \<Longrightarrow> count (multiset_of_set A) x = 0" (is "PROP ?Q")
  1058   "x \<notin> A \<Longrightarrow> count (multiset_of_set A) x = 0" (is "PROP ?R")
  1059 proof -
  1060   { fix A
  1061     assume "x \<notin> A"
  1062     have "count (multiset_of_set A) x = 0"
  1063     proof (cases "finite A")
  1064       case False then show ?thesis by simp
  1065     next
  1066       case True from True `x \<notin> A` show ?thesis by (induct A) auto
  1067     qed
  1068   } note * = this
  1069   then show "PROP ?P" "PROP ?Q" "PROP ?R"
  1070   by (auto elim!: Set.set_insert)
  1071 qed -- {* TODO: maybe define @{const multiset_of_set} also in terms of @{const Abs_multiset} *}
  1072 
  1073 context linorder
  1074 begin
  1075 
  1076 definition sorted_list_of_multiset :: "'a multiset \<Rightarrow> 'a list"
  1077 where
  1078   "sorted_list_of_multiset M = fold insort [] M"
  1079 
  1080 lemma sorted_list_of_multiset_empty [simp]:
  1081   "sorted_list_of_multiset {#} = []"
  1082   by (simp add: sorted_list_of_multiset_def)
  1083 
  1084 lemma sorted_list_of_multiset_singleton [simp]:
  1085   "sorted_list_of_multiset {#x#} = [x]"
  1086 proof -
  1087   interpret comp_fun_commute insort by (fact comp_fun_commute_insort)
  1088   show ?thesis by (simp add: sorted_list_of_multiset_def)
  1089 qed
  1090 
  1091 lemma sorted_list_of_multiset_insert [simp]:
  1092   "sorted_list_of_multiset (M + {#x#}) = List.insort x (sorted_list_of_multiset M)"
  1093 proof -
  1094   interpret comp_fun_commute insort by (fact comp_fun_commute_insort)
  1095   show ?thesis by (simp add: sorted_list_of_multiset_def)
  1096 qed
  1097 
  1098 end
  1099 
  1100 lemma multiset_of_sorted_list_of_multiset [simp]:
  1101   "multiset_of (sorted_list_of_multiset M) = M"
  1102   by (induct M) simp_all
  1103 
  1104 lemma sorted_list_of_multiset_multiset_of [simp]:
  1105   "sorted_list_of_multiset (multiset_of xs) = sort xs"
  1106   by (induct xs) simp_all
  1107 
  1108 lemma finite_set_of_multiset_of_set:
  1109   assumes "finite A"
  1110   shows "set_of (multiset_of_set A) = A"
  1111   using assms by (induct A) simp_all
  1112 
  1113 lemma infinite_set_of_multiset_of_set:
  1114   assumes "\<not> finite A"
  1115   shows "set_of (multiset_of_set A) = {}"
  1116   using assms by simp
  1117 
  1118 lemma set_sorted_list_of_multiset [simp]:
  1119   "set (sorted_list_of_multiset M) = set_of M"
  1120   by (induct M) (simp_all add: set_insort)
  1121 
  1122 lemma sorted_list_of_multiset_of_set [simp]:
  1123   "sorted_list_of_multiset (multiset_of_set A) = sorted_list_of_set A"
  1124   by (cases "finite A") (induct A rule: finite_induct, simp_all add: ac_simps)
  1125 
  1126 
  1127 subsection {* Big operators *}
  1128 
  1129 no_notation times (infixl "*" 70)
  1130 no_notation Groups.one ("1")
  1131 
  1132 locale comm_monoid_mset = comm_monoid
  1133 begin
  1134 
  1135 definition F :: "'a multiset \<Rightarrow> 'a"
  1136 where
  1137   eq_fold: "F M = Multiset.fold f 1 M"
  1138 
  1139 lemma empty [simp]:
  1140   "F {#} = 1"
  1141   by (simp add: eq_fold)
  1142 
  1143 lemma singleton [simp]:
  1144   "F {#x#} = x"
  1145 proof -
  1146   interpret comp_fun_commute
  1147     by default (simp add: fun_eq_iff left_commute)
  1148   show ?thesis by (simp add: eq_fold)
  1149 qed
  1150 
  1151 lemma union [simp]:
  1152   "F (M + N) = F M * F N"
  1153 proof -
  1154   interpret comp_fun_commute f
  1155     by default (simp add: fun_eq_iff left_commute)
  1156   show ?thesis by (induct N) (simp_all add: left_commute eq_fold)
  1157 qed
  1158 
  1159 end
  1160 
  1161 notation times (infixl "*" 70)
  1162 notation Groups.one ("1")
  1163 
  1164 context comm_monoid_add
  1165 begin
  1166 
  1167 definition msetsum :: "'a multiset \<Rightarrow> 'a"
  1168 where
  1169   "msetsum = comm_monoid_mset.F plus 0"
  1170 
  1171 sublocale msetsum!: comm_monoid_mset plus 0
  1172 where
  1173   "comm_monoid_mset.F plus 0 = msetsum"
  1174 proof -
  1175   show "comm_monoid_mset plus 0" ..
  1176   from msetsum_def show "comm_monoid_mset.F plus 0 = msetsum" ..
  1177 qed
  1178 
  1179 lemma setsum_unfold_msetsum:
  1180   "setsum f A = msetsum (image_mset f (multiset_of_set A))"
  1181   by (cases "finite A") (induct A rule: finite_induct, simp_all)
  1182 
  1183 abbreviation msetsum_image :: "('b \<Rightarrow> 'a) \<Rightarrow> 'b multiset \<Rightarrow> 'a"
  1184 where
  1185   "msetsum_image f M \<equiv> msetsum (image_mset f M)"
  1186 
  1187 end
  1188 
  1189 syntax
  1190   "_msetsum_image" :: "pttrn \<Rightarrow> 'b set \<Rightarrow> 'a \<Rightarrow> 'a::comm_monoid_add" 
  1191       ("(3SUM _:#_. _)" [0, 51, 10] 10)
  1192 
  1193 syntax (xsymbols)
  1194   "_msetsum_image" :: "pttrn \<Rightarrow> 'b set \<Rightarrow> 'a \<Rightarrow> 'a::comm_monoid_add" 
  1195       ("(3\<Sum>_:#_. _)" [0, 51, 10] 10)
  1196 
  1197 syntax (HTML output)
  1198   "_msetsum_image" :: "pttrn \<Rightarrow> 'b set \<Rightarrow> 'a \<Rightarrow> 'a::comm_monoid_add" 
  1199       ("(3\<Sum>_\<in>#_. _)" [0, 51, 10] 10)
  1200 
  1201 translations
  1202   "SUM i :# A. b" == "CONST msetsum_image (\<lambda>i. b) A"
  1203 
  1204 context comm_monoid_mult
  1205 begin
  1206 
  1207 definition msetprod :: "'a multiset \<Rightarrow> 'a"
  1208 where
  1209   "msetprod = comm_monoid_mset.F times 1"
  1210 
  1211 sublocale msetprod!: comm_monoid_mset times 1
  1212 where
  1213   "comm_monoid_mset.F times 1 = msetprod"
  1214 proof -
  1215   show "comm_monoid_mset times 1" ..
  1216   from msetprod_def show "comm_monoid_mset.F times 1 = msetprod" ..
  1217 qed
  1218 
  1219 lemma msetprod_empty:
  1220   "msetprod {#} = 1"
  1221   by (fact msetprod.empty)
  1222 
  1223 lemma msetprod_singleton:
  1224   "msetprod {#x#} = x"
  1225   by (fact msetprod.singleton)
  1226 
  1227 lemma msetprod_Un:
  1228   "msetprod (A + B) = msetprod A * msetprod B" 
  1229   by (fact msetprod.union)
  1230 
  1231 lemma setprod_unfold_msetprod:
  1232   "setprod f A = msetprod (image_mset f (multiset_of_set A))"
  1233   by (cases "finite A") (induct A rule: finite_induct, simp_all)
  1234 
  1235 lemma msetprod_multiplicity:
  1236   "msetprod M = setprod (\<lambda>x. x ^ count M x) (set_of M)"
  1237   by (simp add: Multiset.fold_def setprod.eq_fold msetprod.eq_fold funpow_times_power comp_def)
  1238 
  1239 abbreviation msetprod_image :: "('b \<Rightarrow> 'a) \<Rightarrow> 'b multiset \<Rightarrow> 'a"
  1240 where
  1241   "msetprod_image f M \<equiv> msetprod (image_mset f M)"
  1242 
  1243 end
  1244 
  1245 syntax
  1246   "_msetprod_image" :: "pttrn \<Rightarrow> 'b set \<Rightarrow> 'a \<Rightarrow> 'a::comm_monoid_mult" 
  1247       ("(3PROD _:#_. _)" [0, 51, 10] 10)
  1248 
  1249 syntax (xsymbols)
  1250   "_msetprod_image" :: "pttrn \<Rightarrow> 'b set \<Rightarrow> 'a \<Rightarrow> 'a::comm_monoid_mult" 
  1251       ("(3\<Prod>_\<in>#_. _)" [0, 51, 10] 10)
  1252 
  1253 syntax (HTML output)
  1254   "_msetprod_image" :: "pttrn \<Rightarrow> 'b set \<Rightarrow> 'a \<Rightarrow> 'a::comm_monoid_mult" 
  1255       ("(3\<Prod>_\<in>#_. _)" [0, 51, 10] 10)
  1256 
  1257 translations
  1258   "PROD i :# A. b" == "CONST msetprod_image (\<lambda>i. b) A"
  1259 
  1260 lemma (in comm_semiring_1) dvd_msetprod:
  1261   assumes "x \<in># A"
  1262   shows "x dvd msetprod A"
  1263 proof -
  1264   from assms have "A = (A - {#x#}) + {#x#}" by simp
  1265   then obtain B where "A = B + {#x#}" ..
  1266   then show ?thesis by simp
  1267 qed
  1268 
  1269 
  1270 subsection {* Cardinality *}
  1271 
  1272 definition mcard :: "'a multiset \<Rightarrow> nat"
  1273 where
  1274   "mcard = msetsum \<circ> image_mset (\<lambda>_. 1)"
  1275 
  1276 lemma mcard_empty [simp]:
  1277   "mcard {#} = 0"
  1278   by (simp add: mcard_def)
  1279 
  1280 lemma mcard_singleton [simp]:
  1281   "mcard {#a#} = Suc 0"
  1282   by (simp add: mcard_def)
  1283 
  1284 lemma mcard_plus [simp]:
  1285   "mcard (M + N) = mcard M + mcard N"
  1286   by (simp add: mcard_def)
  1287 
  1288 lemma mcard_empty_iff [simp]:
  1289   "mcard M = 0 \<longleftrightarrow> M = {#}"
  1290   by (induct M) simp_all
  1291 
  1292 lemma mcard_unfold_setsum:
  1293   "mcard M = setsum (count M) (set_of M)"
  1294 proof (induct M)
  1295   case empty then show ?case by simp
  1296 next
  1297   case (add M x) then show ?case
  1298     by (cases "x \<in> set_of M")
  1299       (simp_all del: mem_set_of_iff add: setsum.distrib setsum.delta' insert_absorb, simp)
  1300 qed
  1301 
  1302 lemma size_eq_mcard:
  1303   "size = mcard"
  1304   by (simp add: fun_eq_iff size_def mcard_unfold_setsum)
  1305 
  1306 lemma mcard_multiset_of:
  1307   "mcard (multiset_of xs) = length xs"
  1308   by (induct xs) simp_all
  1309 
  1310 
  1311 subsection {* Alternative representations *}
  1312 
  1313 subsubsection {* Lists *}
  1314 
  1315 context linorder
  1316 begin
  1317 
  1318 lemma multiset_of_insort [simp]:
  1319   "multiset_of (insort_key k x xs) = {#x#} + multiset_of xs"
  1320   by (induct xs) (simp_all add: ac_simps)
  1321  
  1322 lemma multiset_of_sort [simp]:
  1323   "multiset_of (sort_key k xs) = multiset_of xs"
  1324   by (induct xs) (simp_all add: ac_simps)
  1325 
  1326 text {*
  1327   This lemma shows which properties suffice to show that a function
  1328   @{text "f"} with @{text "f xs = ys"} behaves like sort.
  1329 *}
  1330 
  1331 lemma properties_for_sort_key:
  1332   assumes "multiset_of ys = multiset_of xs"
  1333   and "\<And>k. k \<in> set ys \<Longrightarrow> filter (\<lambda>x. f k = f x) ys = filter (\<lambda>x. f k = f x) xs"
  1334   and "sorted (map f ys)"
  1335   shows "sort_key f xs = ys"
  1336 using assms
  1337 proof (induct xs arbitrary: ys)
  1338   case Nil then show ?case by simp
  1339 next
  1340   case (Cons x xs)
  1341   from Cons.prems(2) have
  1342     "\<forall>k \<in> set ys. filter (\<lambda>x. f k = f x) (remove1 x ys) = filter (\<lambda>x. f k = f x) xs"
  1343     by (simp add: filter_remove1)
  1344   with Cons.prems have "sort_key f xs = remove1 x ys"
  1345     by (auto intro!: Cons.hyps simp add: sorted_map_remove1)
  1346   moreover from Cons.prems have "x \<in> set ys"
  1347     by (auto simp add: mem_set_multiset_eq intro!: ccontr)
  1348   ultimately show ?case using Cons.prems by (simp add: insort_key_remove1)
  1349 qed
  1350 
  1351 lemma properties_for_sort:
  1352   assumes multiset: "multiset_of ys = multiset_of xs"
  1353   and "sorted ys"
  1354   shows "sort xs = ys"
  1355 proof (rule properties_for_sort_key)
  1356   from multiset show "multiset_of ys = multiset_of xs" .
  1357   from `sorted ys` show "sorted (map (\<lambda>x. x) ys)" by simp
  1358   from multiset have "\<And>k. length (filter (\<lambda>y. k = y) ys) = length (filter (\<lambda>x. k = x) xs)"
  1359     by (rule multiset_of_eq_length_filter)
  1360   then have "\<And>k. replicate (length (filter (\<lambda>y. k = y) ys)) k = replicate (length (filter (\<lambda>x. k = x) xs)) k"
  1361     by simp
  1362   then show "\<And>k. k \<in> set ys \<Longrightarrow> filter (\<lambda>y. k = y) ys = filter (\<lambda>x. k = x) xs"
  1363     by (simp add: replicate_length_filter)
  1364 qed
  1365 
  1366 lemma sort_key_by_quicksort:
  1367   "sort_key f xs = sort_key f [x\<leftarrow>xs. f x < f (xs ! (length xs div 2))]
  1368     @ [x\<leftarrow>xs. f x = f (xs ! (length xs div 2))]
  1369     @ sort_key f [x\<leftarrow>xs. f x > f (xs ! (length xs div 2))]" (is "sort_key f ?lhs = ?rhs")
  1370 proof (rule properties_for_sort_key)
  1371   show "multiset_of ?rhs = multiset_of ?lhs"
  1372     by (rule multiset_eqI) (auto simp add: multiset_of_filter)
  1373 next
  1374   show "sorted (map f ?rhs)"
  1375     by (auto simp add: sorted_append intro: sorted_map_same)
  1376 next
  1377   fix l
  1378   assume "l \<in> set ?rhs"
  1379   let ?pivot = "f (xs ! (length xs div 2))"
  1380   have *: "\<And>x. f l = f x \<longleftrightarrow> f x = f l" by auto
  1381   have "[x \<leftarrow> sort_key f xs . f x = f l] = [x \<leftarrow> xs. f x = f l]"
  1382     unfolding filter_sort by (rule properties_for_sort_key) (auto intro: sorted_map_same)
  1383   with * have **: "[x \<leftarrow> sort_key f xs . f l = f x] = [x \<leftarrow> xs. f l = f x]" by simp
  1384   have "\<And>x P. P (f x) ?pivot \<and> f l = f x \<longleftrightarrow> P (f l) ?pivot \<and> f l = f x" by auto
  1385   then have "\<And>P. [x \<leftarrow> sort_key f xs . P (f x) ?pivot \<and> f l = f x] =
  1386     [x \<leftarrow> sort_key f xs. P (f l) ?pivot \<and> f l = f x]" by simp
  1387   note *** = this [of "op <"] this [of "op >"] this [of "op ="]
  1388   show "[x \<leftarrow> ?rhs. f l = f x] = [x \<leftarrow> ?lhs. f l = f x]"
  1389   proof (cases "f l" ?pivot rule: linorder_cases)
  1390     case less
  1391     then have "f l \<noteq> ?pivot" and "\<not> f l > ?pivot" by auto
  1392     with less show ?thesis
  1393       by (simp add: filter_sort [symmetric] ** ***)
  1394   next
  1395     case equal then show ?thesis
  1396       by (simp add: * less_le)
  1397   next
  1398     case greater
  1399     then have "f l \<noteq> ?pivot" and "\<not> f l < ?pivot" by auto
  1400     with greater show ?thesis
  1401       by (simp add: filter_sort [symmetric] ** ***)
  1402   qed
  1403 qed
  1404 
  1405 lemma sort_by_quicksort:
  1406   "sort xs = sort [x\<leftarrow>xs. x < xs ! (length xs div 2)]
  1407     @ [x\<leftarrow>xs. x = xs ! (length xs div 2)]
  1408     @ sort [x\<leftarrow>xs. x > xs ! (length xs div 2)]" (is "sort ?lhs = ?rhs")
  1409   using sort_key_by_quicksort [of "\<lambda>x. x", symmetric] by simp
  1410 
  1411 text {* A stable parametrized quicksort *}
  1412 
  1413 definition part :: "('b \<Rightarrow> 'a) \<Rightarrow> 'a \<Rightarrow> 'b list \<Rightarrow> 'b list \<times> 'b list \<times> 'b list" where
  1414   "part f pivot xs = ([x \<leftarrow> xs. f x < pivot], [x \<leftarrow> xs. f x = pivot], [x \<leftarrow> xs. pivot < f x])"
  1415 
  1416 lemma part_code [code]:
  1417   "part f pivot [] = ([], [], [])"
  1418   "part f pivot (x # xs) = (let (lts, eqs, gts) = part f pivot xs; x' = f x in
  1419      if x' < pivot then (x # lts, eqs, gts)
  1420      else if x' > pivot then (lts, eqs, x # gts)
  1421      else (lts, x # eqs, gts))"
  1422   by (auto simp add: part_def Let_def split_def)
  1423 
  1424 lemma sort_key_by_quicksort_code [code]:
  1425   "sort_key f xs = (case xs of [] \<Rightarrow> []
  1426     | [x] \<Rightarrow> xs
  1427     | [x, y] \<Rightarrow> (if f x \<le> f y then xs else [y, x])
  1428     | _ \<Rightarrow> (let (lts, eqs, gts) = part f (f (xs ! (length xs div 2))) xs
  1429        in sort_key f lts @ eqs @ sort_key f gts))"
  1430 proof (cases xs)
  1431   case Nil then show ?thesis by simp
  1432 next
  1433   case (Cons _ ys) note hyps = Cons show ?thesis
  1434   proof (cases ys)
  1435     case Nil with hyps show ?thesis by simp
  1436   next
  1437     case (Cons _ zs) note hyps = hyps Cons show ?thesis
  1438     proof (cases zs)
  1439       case Nil with hyps show ?thesis by auto
  1440     next
  1441       case Cons 
  1442       from sort_key_by_quicksort [of f xs]
  1443       have "sort_key f xs = (let (lts, eqs, gts) = part f (f (xs ! (length xs div 2))) xs
  1444         in sort_key f lts @ eqs @ sort_key f gts)"
  1445       by (simp only: split_def Let_def part_def fst_conv snd_conv)
  1446       with hyps Cons show ?thesis by (simp only: list.cases)
  1447     qed
  1448   qed
  1449 qed
  1450 
  1451 end
  1452 
  1453 hide_const (open) part
  1454 
  1455 lemma multiset_of_remdups_le: "multiset_of (remdups xs) \<le> multiset_of xs"
  1456   by (induct xs) (auto intro: order_trans)
  1457 
  1458 lemma multiset_of_update:
  1459   "i < length ls \<Longrightarrow> multiset_of (ls[i := v]) = multiset_of ls - {#ls ! i#} + {#v#}"
  1460 proof (induct ls arbitrary: i)
  1461   case Nil then show ?case by simp
  1462 next
  1463   case (Cons x xs)
  1464   show ?case
  1465   proof (cases i)
  1466     case 0 then show ?thesis by simp
  1467   next
  1468     case (Suc i')
  1469     with Cons show ?thesis
  1470       apply simp
  1471       apply (subst add_assoc)
  1472       apply (subst add_commute [of "{#v#}" "{#x#}"])
  1473       apply (subst add_assoc [symmetric])
  1474       apply simp
  1475       apply (rule mset_le_multiset_union_diff_commute)
  1476       apply (simp add: mset_le_single nth_mem_multiset_of)
  1477       done
  1478   qed
  1479 qed
  1480 
  1481 lemma multiset_of_swap:
  1482   "i < length ls \<Longrightarrow> j < length ls \<Longrightarrow>
  1483     multiset_of (ls[j := ls ! i, i := ls ! j]) = multiset_of ls"
  1484   by (cases "i = j") (simp_all add: multiset_of_update nth_mem_multiset_of)
  1485 
  1486 
  1487 subsection {* The multiset order *}
  1488 
  1489 subsubsection {* Well-foundedness *}
  1490 
  1491 definition mult1 :: "('a \<times> 'a) set => ('a multiset \<times> 'a multiset) set" where
  1492   "mult1 r = {(N, M). \<exists>a M0 K. M = M0 + {#a#} \<and> N = M0 + K \<and>
  1493       (\<forall>b. b :# K --> (b, a) \<in> r)}"
  1494 
  1495 definition mult :: "('a \<times> 'a) set => ('a multiset \<times> 'a multiset) set" where
  1496   "mult r = (mult1 r)\<^sup>+"
  1497 
  1498 lemma not_less_empty [iff]: "(M, {#}) \<notin> mult1 r"
  1499 by (simp add: mult1_def)
  1500 
  1501 lemma less_add: "(N, M0 + {#a#}) \<in> mult1 r ==>
  1502     (\<exists>M. (M, M0) \<in> mult1 r \<and> N = M + {#a#}) \<or>
  1503     (\<exists>K. (\<forall>b. b :# K --> (b, a) \<in> r) \<and> N = M0 + K)"
  1504   (is "_ \<Longrightarrow> ?case1 (mult1 r) \<or> ?case2")
  1505 proof (unfold mult1_def)
  1506   let ?r = "\<lambda>K a. \<forall>b. b :# K --> (b, a) \<in> r"
  1507   let ?R = "\<lambda>N M. \<exists>a M0 K. M = M0 + {#a#} \<and> N = M0 + K \<and> ?r K a"
  1508   let ?case1 = "?case1 {(N, M). ?R N M}"
  1509 
  1510   assume "(N, M0 + {#a#}) \<in> {(N, M). ?R N M}"
  1511   then have "\<exists>a' M0' K.
  1512       M0 + {#a#} = M0' + {#a'#} \<and> N = M0' + K \<and> ?r K a'" by simp
  1513   then show "?case1 \<or> ?case2"
  1514   proof (elim exE conjE)
  1515     fix a' M0' K
  1516     assume N: "N = M0' + K" and r: "?r K a'"
  1517     assume "M0 + {#a#} = M0' + {#a'#}"
  1518     then have "M0 = M0' \<and> a = a' \<or>
  1519         (\<exists>K'. M0 = K' + {#a'#} \<and> M0' = K' + {#a#})"
  1520       by (simp only: add_eq_conv_ex)
  1521     then show ?thesis
  1522     proof (elim disjE conjE exE)
  1523       assume "M0 = M0'" "a = a'"
  1524       with N r have "?r K a \<and> N = M0 + K" by simp
  1525       then have ?case2 .. then show ?thesis ..
  1526     next
  1527       fix K'
  1528       assume "M0' = K' + {#a#}"
  1529       with N have n: "N = K' + K + {#a#}" by (simp add: add_ac)
  1530 
  1531       assume "M0 = K' + {#a'#}"
  1532       with r have "?R (K' + K) M0" by blast
  1533       with n have ?case1 by simp then show ?thesis ..
  1534     qed
  1535   qed
  1536 qed
  1537 
  1538 lemma all_accessible: "wf r ==> \<forall>M. M \<in> Wellfounded.acc (mult1 r)"
  1539 proof
  1540   let ?R = "mult1 r"
  1541   let ?W = "Wellfounded.acc ?R"
  1542   {
  1543     fix M M0 a
  1544     assume M0: "M0 \<in> ?W"
  1545       and wf_hyp: "!!b. (b, a) \<in> r ==> (\<forall>M \<in> ?W. M + {#b#} \<in> ?W)"
  1546       and acc_hyp: "\<forall>M. (M, M0) \<in> ?R --> M + {#a#} \<in> ?W"
  1547     have "M0 + {#a#} \<in> ?W"
  1548     proof (rule accI [of "M0 + {#a#}"])
  1549       fix N
  1550       assume "(N, M0 + {#a#}) \<in> ?R"
  1551       then have "((\<exists>M. (M, M0) \<in> ?R \<and> N = M + {#a#}) \<or>
  1552           (\<exists>K. (\<forall>b. b :# K --> (b, a) \<in> r) \<and> N = M0 + K))"
  1553         by (rule less_add)
  1554       then show "N \<in> ?W"
  1555       proof (elim exE disjE conjE)
  1556         fix M assume "(M, M0) \<in> ?R" and N: "N = M + {#a#}"
  1557         from acc_hyp have "(M, M0) \<in> ?R --> M + {#a#} \<in> ?W" ..
  1558         from this and `(M, M0) \<in> ?R` have "M + {#a#} \<in> ?W" ..
  1559         then show "N \<in> ?W" by (simp only: N)
  1560       next
  1561         fix K
  1562         assume N: "N = M0 + K"
  1563         assume "\<forall>b. b :# K --> (b, a) \<in> r"
  1564         then have "M0 + K \<in> ?W"
  1565         proof (induct K)
  1566           case empty
  1567           from M0 show "M0 + {#} \<in> ?W" by simp
  1568         next
  1569           case (add K x)
  1570           from add.prems have "(x, a) \<in> r" by simp
  1571           with wf_hyp have "\<forall>M \<in> ?W. M + {#x#} \<in> ?W" by blast
  1572           moreover from add have "M0 + K \<in> ?W" by simp
  1573           ultimately have "(M0 + K) + {#x#} \<in> ?W" ..
  1574           then show "M0 + (K + {#x#}) \<in> ?W" by (simp only: add_assoc)
  1575         qed
  1576         then show "N \<in> ?W" by (simp only: N)
  1577       qed
  1578     qed
  1579   } note tedious_reasoning = this
  1580 
  1581   assume wf: "wf r"
  1582   fix M
  1583   show "M \<in> ?W"
  1584   proof (induct M)
  1585     show "{#} \<in> ?W"
  1586     proof (rule accI)
  1587       fix b assume "(b, {#}) \<in> ?R"
  1588       with not_less_empty show "b \<in> ?W" by contradiction
  1589     qed
  1590 
  1591     fix M a assume "M \<in> ?W"
  1592     from wf have "\<forall>M \<in> ?W. M + {#a#} \<in> ?W"
  1593     proof induct
  1594       fix a
  1595       assume r: "!!b. (b, a) \<in> r ==> (\<forall>M \<in> ?W. M + {#b#} \<in> ?W)"
  1596       show "\<forall>M \<in> ?W. M + {#a#} \<in> ?W"
  1597       proof
  1598         fix M assume "M \<in> ?W"
  1599         then show "M + {#a#} \<in> ?W"
  1600           by (rule acc_induct) (rule tedious_reasoning [OF _ r])
  1601       qed
  1602     qed
  1603     from this and `M \<in> ?W` show "M + {#a#} \<in> ?W" ..
  1604   qed
  1605 qed
  1606 
  1607 theorem wf_mult1: "wf r ==> wf (mult1 r)"
  1608 by (rule acc_wfI) (rule all_accessible)
  1609 
  1610 theorem wf_mult: "wf r ==> wf (mult r)"
  1611 unfolding mult_def by (rule wf_trancl) (rule wf_mult1)
  1612 
  1613 
  1614 subsubsection {* Closure-free presentation *}
  1615 
  1616 text {* One direction. *}
  1617 
  1618 lemma mult_implies_one_step:
  1619   "trans r ==> (M, N) \<in> mult r ==>
  1620     \<exists>I J K. N = I + J \<and> M = I + K \<and> J \<noteq> {#} \<and>
  1621     (\<forall>k \<in> set_of K. \<exists>j \<in> set_of J. (k, j) \<in> r)"
  1622 apply (unfold mult_def mult1_def set_of_def)
  1623 apply (erule converse_trancl_induct, clarify)
  1624  apply (rule_tac x = M0 in exI, simp, clarify)
  1625 apply (case_tac "a :# K")
  1626  apply (rule_tac x = I in exI)
  1627  apply (simp (no_asm))
  1628  apply (rule_tac x = "(K - {#a#}) + Ka" in exI)
  1629  apply (simp (no_asm_simp) add: add_assoc [symmetric])
  1630  apply (drule_tac f = "\<lambda>M. M - {#a#}" in arg_cong)
  1631  apply (simp add: diff_union_single_conv)
  1632  apply (simp (no_asm_use) add: trans_def)
  1633  apply blast
  1634 apply (subgoal_tac "a :# I")
  1635  apply (rule_tac x = "I - {#a#}" in exI)
  1636  apply (rule_tac x = "J + {#a#}" in exI)
  1637  apply (rule_tac x = "K + Ka" in exI)
  1638  apply (rule conjI)
  1639   apply (simp add: multiset_eq_iff split: nat_diff_split)
  1640  apply (rule conjI)
  1641   apply (drule_tac f = "\<lambda>M. M - {#a#}" in arg_cong, simp)
  1642   apply (simp add: multiset_eq_iff split: nat_diff_split)
  1643  apply (simp (no_asm_use) add: trans_def)
  1644  apply blast
  1645 apply (subgoal_tac "a :# (M0 + {#a#})")
  1646  apply simp
  1647 apply (simp (no_asm))
  1648 done
  1649 
  1650 lemma one_step_implies_mult_aux:
  1651   "trans r ==>
  1652     \<forall>I J K. (size J = n \<and> J \<noteq> {#} \<and> (\<forall>k \<in> set_of K. \<exists>j \<in> set_of J. (k, j) \<in> r))
  1653       --> (I + K, I + J) \<in> mult r"
  1654 apply (induct_tac n, auto)
  1655 apply (frule size_eq_Suc_imp_eq_union, clarify)
  1656 apply (rename_tac "J'", simp)
  1657 apply (erule notE, auto)
  1658 apply (case_tac "J' = {#}")
  1659  apply (simp add: mult_def)
  1660  apply (rule r_into_trancl)
  1661  apply (simp add: mult1_def set_of_def, blast)
  1662 txt {* Now we know @{term "J' \<noteq> {#}"}. *}
  1663 apply (cut_tac M = K and P = "\<lambda>x. (x, a) \<in> r" in multiset_partition)
  1664 apply (erule_tac P = "\<forall>k \<in> set_of K. ?P k" in rev_mp)
  1665 apply (erule ssubst)
  1666 apply (simp add: Ball_def, auto)
  1667 apply (subgoal_tac
  1668   "((I + {# x :# K. (x, a) \<in> r #}) + {# x :# K. (x, a) \<notin> r #},
  1669     (I + {# x :# K. (x, a) \<in> r #}) + J') \<in> mult r")
  1670  prefer 2
  1671  apply force
  1672 apply (simp (no_asm_use) add: add_assoc [symmetric] mult_def)
  1673 apply (erule trancl_trans)
  1674 apply (rule r_into_trancl)
  1675 apply (simp add: mult1_def set_of_def)
  1676 apply (rule_tac x = a in exI)
  1677 apply (rule_tac x = "I + J'" in exI)
  1678 apply (simp add: add_ac)
  1679 done
  1680 
  1681 lemma one_step_implies_mult:
  1682   "trans r ==> J \<noteq> {#} ==> \<forall>k \<in> set_of K. \<exists>j \<in> set_of J. (k, j) \<in> r
  1683     ==> (I + K, I + J) \<in> mult r"
  1684 using one_step_implies_mult_aux by blast
  1685 
  1686 
  1687 subsubsection {* Partial-order properties *}
  1688 
  1689 definition less_multiset :: "'a\<Colon>order multiset \<Rightarrow> 'a multiset \<Rightarrow> bool" (infix "<#" 50) where
  1690   "M' <# M \<longleftrightarrow> (M', M) \<in> mult {(x', x). x' < x}"
  1691 
  1692 definition le_multiset :: "'a\<Colon>order multiset \<Rightarrow> 'a multiset \<Rightarrow> bool" (infix "<=#" 50) where
  1693   "M' <=# M \<longleftrightarrow> M' <# M \<or> M' = M"
  1694 
  1695 notation (xsymbols) less_multiset (infix "\<subset>#" 50)
  1696 notation (xsymbols) le_multiset (infix "\<subseteq>#" 50)
  1697 
  1698 interpretation multiset_order: order le_multiset less_multiset
  1699 proof -
  1700   have irrefl: "\<And>M :: 'a multiset. \<not> M \<subset># M"
  1701   proof
  1702     fix M :: "'a multiset"
  1703     assume "M \<subset># M"
  1704     then have MM: "(M, M) \<in> mult {(x, y). x < y}" by (simp add: less_multiset_def)
  1705     have "trans {(x'::'a, x). x' < x}"
  1706       by (rule transI) simp
  1707     moreover note MM
  1708     ultimately have "\<exists>I J K. M = I + J \<and> M = I + K
  1709       \<and> J \<noteq> {#} \<and> (\<forall>k\<in>set_of K. \<exists>j\<in>set_of J. (k, j) \<in> {(x, y). x < y})"
  1710       by (rule mult_implies_one_step)
  1711     then obtain I J K where "M = I + J" and "M = I + K"
  1712       and "J \<noteq> {#}" and "(\<forall>k\<in>set_of K. \<exists>j\<in>set_of J. (k, j) \<in> {(x, y). x < y})" by blast
  1713     then have aux1: "K \<noteq> {#}" and aux2: "\<forall>k\<in>set_of K. \<exists>j\<in>set_of K. k < j" by auto
  1714     have "finite (set_of K)" by simp
  1715     moreover note aux2
  1716     ultimately have "set_of K = {}"
  1717       by (induct rule: finite_induct) (auto intro: order_less_trans)
  1718     with aux1 show False by simp
  1719   qed
  1720   have trans: "\<And>K M N :: 'a multiset. K \<subset># M \<Longrightarrow> M \<subset># N \<Longrightarrow> K \<subset># N"
  1721     unfolding less_multiset_def mult_def by (blast intro: trancl_trans)
  1722   show "class.order (le_multiset :: 'a multiset \<Rightarrow> _) less_multiset"
  1723     by default (auto simp add: le_multiset_def irrefl dest: trans)
  1724 qed
  1725 
  1726 lemma mult_less_irrefl [elim!]: "M \<subset># (M::'a::order multiset) ==> R"
  1727   by simp
  1728 
  1729 
  1730 subsubsection {* Monotonicity of multiset union *}
  1731 
  1732 lemma mult1_union: "(B, D) \<in> mult1 r ==> (C + B, C + D) \<in> mult1 r"
  1733 apply (unfold mult1_def)
  1734 apply auto
  1735 apply (rule_tac x = a in exI)
  1736 apply (rule_tac x = "C + M0" in exI)
  1737 apply (simp add: add_assoc)
  1738 done
  1739 
  1740 lemma union_less_mono2: "B \<subset># D ==> C + B \<subset># C + (D::'a::order multiset)"
  1741 apply (unfold less_multiset_def mult_def)
  1742 apply (erule trancl_induct)
  1743  apply (blast intro: mult1_union)
  1744 apply (blast intro: mult1_union trancl_trans)
  1745 done
  1746 
  1747 lemma union_less_mono1: "B \<subset># D ==> B + C \<subset># D + (C::'a::order multiset)"
  1748 apply (subst add_commute [of B C])
  1749 apply (subst add_commute [of D C])
  1750 apply (erule union_less_mono2)
  1751 done
  1752 
  1753 lemma union_less_mono:
  1754   "A \<subset># C ==> B \<subset># D ==> A + B \<subset># C + (D::'a::order multiset)"
  1755   by (blast intro!: union_less_mono1 union_less_mono2 multiset_order.less_trans)
  1756 
  1757 interpretation multiset_order: ordered_ab_semigroup_add plus le_multiset less_multiset
  1758 proof
  1759 qed (auto simp add: le_multiset_def intro: union_less_mono2)
  1760 
  1761 
  1762 subsection {* Termination proofs with multiset orders *}
  1763 
  1764 lemma multi_member_skip: "x \<in># XS \<Longrightarrow> x \<in># {# y #} + XS"
  1765   and multi_member_this: "x \<in># {# x #} + XS"
  1766   and multi_member_last: "x \<in># {# x #}"
  1767   by auto
  1768 
  1769 definition "ms_strict = mult pair_less"
  1770 definition "ms_weak = ms_strict \<union> Id"
  1771 
  1772 lemma ms_reduction_pair: "reduction_pair (ms_strict, ms_weak)"
  1773 unfolding reduction_pair_def ms_strict_def ms_weak_def pair_less_def
  1774 by (auto intro: wf_mult1 wf_trancl simp: mult_def)
  1775 
  1776 lemma smsI:
  1777   "(set_of A, set_of B) \<in> max_strict \<Longrightarrow> (Z + A, Z + B) \<in> ms_strict"
  1778   unfolding ms_strict_def
  1779 by (rule one_step_implies_mult) (auto simp add: max_strict_def pair_less_def elim!:max_ext.cases)
  1780 
  1781 lemma wmsI:
  1782   "(set_of A, set_of B) \<in> max_strict \<or> A = {#} \<and> B = {#}
  1783   \<Longrightarrow> (Z + A, Z + B) \<in> ms_weak"
  1784 unfolding ms_weak_def ms_strict_def
  1785 by (auto simp add: pair_less_def max_strict_def elim!:max_ext.cases intro: one_step_implies_mult)
  1786 
  1787 inductive pw_leq
  1788 where
  1789   pw_leq_empty: "pw_leq {#} {#}"
  1790 | pw_leq_step:  "\<lbrakk>(x,y) \<in> pair_leq; pw_leq X Y \<rbrakk> \<Longrightarrow> pw_leq ({#x#} + X) ({#y#} + Y)"
  1791 
  1792 lemma pw_leq_lstep:
  1793   "(x, y) \<in> pair_leq \<Longrightarrow> pw_leq {#x#} {#y#}"
  1794 by (drule pw_leq_step) (rule pw_leq_empty, simp)
  1795 
  1796 lemma pw_leq_split:
  1797   assumes "pw_leq X Y"
  1798   shows "\<exists>A B Z. X = A + Z \<and> Y = B + Z \<and> ((set_of A, set_of B) \<in> max_strict \<or> (B = {#} \<and> A = {#}))"
  1799   using assms
  1800 proof (induct)
  1801   case pw_leq_empty thus ?case by auto
  1802 next
  1803   case (pw_leq_step x y X Y)
  1804   then obtain A B Z where
  1805     [simp]: "X = A + Z" "Y = B + Z" 
  1806       and 1[simp]: "(set_of A, set_of B) \<in> max_strict \<or> (B = {#} \<and> A = {#})" 
  1807     by auto
  1808   from pw_leq_step have "x = y \<or> (x, y) \<in> pair_less" 
  1809     unfolding pair_leq_def by auto
  1810   thus ?case
  1811   proof
  1812     assume [simp]: "x = y"
  1813     have
  1814       "{#x#} + X = A + ({#y#}+Z) 
  1815       \<and> {#y#} + Y = B + ({#y#}+Z)
  1816       \<and> ((set_of A, set_of B) \<in> max_strict \<or> (B = {#} \<and> A = {#}))"
  1817       by (auto simp: add_ac)
  1818     thus ?case by (intro exI)
  1819   next
  1820     assume A: "(x, y) \<in> pair_less"
  1821     let ?A' = "{#x#} + A" and ?B' = "{#y#} + B"
  1822     have "{#x#} + X = ?A' + Z"
  1823       "{#y#} + Y = ?B' + Z"
  1824       by (auto simp add: add_ac)
  1825     moreover have 
  1826       "(set_of ?A', set_of ?B') \<in> max_strict"
  1827       using 1 A unfolding max_strict_def 
  1828       by (auto elim!: max_ext.cases)
  1829     ultimately show ?thesis by blast
  1830   qed
  1831 qed
  1832 
  1833 lemma 
  1834   assumes pwleq: "pw_leq Z Z'"
  1835   shows ms_strictI: "(set_of A, set_of B) \<in> max_strict \<Longrightarrow> (Z + A, Z' + B) \<in> ms_strict"
  1836   and   ms_weakI1:  "(set_of A, set_of B) \<in> max_strict \<Longrightarrow> (Z + A, Z' + B) \<in> ms_weak"
  1837   and   ms_weakI2:  "(Z + {#}, Z' + {#}) \<in> ms_weak"
  1838 proof -
  1839   from pw_leq_split[OF pwleq] 
  1840   obtain A' B' Z''
  1841     where [simp]: "Z = A' + Z''" "Z' = B' + Z''"
  1842     and mx_or_empty: "(set_of A', set_of B') \<in> max_strict \<or> (A' = {#} \<and> B' = {#})"
  1843     by blast
  1844   {
  1845     assume max: "(set_of A, set_of B) \<in> max_strict"
  1846     from mx_or_empty
  1847     have "(Z'' + (A + A'), Z'' + (B + B')) \<in> ms_strict"
  1848     proof
  1849       assume max': "(set_of A', set_of B') \<in> max_strict"
  1850       with max have "(set_of (A + A'), set_of (B + B')) \<in> max_strict"
  1851         by (auto simp: max_strict_def intro: max_ext_additive)
  1852       thus ?thesis by (rule smsI) 
  1853     next
  1854       assume [simp]: "A' = {#} \<and> B' = {#}"
  1855       show ?thesis by (rule smsI) (auto intro: max)
  1856     qed
  1857     thus "(Z + A, Z' + B) \<in> ms_strict" by (simp add:add_ac)
  1858     thus "(Z + A, Z' + B) \<in> ms_weak" by (simp add: ms_weak_def)
  1859   }
  1860   from mx_or_empty
  1861   have "(Z'' + A', Z'' + B') \<in> ms_weak" by (rule wmsI)
  1862   thus "(Z + {#}, Z' + {#}) \<in> ms_weak" by (simp add:add_ac)
  1863 qed
  1864 
  1865 lemma empty_neutral: "{#} + x = x" "x + {#} = x"
  1866 and nonempty_plus: "{# x #} + rs \<noteq> {#}"
  1867 and nonempty_single: "{# x #} \<noteq> {#}"
  1868 by auto
  1869 
  1870 setup {*
  1871 let
  1872   fun msetT T = Type (@{type_name multiset}, [T]);
  1873 
  1874   fun mk_mset T [] = Const (@{const_abbrev Mempty}, msetT T)
  1875     | mk_mset T [x] = Const (@{const_name single}, T --> msetT T) $ x
  1876     | mk_mset T (x :: xs) =
  1877           Const (@{const_name plus}, msetT T --> msetT T --> msetT T) $
  1878                 mk_mset T [x] $ mk_mset T xs
  1879 
  1880   fun mset_member_tac m i =
  1881       (if m <= 0 then
  1882            rtac @{thm multi_member_this} i ORELSE rtac @{thm multi_member_last} i
  1883        else
  1884            rtac @{thm multi_member_skip} i THEN mset_member_tac (m - 1) i)
  1885 
  1886   val mset_nonempty_tac =
  1887       rtac @{thm nonempty_plus} ORELSE' rtac @{thm nonempty_single}
  1888 
  1889   val regroup_munion_conv =
  1890       Function_Lib.regroup_conv @{const_abbrev Mempty} @{const_name plus}
  1891         (map (fn t => t RS eq_reflection) (@{thms add_ac} @ @{thms empty_neutral}))
  1892 
  1893   fun unfold_pwleq_tac i =
  1894     (rtac @{thm pw_leq_step} i THEN (fn st => unfold_pwleq_tac (i + 1) st))
  1895       ORELSE (rtac @{thm pw_leq_lstep} i)
  1896       ORELSE (rtac @{thm pw_leq_empty} i)
  1897 
  1898   val set_of_simps = [@{thm set_of_empty}, @{thm set_of_single}, @{thm set_of_union},
  1899                       @{thm Un_insert_left}, @{thm Un_empty_left}]
  1900 in
  1901   ScnpReconstruct.multiset_setup (ScnpReconstruct.Multiset 
  1902   {
  1903     msetT=msetT, mk_mset=mk_mset, mset_regroup_conv=regroup_munion_conv,
  1904     mset_member_tac=mset_member_tac, mset_nonempty_tac=mset_nonempty_tac,
  1905     mset_pwleq_tac=unfold_pwleq_tac, set_of_simps=set_of_simps,
  1906     smsI'= @{thm ms_strictI}, wmsI2''= @{thm ms_weakI2}, wmsI1= @{thm ms_weakI1},
  1907     reduction_pair= @{thm ms_reduction_pair}
  1908   })
  1909 end
  1910 *}
  1911 
  1912 
  1913 subsection {* Legacy theorem bindings *}
  1914 
  1915 lemmas multi_count_eq = multiset_eq_iff [symmetric]
  1916 
  1917 lemma union_commute: "M + N = N + (M::'a multiset)"
  1918   by (fact add_commute)
  1919 
  1920 lemma union_assoc: "(M + N) + K = M + (N + (K::'a multiset))"
  1921   by (fact add_assoc)
  1922 
  1923 lemma union_lcomm: "M + (N + K) = N + (M + (K::'a multiset))"
  1924   by (fact add_left_commute)
  1925 
  1926 lemmas union_ac = union_assoc union_commute union_lcomm
  1927 
  1928 lemma union_right_cancel: "M + K = N + K \<longleftrightarrow> M = (N::'a multiset)"
  1929   by (fact add_right_cancel)
  1930 
  1931 lemma union_left_cancel: "K + M = K + N \<longleftrightarrow> M = (N::'a multiset)"
  1932   by (fact add_left_cancel)
  1933 
  1934 lemma multi_union_self_other_eq: "(A::'a multiset) + X = A + Y \<Longrightarrow> X = Y"
  1935   by (fact add_imp_eq)
  1936 
  1937 lemma mset_less_trans: "(M::'a multiset) < K \<Longrightarrow> K < N \<Longrightarrow> M < N"
  1938   by (fact order_less_trans)
  1939 
  1940 lemma multiset_inter_commute: "A #\<inter> B = B #\<inter> A"
  1941   by (fact inf.commute)
  1942 
  1943 lemma multiset_inter_assoc: "A #\<inter> (B #\<inter> C) = A #\<inter> B #\<inter> C"
  1944   by (fact inf.assoc [symmetric])
  1945 
  1946 lemma multiset_inter_left_commute: "A #\<inter> (B #\<inter> C) = B #\<inter> (A #\<inter> C)"
  1947   by (fact inf.left_commute)
  1948 
  1949 lemmas multiset_inter_ac =
  1950   multiset_inter_commute
  1951   multiset_inter_assoc
  1952   multiset_inter_left_commute
  1953 
  1954 lemma mult_less_not_refl:
  1955   "\<not> M \<subset># (M::'a::order multiset)"
  1956   by (fact multiset_order.less_irrefl)
  1957 
  1958 lemma mult_less_trans:
  1959   "K \<subset># M ==> M \<subset># N ==> K \<subset># (N::'a::order multiset)"
  1960   by (fact multiset_order.less_trans)
  1961     
  1962 lemma mult_less_not_sym:
  1963   "M \<subset># N ==> \<not> N \<subset># (M::'a::order multiset)"
  1964   by (fact multiset_order.less_not_sym)
  1965 
  1966 lemma mult_less_asym:
  1967   "M \<subset># N ==> (\<not> P ==> N \<subset># (M::'a::order multiset)) ==> P"
  1968   by (fact multiset_order.less_asym)
  1969 
  1970 ML {*
  1971 fun multiset_postproc _ maybe_name all_values (T as Type (_, [elem_T]))
  1972                       (Const _ $ t') =
  1973     let
  1974       val (maybe_opt, ps) =
  1975         Nitpick_Model.dest_plain_fun t' ||> op ~~
  1976         ||> map (apsnd (snd o HOLogic.dest_number))
  1977       fun elems_for t =
  1978         case AList.lookup (op =) ps t of
  1979           SOME n => replicate n t
  1980         | NONE => [Const (maybe_name, elem_T --> elem_T) $ t]
  1981     in
  1982       case maps elems_for (all_values elem_T) @
  1983            (if maybe_opt then [Const (Nitpick_Model.unrep (), elem_T)]
  1984             else []) of
  1985         [] => Const (@{const_name zero_class.zero}, T)
  1986       | ts => foldl1 (fn (t1, t2) =>
  1987                          Const (@{const_name plus_class.plus}, T --> T --> T)
  1988                          $ t1 $ t2)
  1989                      (map (curry (op $) (Const (@{const_name single},
  1990                                                 elem_T --> T))) ts)
  1991     end
  1992   | multiset_postproc _ _ _ _ t = t
  1993 *}
  1994 
  1995 declaration {*
  1996 Nitpick_Model.register_term_postprocessor @{typ "'a multiset"}
  1997     multiset_postproc
  1998 *}
  1999 
  2000 hide_const (open) fold
  2001 
  2002 
  2003 subsection {* Naive implementation using lists *}
  2004 
  2005 code_datatype multiset_of
  2006 
  2007 lemma [code]:
  2008   "{#} = multiset_of []"
  2009   by simp
  2010 
  2011 lemma [code]:
  2012   "{#x#} = multiset_of [x]"
  2013   by simp
  2014 
  2015 lemma union_code [code]:
  2016   "multiset_of xs + multiset_of ys = multiset_of (xs @ ys)"
  2017   by simp
  2018 
  2019 lemma [code]:
  2020   "image_mset f (multiset_of xs) = multiset_of (map f xs)"
  2021   by (simp add: multiset_of_map)
  2022 
  2023 lemma [code]:
  2024   "Multiset.filter f (multiset_of xs) = multiset_of (filter f xs)"
  2025   by (simp add: multiset_of_filter)
  2026 
  2027 lemma [code]:
  2028   "multiset_of xs - multiset_of ys = multiset_of (fold remove1 ys xs)"
  2029   by (rule sym, induct ys arbitrary: xs) (simp_all add: diff_add diff_right_commute)
  2030 
  2031 lemma [code]:
  2032   "multiset_of xs #\<inter> multiset_of ys =
  2033     multiset_of (snd (fold (\<lambda>x (ys, zs).
  2034       if x \<in> set ys then (remove1 x ys, x # zs) else (ys, zs)) xs (ys, [])))"
  2035 proof -
  2036   have "\<And>zs. multiset_of (snd (fold (\<lambda>x (ys, zs).
  2037     if x \<in> set ys then (remove1 x ys, x # zs) else (ys, zs)) xs (ys, zs))) =
  2038       (multiset_of xs #\<inter> multiset_of ys) + multiset_of zs"
  2039     by (induct xs arbitrary: ys)
  2040       (auto simp add: mem_set_multiset_eq inter_add_right1 inter_add_right2 ac_simps)
  2041   then show ?thesis by simp
  2042 qed
  2043 
  2044 lemma [code]:
  2045   "multiset_of xs #\<union> multiset_of ys =
  2046     multiset_of (split append (fold (\<lambda>x (ys, zs). (remove1 x ys, x # zs)) xs (ys, [])))"
  2047 proof -
  2048   have "\<And>zs. multiset_of (split append (fold (\<lambda>x (ys, zs). (remove1 x ys, x # zs)) xs (ys, zs))) =
  2049       (multiset_of xs #\<union> multiset_of ys) + multiset_of zs"
  2050     by (induct xs arbitrary: ys) (simp_all add: multiset_eq_iff)
  2051   then show ?thesis by simp
  2052 qed
  2053 
  2054 lemma [code_unfold]:
  2055   "x \<in># multiset_of xs \<longleftrightarrow> x \<in> set xs"
  2056   by (simp add: in_multiset_of)
  2057 
  2058 lemma [code]:
  2059   "count (multiset_of xs) x = fold (\<lambda>y. if x = y then Suc else id) xs 0"
  2060 proof -
  2061   have "\<And>n. fold (\<lambda>y. if x = y then Suc else id) xs n = count (multiset_of xs) x + n"
  2062     by (induct xs) simp_all
  2063   then show ?thesis by simp
  2064 qed
  2065 
  2066 lemma [code]:
  2067   "set_of (multiset_of xs) = set xs"
  2068   by simp
  2069 
  2070 lemma [code]:
  2071   "sorted_list_of_multiset (multiset_of xs) = sort xs"
  2072   by (induct xs) simp_all
  2073 
  2074 lemma [code]: -- {* not very efficient, but representation-ignorant! *}
  2075   "multiset_of_set A = multiset_of (sorted_list_of_set A)"
  2076   apply (cases "finite A")
  2077   apply simp_all
  2078   apply (induct A rule: finite_induct)
  2079   apply (simp_all add: union_commute)
  2080   done
  2081 
  2082 lemma [code]:
  2083   "mcard (multiset_of xs) = length xs"
  2084   by (simp add: mcard_multiset_of)
  2085 
  2086 lemma [code]:
  2087   "A \<le> B \<longleftrightarrow> A #\<inter> B = A" 
  2088   by (auto simp add: inf.order_iff)
  2089 
  2090 instantiation multiset :: (equal) equal
  2091 begin
  2092 
  2093 definition
  2094   [code]: "HOL.equal A B \<longleftrightarrow> (A::'a multiset) \<le> B \<and> B \<le> A"
  2095 
  2096 instance
  2097   by default (simp add: equal_multiset_def eq_iff)
  2098 
  2099 end
  2100 
  2101 lemma [code]:
  2102   "(A::'a multiset) < B \<longleftrightarrow> A \<le> B \<and> A \<noteq> B"
  2103   by auto
  2104 
  2105 lemma [code]:
  2106   "msetsum (multiset_of xs) = listsum xs"
  2107   by (induct xs) (simp_all add: add.commute)
  2108 
  2109 lemma [code]:
  2110   "msetprod (multiset_of xs) = fold times xs 1"
  2111 proof -
  2112   have "\<And>x. fold times xs x = msetprod (multiset_of xs) * x"
  2113     by (induct xs) (simp_all add: mult.assoc)
  2114   then show ?thesis by simp
  2115 qed
  2116 
  2117 lemma [code]:
  2118   "size = mcard"
  2119   by (fact size_eq_mcard)
  2120 
  2121 text {*
  2122   Exercise for the casual reader: add implementations for @{const le_multiset}
  2123   and @{const less_multiset} (multiset order).
  2124 *}
  2125 
  2126 text {* Quickcheck generators *}
  2127 
  2128 definition (in term_syntax)
  2129   msetify :: "'a\<Colon>typerep list \<times> (unit \<Rightarrow> Code_Evaluation.term)
  2130     \<Rightarrow> 'a multiset \<times> (unit \<Rightarrow> Code_Evaluation.term)" where
  2131   [code_unfold]: "msetify xs = Code_Evaluation.valtermify multiset_of {\<cdot>} xs"
  2132 
  2133 notation fcomp (infixl "\<circ>>" 60)
  2134 notation scomp (infixl "\<circ>\<rightarrow>" 60)
  2135 
  2136 instantiation multiset :: (random) random
  2137 begin
  2138 
  2139 definition
  2140   "Quickcheck_Random.random i = Quickcheck_Random.random i \<circ>\<rightarrow> (\<lambda>xs. Pair (msetify xs))"
  2141 
  2142 instance ..
  2143 
  2144 end
  2145 
  2146 no_notation fcomp (infixl "\<circ>>" 60)
  2147 no_notation scomp (infixl "\<circ>\<rightarrow>" 60)
  2148 
  2149 instantiation multiset :: (full_exhaustive) full_exhaustive
  2150 begin
  2151 
  2152 definition full_exhaustive_multiset :: "('a multiset \<times> (unit \<Rightarrow> term) \<Rightarrow> (bool \<times> term list) option) \<Rightarrow> natural \<Rightarrow> (bool \<times> term list) option"
  2153 where
  2154   "full_exhaustive_multiset f i = Quickcheck_Exhaustive.full_exhaustive (\<lambda>xs. f (msetify xs)) i"
  2155 
  2156 instance ..
  2157 
  2158 end
  2159 
  2160 hide_const (open) msetify
  2161 
  2162 
  2163 subsection {* BNF setup *}
  2164 
  2165 lemma setsum_gt_0_iff:
  2166 fixes f :: "'a \<Rightarrow> nat" assumes "finite A"
  2167 shows "setsum f A > 0 \<longleftrightarrow> (\<exists> a \<in> A. f a > 0)"
  2168 (is "?L \<longleftrightarrow> ?R")
  2169 proof-
  2170   have "?L \<longleftrightarrow> \<not> setsum f A = 0" by fast
  2171   also have "... \<longleftrightarrow> (\<exists> a \<in> A. f a \<noteq> 0)" using assms by simp
  2172   also have "... \<longleftrightarrow> ?R" by simp
  2173   finally show ?thesis .
  2174 qed
  2175 
  2176 lift_definition mmap :: "('a \<Rightarrow> 'b) \<Rightarrow> 'a multiset \<Rightarrow> 'b multiset" is
  2177   "\<lambda>h f b. setsum f {a. h a = b \<and> f a > 0} :: nat"
  2178 unfolding multiset_def proof safe
  2179   fix h :: "'a \<Rightarrow> 'b" and f :: "'a \<Rightarrow> nat"
  2180   assume fin: "finite {a. 0 < f a}"  (is "finite ?A")
  2181   show "finite {b. 0 < setsum f {a. h a = b \<and> 0 < f a}}"
  2182   (is "finite {b. 0 < setsum f (?As b)}")
  2183   proof- let ?B = "{b. 0 < setsum f (?As b)}"
  2184     have "\<And> b. finite (?As b)" using fin by simp
  2185     hence B: "?B = {b. ?As b \<noteq> {}}" by (auto simp add: setsum_gt_0_iff)
  2186     hence "?B \<subseteq> h ` ?A" by auto
  2187     thus ?thesis using finite_surj[OF fin] by auto
  2188   qed
  2189 qed
  2190 
  2191 lemma mmap_id0: "mmap id = id"
  2192 proof (intro ext multiset_eqI)
  2193   fix f a show "count (mmap id f) a = count (id f) a"
  2194   proof (cases "count f a = 0")
  2195     case False
  2196     hence 1: "{aa. aa = a \<and> aa \<in># f} = {a}" by auto
  2197     thus ?thesis by transfer auto
  2198   qed (transfer, simp)
  2199 qed
  2200 
  2201 lemma inj_on_setsum_inv:
  2202 assumes 1: "(0::nat) < setsum (count f) {a. h a = b' \<and> a \<in># f}" (is "0 < setsum (count f) ?A'")
  2203 and     2: "{a. h a = b \<and> a \<in># f} = {a. h a = b' \<and> a \<in># f}" (is "?A = ?A'")
  2204 shows "b = b'"
  2205 using assms by (auto simp add: setsum_gt_0_iff)
  2206 
  2207 lemma mmap_comp:
  2208 fixes h1 :: "'a \<Rightarrow> 'b" and h2 :: "'b \<Rightarrow> 'c"
  2209 shows "mmap (h2 o h1) = mmap h2 o mmap h1"
  2210 proof (intro ext multiset_eqI)
  2211   fix f :: "'a multiset" fix c :: 'c
  2212   let ?A = "{a. h2 (h1 a) = c \<and> a \<in># f}"
  2213   let ?As = "\<lambda> b. {a. h1 a = b \<and> a \<in># f}"
  2214   let ?B = "{b. h2 b = c \<and> 0 < setsum (count f) (?As b)}"
  2215   have 0: "{?As b | b.  b \<in> ?B} = ?As ` ?B" by auto
  2216   have "\<And> b. finite (?As b)" by transfer (simp add: multiset_def)
  2217   hence "?B = {b. h2 b = c \<and> ?As b \<noteq> {}}" by (auto simp add: setsum_gt_0_iff)
  2218   hence A: "?A = \<Union> {?As b | b.  b \<in> ?B}" by auto
  2219   have "setsum (count f) ?A = setsum (setsum (count f)) {?As b | b.  b \<in> ?B}"
  2220     unfolding A by transfer (intro setsum_Union_disjoint, auto simp: multiset_def)
  2221   also have "... = setsum (setsum (count f)) (?As ` ?B)" unfolding 0 ..
  2222   also have "... = setsum (setsum (count f) o ?As) ?B"
  2223     by(intro setsum_reindex) (auto simp add: setsum_gt_0_iff inj_on_def)
  2224   also have "... = setsum (\<lambda> b. setsum (count f) (?As b)) ?B" unfolding comp_def ..
  2225   finally have "setsum (count f) ?A = setsum (\<lambda> b. setsum (count f) (?As b)) ?B" .
  2226   thus "count (mmap (h2 \<circ> h1) f) c = count ((mmap h2 \<circ> mmap h1) f) c"
  2227     by transfer (unfold comp_apply, blast)
  2228 qed
  2229 
  2230 lemma mmap_cong:
  2231 assumes "\<And>a. a \<in># M \<Longrightarrow> f a = g a"
  2232 shows "mmap f M = mmap g M"
  2233 using assms by transfer (auto intro!: setsum_cong)
  2234 
  2235 context
  2236 begin
  2237 interpretation lifting_syntax .
  2238 
  2239 lemma set_of_transfer[transfer_rule]: "(pcr_multiset op = ===> op =) (\<lambda>f. {a. 0 < f a}) set_of"
  2240   unfolding set_of_def pcr_multiset_def cr_multiset_def fun_rel_def by auto
  2241 
  2242 end
  2243 
  2244 lemma set_of_mmap: "set_of o mmap h = image h o set_of"
  2245 proof (rule ext, unfold comp_apply)
  2246   fix M show "set_of (mmap h M) = h ` set_of M"
  2247     by transfer (auto simp add: multiset_def setsum_gt_0_iff)
  2248 qed
  2249 
  2250 lemma multiset_of_surj:
  2251   "multiset_of ` {as. set as \<subseteq> A} = {M. set_of M \<subseteq> A}"
  2252 proof safe
  2253   fix M assume M: "set_of M \<subseteq> A"
  2254   obtain as where eq: "M = multiset_of as" using surj_multiset_of unfolding surj_def by auto
  2255   hence "set as \<subseteq> A" using M by auto
  2256   thus "M \<in> multiset_of ` {as. set as \<subseteq> A}" using eq by auto
  2257 next
  2258   show "\<And>x xa xb. \<lbrakk>set xa \<subseteq> A; xb \<in> set_of (multiset_of xa)\<rbrakk> \<Longrightarrow> xb \<in> A"
  2259   by (erule set_mp) (unfold set_of_multiset_of)
  2260 qed
  2261 
  2262 lemma card_of_set_of:
  2263 "(card_of {M. set_of M \<subseteq> A}, card_of {as. set as \<subseteq> A}) \<in> ordLeq"
  2264 apply(rule card_of_ordLeqI2[of _ multiset_of]) using multiset_of_surj by auto
  2265 
  2266 lemma nat_sum_induct:
  2267 assumes "\<And>n1 n2. (\<And> m1 m2. m1 + m2 < n1 + n2 \<Longrightarrow> phi m1 m2) \<Longrightarrow> phi n1 n2"
  2268 shows "phi (n1::nat) (n2::nat)"
  2269 proof-
  2270   let ?chi = "\<lambda> n1n2 :: nat * nat. phi (fst n1n2) (snd n1n2)"
  2271   have "?chi (n1,n2)"
  2272   apply(induct rule: measure_induct[of "\<lambda> n1n2. fst n1n2 + snd n1n2" ?chi])
  2273   using assms by (metis fstI sndI)
  2274   thus ?thesis by simp
  2275 qed
  2276 
  2277 lemma matrix_count:
  2278 fixes ct1 ct2 :: "nat \<Rightarrow> nat"
  2279 assumes "setsum ct1 {..<Suc n1} = setsum ct2 {..<Suc n2}"
  2280 shows
  2281 "\<exists> ct. (\<forall> i1 \<le> n1. setsum (\<lambda> i2. ct i1 i2) {..<Suc n2} = ct1 i1) \<and>
  2282        (\<forall> i2 \<le> n2. setsum (\<lambda> i1. ct i1 i2) {..<Suc n1} = ct2 i2)"
  2283 (is "?phi ct1 ct2 n1 n2")
  2284 proof-
  2285   have "\<forall> ct1 ct2 :: nat \<Rightarrow> nat.
  2286         setsum ct1 {..<Suc n1} = setsum ct2 {..<Suc n2} \<longrightarrow> ?phi ct1 ct2 n1 n2"
  2287   proof(induct rule: nat_sum_induct[of
  2288 "\<lambda> n1 n2. \<forall> ct1 ct2 :: nat \<Rightarrow> nat.
  2289      setsum ct1 {..<Suc n1} = setsum ct2 {..<Suc n2} \<longrightarrow> ?phi ct1 ct2 n1 n2"],
  2290       clarify)
  2291   fix n1 n2 :: nat and ct1 ct2 :: "nat \<Rightarrow> nat"
  2292   assume IH: "\<And> m1 m2. m1 + m2 < n1 + n2 \<Longrightarrow>
  2293                 \<forall> dt1 dt2 :: nat \<Rightarrow> nat.
  2294                 setsum dt1 {..<Suc m1} = setsum dt2 {..<Suc m2} \<longrightarrow> ?phi dt1 dt2 m1 m2"
  2295   and ss: "setsum ct1 {..<Suc n1} = setsum ct2 {..<Suc n2}"
  2296   show "?phi ct1 ct2 n1 n2"
  2297   proof(cases n1)
  2298     case 0 note n1 = 0
  2299     show ?thesis
  2300     proof(cases n2)
  2301       case 0 note n2 = 0
  2302       let ?ct = "\<lambda> i1 i2. ct2 0"
  2303       show ?thesis apply(rule exI[of _ ?ct]) using n1 n2 ss by simp
  2304     next
  2305       case (Suc m2) note n2 = Suc
  2306       let ?ct = "\<lambda> i1 i2. ct2 i2"
  2307       show ?thesis apply(rule exI[of _ ?ct]) using n1 n2 ss by auto
  2308     qed
  2309   next
  2310     case (Suc m1) note n1 = Suc
  2311     show ?thesis
  2312     proof(cases n2)
  2313       case 0 note n2 = 0
  2314       let ?ct = "\<lambda> i1 i2. ct1 i1"
  2315       show ?thesis apply(rule exI[of _ ?ct]) using n1 n2 ss by auto
  2316     next
  2317       case (Suc m2) note n2 = Suc
  2318       show ?thesis
  2319       proof(cases "ct1 n1 \<le> ct2 n2")
  2320         case True
  2321         def dt2 \<equiv> "\<lambda> i2. if i2 = n2 then ct2 i2 - ct1 n1 else ct2 i2"
  2322         have "setsum ct1 {..<Suc m1} = setsum dt2 {..<Suc n2}"
  2323         unfolding dt2_def using ss n1 True by auto
  2324         hence "?phi ct1 dt2 m1 n2" using IH[of m1 n2] n1 by simp
  2325         then obtain dt where
  2326         1: "\<And> i1. i1 \<le> m1 \<Longrightarrow> setsum (\<lambda> i2. dt i1 i2) {..<Suc n2} = ct1 i1" and
  2327         2: "\<And> i2. i2 \<le> n2 \<Longrightarrow> setsum (\<lambda> i1. dt i1 i2) {..<Suc m1} = dt2 i2" by auto
  2328         let ?ct = "\<lambda> i1 i2. if i1 = n1 then (if i2 = n2 then ct1 n1 else 0)
  2329                                        else dt i1 i2"
  2330         show ?thesis apply(rule exI[of _ ?ct])
  2331         using n1 n2 1 2 True unfolding dt2_def by simp
  2332       next
  2333         case False
  2334         hence False: "ct2 n2 < ct1 n1" by simp
  2335         def dt1 \<equiv> "\<lambda> i1. if i1 = n1 then ct1 i1 - ct2 n2 else ct1 i1"
  2336         have "setsum dt1 {..<Suc n1} = setsum ct2 {..<Suc m2}"
  2337         unfolding dt1_def using ss n2 False by auto
  2338         hence "?phi dt1 ct2 n1 m2" using IH[of n1 m2] n2 by simp
  2339         then obtain dt where
  2340         1: "\<And> i1. i1 \<le> n1 \<Longrightarrow> setsum (\<lambda> i2. dt i1 i2) {..<Suc m2} = dt1 i1" and
  2341         2: "\<And> i2. i2 \<le> m2 \<Longrightarrow> setsum (\<lambda> i1. dt i1 i2) {..<Suc n1} = ct2 i2" by force
  2342         let ?ct = "\<lambda> i1 i2. if i2 = n2 then (if i1 = n1 then ct2 n2 else 0)
  2343                                        else dt i1 i2"
  2344         show ?thesis apply(rule exI[of _ ?ct])
  2345         using n1 n2 1 2 False unfolding dt1_def by simp
  2346       qed
  2347     qed
  2348   qed
  2349   qed
  2350   thus ?thesis using assms by auto
  2351 qed
  2352 
  2353 definition
  2354 "inj2 u B1 B2 \<equiv>
  2355  \<forall> b1 b1' b2 b2'. {b1,b1'} \<subseteq> B1 \<and> {b2,b2'} \<subseteq> B2 \<and> u b1 b2 = u b1' b2'
  2356                   \<longrightarrow> b1 = b1' \<and> b2 = b2'"
  2357 
  2358 lemma matrix_setsum_finite:
  2359 assumes B1: "B1 \<noteq> {}" "finite B1" and B2: "B2 \<noteq> {}" "finite B2" and u: "inj2 u B1 B2"
  2360 and ss: "setsum N1 B1 = setsum N2 B2"
  2361 shows "\<exists> M :: 'a \<Rightarrow> nat.
  2362             (\<forall> b1 \<in> B1. setsum (\<lambda> b2. M (u b1 b2)) B2 = N1 b1) \<and>
  2363             (\<forall> b2 \<in> B2. setsum (\<lambda> b1. M (u b1 b2)) B1 = N2 b2)"
  2364 proof-
  2365   obtain n1 where "card B1 = Suc n1" using B1 by (metis card_insert finite.simps)
  2366   then obtain e1 where e1: "bij_betw e1 {..<Suc n1} B1"
  2367   using ex_bij_betw_finite_nat[OF B1(2)] by (metis atLeast0LessThan bij_betw_the_inv_into)
  2368   hence e1_inj: "inj_on e1 {..<Suc n1}" and e1_surj: "e1 ` {..<Suc n1} = B1"
  2369   unfolding bij_betw_def by auto
  2370   def f1 \<equiv> "inv_into {..<Suc n1} e1"
  2371   have f1: "bij_betw f1 B1 {..<Suc n1}"
  2372   and f1e1[simp]: "\<And> i1. i1 < Suc n1 \<Longrightarrow> f1 (e1 i1) = i1"
  2373   and e1f1[simp]: "\<And> b1. b1 \<in> B1 \<Longrightarrow> e1 (f1 b1) = b1" unfolding f1_def
  2374   apply (metis bij_betw_inv_into e1, metis bij_betw_inv_into_left e1 lessThan_iff)
  2375   by (metis e1_surj f_inv_into_f)
  2376   (*  *)
  2377   obtain n2 where "card B2 = Suc n2" using B2 by (metis card_insert finite.simps)
  2378   then obtain e2 where e2: "bij_betw e2 {..<Suc n2} B2"
  2379   using ex_bij_betw_finite_nat[OF B2(2)] by (metis atLeast0LessThan bij_betw_the_inv_into)
  2380   hence e2_inj: "inj_on e2 {..<Suc n2}" and e2_surj: "e2 ` {..<Suc n2} = B2"
  2381   unfolding bij_betw_def by auto
  2382   def f2 \<equiv> "inv_into {..<Suc n2} e2"
  2383   have f2: "bij_betw f2 B2 {..<Suc n2}"
  2384   and f2e2[simp]: "\<And> i2. i2 < Suc n2 \<Longrightarrow> f2 (e2 i2) = i2"
  2385   and e2f2[simp]: "\<And> b2. b2 \<in> B2 \<Longrightarrow> e2 (f2 b2) = b2" unfolding f2_def
  2386   apply (metis bij_betw_inv_into e2, metis bij_betw_inv_into_left e2 lessThan_iff)
  2387   by (metis e2_surj f_inv_into_f)
  2388   (*  *)
  2389   let ?ct1 = "N1 o e1"  let ?ct2 = "N2 o e2"
  2390   have ss: "setsum ?ct1 {..<Suc n1} = setsum ?ct2 {..<Suc n2}"
  2391   unfolding setsum_reindex[OF e1_inj, symmetric] setsum_reindex[OF e2_inj, symmetric]
  2392   e1_surj e2_surj using ss .
  2393   obtain ct where
  2394   ct1: "\<And> i1. i1 \<le> n1 \<Longrightarrow> setsum (\<lambda> i2. ct i1 i2) {..<Suc n2} = ?ct1 i1" and
  2395   ct2: "\<And> i2. i2 \<le> n2 \<Longrightarrow> setsum (\<lambda> i1. ct i1 i2) {..<Suc n1} = ?ct2 i2"
  2396   using matrix_count[OF ss] by blast
  2397   (*  *)
  2398   def A \<equiv> "{u b1 b2 | b1 b2. b1 \<in> B1 \<and> b2 \<in> B2}"
  2399   have "\<forall> a \<in> A. \<exists> b1b2 \<in> B1 <*> B2. u (fst b1b2) (snd b1b2) = a"
  2400   unfolding A_def Ball_def mem_Collect_eq by auto
  2401   then obtain h1h2 where h12:
  2402   "\<And>a. a \<in> A \<Longrightarrow> u (fst (h1h2 a)) (snd (h1h2 a)) = a \<and> h1h2 a \<in> B1 <*> B2" by metis
  2403   def h1 \<equiv> "fst o h1h2"  def h2 \<equiv> "snd o h1h2"
  2404   have h12[simp]: "\<And>a. a \<in> A \<Longrightarrow> u (h1 a) (h2 a) = a"
  2405                   "\<And> a. a \<in> A \<Longrightarrow> h1 a \<in> B1"  "\<And> a. a \<in> A \<Longrightarrow> h2 a \<in> B2"
  2406   using h12 unfolding h1_def h2_def by force+
  2407   {fix b1 b2 assume b1: "b1 \<in> B1" and b2: "b2 \<in> B2"
  2408    hence inA: "u b1 b2 \<in> A" unfolding A_def by auto
  2409    hence "u b1 b2 = u (h1 (u b1 b2)) (h2 (u b1 b2))" by auto
  2410    moreover have "h1 (u b1 b2) \<in> B1" "h2 (u b1 b2) \<in> B2" using inA by auto
  2411    ultimately have "h1 (u b1 b2) = b1 \<and> h2 (u b1 b2) = b2"
  2412    using u b1 b2 unfolding inj2_def by fastforce
  2413   }
  2414   hence h1[simp]: "\<And> b1 b2. \<lbrakk>b1 \<in> B1; b2 \<in> B2\<rbrakk> \<Longrightarrow> h1 (u b1 b2) = b1" and
  2415         h2[simp]: "\<And> b1 b2. \<lbrakk>b1 \<in> B1; b2 \<in> B2\<rbrakk> \<Longrightarrow> h2 (u b1 b2) = b2" by auto
  2416   def M \<equiv> "\<lambda> a. ct (f1 (h1 a)) (f2 (h2 a))"
  2417   show ?thesis
  2418   apply(rule exI[of _ M]) proof safe
  2419     fix b1 assume b1: "b1 \<in> B1"
  2420     hence f1b1: "f1 b1 \<le> n1" using f1 unfolding bij_betw_def
  2421     by (metis image_eqI lessThan_iff less_Suc_eq_le)
  2422     have "(\<Sum>b2\<in>B2. M (u b1 b2)) = (\<Sum>i2<Suc n2. ct (f1 b1) (f2 (e2 i2)))"
  2423     unfolding e2_surj[symmetric] setsum_reindex[OF e2_inj]
  2424     unfolding M_def comp_def apply(intro setsum_cong) apply force
  2425     by (metis e2_surj b1 h1 h2 imageI)
  2426     also have "... = N1 b1" using b1 ct1[OF f1b1] by simp
  2427     finally show "(\<Sum>b2\<in>B2. M (u b1 b2)) = N1 b1" .
  2428   next
  2429     fix b2 assume b2: "b2 \<in> B2"
  2430     hence f2b2: "f2 b2 \<le> n2" using f2 unfolding bij_betw_def
  2431     by (metis image_eqI lessThan_iff less_Suc_eq_le)
  2432     have "(\<Sum>b1\<in>B1. M (u b1 b2)) = (\<Sum>i1<Suc n1. ct (f1 (e1 i1)) (f2 b2))"
  2433     unfolding e1_surj[symmetric] setsum_reindex[OF e1_inj]
  2434     unfolding M_def comp_def apply(intro setsum_cong) apply force
  2435     by (metis e1_surj b2 h1 h2 imageI)
  2436     also have "... = N2 b2" using b2 ct2[OF f2b2] by simp
  2437     finally show "(\<Sum>b1\<in>B1. M (u b1 b2)) = N2 b2" .
  2438   qed
  2439 qed
  2440 
  2441 lemma supp_vimage_mmap: "set_of M \<subseteq> f -` (set_of (mmap f M))"
  2442   by transfer (auto simp: multiset_def setsum_gt_0_iff)
  2443 
  2444 lemma mmap_ge_0: "b \<in># mmap f M \<longleftrightarrow> (\<exists>a. a \<in># M \<and> f a = b)"
  2445   by transfer (auto simp: multiset_def setsum_gt_0_iff)
  2446 
  2447 lemma finite_twosets:
  2448 assumes "finite B1" and "finite B2"
  2449 shows "finite {u b1 b2 |b1 b2. b1 \<in> B1 \<and> b2 \<in> B2}"  (is "finite ?A")
  2450 proof-
  2451   have A: "?A = (\<lambda> b1b2. u (fst b1b2) (snd b1b2)) ` (B1 <*> B2)" by force
  2452   show ?thesis unfolding A using finite_cartesian_product[OF assms] by auto
  2453 qed
  2454 
  2455 (* Weak pullbacks: *)
  2456 definition wpull where
  2457 "wpull A B1 B2 f1 f2 p1 p2 \<longleftrightarrow>
  2458  (\<forall> b1 b2. b1 \<in> B1 \<and> b2 \<in> B2 \<and> f1 b1 = f2 b2 \<longrightarrow> (\<exists> a \<in> A. p1 a = b1 \<and> p2 a = b2))"
  2459 
  2460 (* Weak pseudo-pullbacks *)
  2461 definition wppull where
  2462 "wppull A B1 B2 f1 f2 e1 e2 p1 p2 \<longleftrightarrow>
  2463  (\<forall> b1 b2. b1 \<in> B1 \<and> b2 \<in> B2 \<and> f1 b1 = f2 b2 \<longrightarrow>
  2464            (\<exists> a \<in> A. e1 (p1 a) = e1 b1 \<and> e2 (p2 a) = e2 b2))"
  2465 
  2466 
  2467 (* The pullback of sets *)
  2468 definition thePull where
  2469 "thePull B1 B2 f1 f2 = {(b1,b2). b1 \<in> B1 \<and> b2 \<in> B2 \<and> f1 b1 = f2 b2}"
  2470 
  2471 lemma wpull_thePull:
  2472 "wpull (thePull B1 B2 f1 f2) B1 B2 f1 f2 fst snd"
  2473 unfolding wpull_def thePull_def by auto
  2474 
  2475 lemma wppull_thePull:
  2476 assumes "wppull A B1 B2 f1 f2 e1 e2 p1 p2"
  2477 shows
  2478 "\<exists> j. \<forall> a' \<in> thePull B1 B2 f1 f2.
  2479    j a' \<in> A \<and>
  2480    e1 (p1 (j a')) = e1 (fst a') \<and> e2 (p2 (j a')) = e2 (snd a')"
  2481 (is "\<exists> j. \<forall> a' \<in> ?A'. ?phi a' (j a')")
  2482 proof(rule bchoice[of ?A' ?phi], default)
  2483   fix a' assume a': "a' \<in> ?A'"
  2484   hence "fst a' \<in> B1" unfolding thePull_def by auto
  2485   moreover
  2486   from a' have "snd a' \<in> B2" unfolding thePull_def by auto
  2487   moreover have "f1 (fst a') = f2 (snd a')"
  2488   using a' unfolding csquare_def thePull_def by auto
  2489   ultimately show "\<exists> ja'. ?phi a' ja'"
  2490   using assms unfolding wppull_def by blast
  2491 qed
  2492 
  2493 lemma wpull_wppull:
  2494 assumes wp: "wpull A' B1 B2 f1 f2 p1' p2'" and
  2495 1: "\<forall> a' \<in> A'. j a' \<in> A \<and> e1 (p1 (j a')) = e1 (p1' a') \<and> e2 (p2 (j a')) = e2 (p2' a')"
  2496 shows "wppull A B1 B2 f1 f2 e1 e2 p1 p2"
  2497 unfolding wppull_def proof safe
  2498   fix b1 b2
  2499   assume b1: "b1 \<in> B1" and b2: "b2 \<in> B2" and f: "f1 b1 = f2 b2"
  2500   then obtain a' where a': "a' \<in> A'" and b1: "b1 = p1' a'" and b2: "b2 = p2' a'"
  2501   using wp unfolding wpull_def by blast
  2502   show "\<exists>a\<in>A. e1 (p1 a) = e1 b1 \<and> e2 (p2 a) = e2 b2"
  2503   apply (rule bexI[of _ "j a'"]) unfolding b1 b2 using a' 1 by auto
  2504 qed
  2505 
  2506 lemma wppull_fstOp_sndOp:
  2507 shows "wppull (Collect (split (P OO Q))) (Collect (split P)) (Collect (split Q))
  2508   snd fst fst snd (BNF_Def.fstOp P Q) (BNF_Def.sndOp P Q)"
  2509 using pick_middlep unfolding wppull_def fstOp_def sndOp_def relcompp.simps by auto
  2510 
  2511 lemma wpull_mmap:
  2512 fixes A :: "'a set" and B1 :: "'b1 set" and B2 :: "'b2 set"
  2513 assumes wp: "wpull A B1 B2 f1 f2 p1 p2"
  2514 shows
  2515 "wpull {M. set_of M \<subseteq> A}
  2516        {N1. set_of N1 \<subseteq> B1} {N2. set_of N2 \<subseteq> B2}
  2517        (mmap f1) (mmap f2) (mmap p1) (mmap p2)"
  2518 unfolding wpull_def proof (safe, unfold Bex_def mem_Collect_eq)
  2519   fix N1 :: "'b1 multiset" and N2 :: "'b2 multiset"
  2520   assume mmap': "mmap f1 N1 = mmap f2 N2"
  2521   and N1[simp]: "set_of N1 \<subseteq> B1"
  2522   and N2[simp]: "set_of N2 \<subseteq> B2"
  2523   def P \<equiv> "mmap f1 N1"
  2524   have P1: "P = mmap f1 N1" and P2: "P = mmap f2 N2" unfolding P_def using mmap' by auto
  2525   note P = P1 P2
  2526   have fin_N1[simp]: "finite (set_of N1)"
  2527    and fin_N2[simp]: "finite (set_of N2)"
  2528    and fin_P[simp]: "finite (set_of P)" by auto
  2529 
  2530   def set1 \<equiv> "\<lambda> c. {b1 \<in> set_of N1. f1 b1 = c}"
  2531   have set1[simp]: "\<And> c b1. b1 \<in> set1 c \<Longrightarrow> f1 b1 = c" unfolding set1_def by auto
  2532   have fin_set1: "\<And> c. c \<in> set_of P \<Longrightarrow> finite (set1 c)"
  2533     using N1(1) unfolding set1_def multiset_def by auto
  2534   have set1_NE: "\<And> c. c \<in> set_of P \<Longrightarrow> set1 c \<noteq> {}"
  2535    unfolding set1_def set_of_def P mmap_ge_0 by auto
  2536   have supp_N1_set1: "set_of N1 = (\<Union> c \<in> set_of P. set1 c)"
  2537     using supp_vimage_mmap[of N1 f1] unfolding set1_def P1 by auto
  2538   hence set1_inclN1: "\<And>c. c \<in> set_of P \<Longrightarrow> set1 c \<subseteq> set_of N1" by auto
  2539   hence set1_incl: "\<And> c. c \<in> set_of P \<Longrightarrow> set1 c \<subseteq> B1" using N1 by blast
  2540   have set1_disj: "\<And> c c'. c \<noteq> c' \<Longrightarrow> set1 c \<inter> set1 c' = {}"
  2541     unfolding set1_def by auto
  2542   have setsum_set1: "\<And> c. setsum (count N1) (set1 c) = count P c"
  2543     unfolding P1 set1_def by transfer (auto intro: setsum_cong)
  2544 
  2545   def set2 \<equiv> "\<lambda> c. {b2 \<in> set_of N2. f2 b2 = c}"
  2546   have set2[simp]: "\<And> c b2. b2 \<in> set2 c \<Longrightarrow> f2 b2 = c" unfolding set2_def by auto
  2547   have fin_set2: "\<And> c. c \<in> set_of P \<Longrightarrow> finite (set2 c)"
  2548   using N2(1) unfolding set2_def multiset_def by auto
  2549   have set2_NE: "\<And> c. c \<in> set_of P \<Longrightarrow> set2 c \<noteq> {}"
  2550     unfolding set2_def P2 mmap_ge_0 set_of_def by auto
  2551   have supp_N2_set2: "set_of N2 = (\<Union> c \<in> set_of P. set2 c)"
  2552     using supp_vimage_mmap[of N2 f2] unfolding set2_def P2 by auto
  2553   hence set2_inclN2: "\<And>c. c \<in> set_of P \<Longrightarrow> set2 c \<subseteq> set_of N2" by auto
  2554   hence set2_incl: "\<And> c. c \<in> set_of P \<Longrightarrow> set2 c \<subseteq> B2" using N2 by blast
  2555   have set2_disj: "\<And> c c'. c \<noteq> c' \<Longrightarrow> set2 c \<inter> set2 c' = {}"
  2556     unfolding set2_def by auto
  2557   have setsum_set2: "\<And> c. setsum (count N2) (set2 c) = count P c"
  2558     unfolding P2 set2_def by transfer (auto intro: setsum_cong)
  2559 
  2560   have ss: "\<And> c. c \<in> set_of P \<Longrightarrow> setsum (count N1) (set1 c) = setsum (count N2) (set2 c)"
  2561     unfolding setsum_set1 setsum_set2 ..
  2562   have "\<forall> c \<in> set_of P. \<forall> b1b2 \<in> (set1 c) \<times> (set2 c).
  2563           \<exists> a \<in> A. p1 a = fst b1b2 \<and> p2 a = snd b1b2"
  2564     using wp set1_incl set2_incl unfolding wpull_def Ball_def mem_Collect_eq
  2565     by simp (metis set1 set2 set_rev_mp)
  2566   then obtain uu where uu:
  2567   "\<forall> c \<in> set_of P. \<forall> b1b2 \<in> (set1 c) \<times> (set2 c).
  2568      uu c b1b2 \<in> A \<and> p1 (uu c b1b2) = fst b1b2 \<and> p2 (uu c b1b2) = snd b1b2" by metis
  2569   def u \<equiv> "\<lambda> c b1 b2. uu c (b1,b2)"
  2570   have u[simp]:
  2571   "\<And> c b1 b2. \<lbrakk>c \<in> set_of P; b1 \<in> set1 c; b2 \<in> set2 c\<rbrakk> \<Longrightarrow> u c b1 b2 \<in> A"
  2572   "\<And> c b1 b2. \<lbrakk>c \<in> set_of P; b1 \<in> set1 c; b2 \<in> set2 c\<rbrakk> \<Longrightarrow> p1 (u c b1 b2) = b1"
  2573   "\<And> c b1 b2. \<lbrakk>c \<in> set_of P; b1 \<in> set1 c; b2 \<in> set2 c\<rbrakk> \<Longrightarrow> p2 (u c b1 b2) = b2"
  2574     using uu unfolding u_def by auto
  2575   {fix c assume c: "c \<in> set_of P"
  2576    have "inj2 (u c) (set1 c) (set2 c)" unfolding inj2_def proof clarify
  2577      fix b1 b1' b2 b2'
  2578      assume "{b1, b1'} \<subseteq> set1 c" "{b2, b2'} \<subseteq> set2 c" and 0: "u c b1 b2 = u c b1' b2'"
  2579      hence "p1 (u c b1 b2) = b1 \<and> p2 (u c b1 b2) = b2 \<and>
  2580             p1 (u c b1' b2') = b1' \<and> p2 (u c b1' b2') = b2'"
  2581      using u(2)[OF c] u(3)[OF c] by simp metis
  2582      thus "b1 = b1' \<and> b2 = b2'" using 0 by auto
  2583    qed
  2584   } note inj = this
  2585   def sset \<equiv> "\<lambda> c. {u c b1 b2 | b1 b2. b1 \<in> set1 c \<and> b2 \<in> set2 c}"
  2586   have fin_sset[simp]: "\<And> c. c \<in> set_of P \<Longrightarrow> finite (sset c)" unfolding sset_def
  2587     using fin_set1 fin_set2 finite_twosets by blast
  2588   have sset_A: "\<And> c. c \<in> set_of P \<Longrightarrow> sset c \<subseteq> A" unfolding sset_def by auto
  2589   {fix c a assume c: "c \<in> set_of P" and ac: "a \<in> sset c"
  2590    then obtain b1 b2 where b1: "b1 \<in> set1 c" and b2: "b2 \<in> set2 c"
  2591    and a: "a = u c b1 b2" unfolding sset_def by auto
  2592    have "p1 a \<in> set1 c" and p2a: "p2 a \<in> set2 c"
  2593    using ac a b1 b2 c u(2) u(3) by simp+
  2594    hence "u c (p1 a) (p2 a) = a" unfolding a using b1 b2 inj[OF c]
  2595    unfolding inj2_def by (metis c u(2) u(3))
  2596   } note u_p12[simp] = this
  2597   {fix c a assume c: "c \<in> set_of P" and ac: "a \<in> sset c"
  2598    hence "p1 a \<in> set1 c" unfolding sset_def by auto
  2599   }note p1[simp] = this
  2600   {fix c a assume c: "c \<in> set_of P" and ac: "a \<in> sset c"
  2601    hence "p2 a \<in> set2 c" unfolding sset_def by auto
  2602   }note p2[simp] = this
  2603 
  2604   {fix c assume c: "c \<in> set_of P"
  2605    hence "\<exists> M. (\<forall> b1 \<in> set1 c. setsum (\<lambda> b2. M (u c b1 b2)) (set2 c) = count N1 b1) \<and>
  2606                (\<forall> b2 \<in> set2 c. setsum (\<lambda> b1. M (u c b1 b2)) (set1 c) = count N2 b2)"
  2607    unfolding sset_def
  2608    using matrix_setsum_finite[OF set1_NE[OF c] fin_set1[OF c]
  2609                                  set2_NE[OF c] fin_set2[OF c] inj[OF c] ss[OF c]] by auto
  2610   }
  2611   then obtain Ms where
  2612   ss1: "\<And> c b1. \<lbrakk>c \<in> set_of P; b1 \<in> set1 c\<rbrakk> \<Longrightarrow>
  2613                    setsum (\<lambda> b2. Ms c (u c b1 b2)) (set2 c) = count N1 b1" and
  2614   ss2: "\<And> c b2. \<lbrakk>c \<in> set_of P; b2 \<in> set2 c\<rbrakk> \<Longrightarrow>
  2615                    setsum (\<lambda> b1. Ms c (u c b1 b2)) (set1 c) = count N2 b2"
  2616   by metis
  2617   def SET \<equiv> "\<Union> c \<in> set_of P. sset c"
  2618   have fin_SET[simp]: "finite SET" unfolding SET_def apply(rule finite_UN_I) by auto
  2619   have SET_A: "SET \<subseteq> A" unfolding SET_def using sset_A by blast
  2620   have u_SET[simp]: "\<And> c b1 b2. \<lbrakk>c \<in> set_of P; b1 \<in> set1 c; b2 \<in> set2 c\<rbrakk> \<Longrightarrow> u c b1 b2 \<in> SET"
  2621     unfolding SET_def sset_def by blast
  2622   {fix c a assume c: "c \<in> set_of P" and a: "a \<in> SET" and p1a: "p1 a \<in> set1 c"
  2623    then obtain c' where c': "c' \<in> set_of P" and ac': "a \<in> sset c'"
  2624     unfolding SET_def by auto
  2625    hence "p1 a \<in> set1 c'" unfolding sset_def by auto
  2626    hence eq: "c = c'" using p1a c c' set1_disj by auto
  2627    hence "a \<in> sset c" using ac' by simp
  2628   } note p1_rev = this
  2629   {fix c a assume c: "c \<in> set_of P" and a: "a \<in> SET" and p2a: "p2 a \<in> set2 c"
  2630    then obtain c' where c': "c' \<in> set_of P" and ac': "a \<in> sset c'"
  2631    unfolding SET_def by auto
  2632    hence "p2 a \<in> set2 c'" unfolding sset_def by auto
  2633    hence eq: "c = c'" using p2a c c' set2_disj by auto
  2634    hence "a \<in> sset c" using ac' by simp
  2635   } note p2_rev = this
  2636 
  2637   have "\<forall> a \<in> SET. \<exists> c \<in> set_of P. a \<in> sset c" unfolding SET_def by auto
  2638   then obtain h where h: "\<forall> a \<in> SET. h a \<in> set_of P \<and> a \<in> sset (h a)" by metis
  2639   have h_u[simp]: "\<And> c b1 b2. \<lbrakk>c \<in> set_of P; b1 \<in> set1 c; b2 \<in> set2 c\<rbrakk>
  2640                       \<Longrightarrow> h (u c b1 b2) = c"
  2641   by (metis h p2 set2 u(3) u_SET)
  2642   have h_u1: "\<And> c b1 b2. \<lbrakk>c \<in> set_of P; b1 \<in> set1 c; b2 \<in> set2 c\<rbrakk>
  2643                       \<Longrightarrow> h (u c b1 b2) = f1 b1"
  2644   using h unfolding sset_def by auto
  2645   have h_u2: "\<And> c b1 b2. \<lbrakk>c \<in> set_of P; b1 \<in> set1 c; b2 \<in> set2 c\<rbrakk>
  2646                       \<Longrightarrow> h (u c b1 b2) = f2 b2"
  2647   using h unfolding sset_def by auto
  2648   def M \<equiv>
  2649     "Abs_multiset (\<lambda> a. if a \<in> SET \<and> p1 a \<in> set_of N1 \<and> p2 a \<in> set_of N2 then Ms (h a) a else 0)"
  2650   have "(\<lambda> a. if a \<in> SET \<and> p1 a \<in> set_of N1 \<and> p2 a \<in> set_of N2 then Ms (h a) a else 0) \<in> multiset"
  2651     unfolding multiset_def by auto
  2652   hence [transfer_rule]: "pcr_multiset op = (\<lambda> a. if a \<in> SET \<and> p1 a \<in> set_of N1 \<and> p2 a \<in> set_of N2 then Ms (h a) a else 0) M"
  2653     unfolding M_def pcr_multiset_def cr_multiset_def by (auto simp: Abs_multiset_inverse)
  2654   have sM: "set_of M \<subseteq> SET" "set_of M \<subseteq> p1 -` (set_of N1)" "set_of M \<subseteq> p2 -` set_of N2"
  2655     by (transfer, auto split: split_if_asm)+
  2656   show "\<exists>M. set_of M \<subseteq> A \<and> mmap p1 M = N1 \<and> mmap p2 M = N2"
  2657   proof(rule exI[of _ M], safe)
  2658     fix a assume *: "a \<in> set_of M"
  2659     from SET_A show "a \<in> A"
  2660     proof (cases "a \<in> SET")
  2661       case False thus ?thesis using * by transfer' auto
  2662     qed blast
  2663   next
  2664     show "mmap p1 M = N1"
  2665     proof(intro multiset_eqI)
  2666       fix b1
  2667       let ?K = "{a. p1 a = b1 \<and> a \<in># M}"
  2668       have "setsum (count M) ?K = count N1 b1"
  2669       proof(cases "b1 \<in> set_of N1")
  2670         case False
  2671         hence "?K = {}" using sM(2) by auto
  2672         thus ?thesis using False by auto
  2673       next
  2674         case True
  2675         def c \<equiv> "f1 b1"
  2676         have c: "c \<in> set_of P" and b1: "b1 \<in> set1 c"
  2677           unfolding set1_def c_def P1 using True by (auto simp: comp_eq_dest[OF set_of_mmap])
  2678         with sM(1) have "setsum (count M) ?K = setsum (count M) {a. p1 a = b1 \<and> a \<in> SET}"
  2679           by transfer (force intro: setsum_mono_zero_cong_left split: split_if_asm)
  2680         also have "... = setsum (count M) ((\<lambda> b2. u c b1 b2) ` (set2 c))"
  2681           apply(rule setsum_cong) using c b1 proof safe
  2682           fix a assume p1a: "p1 a \<in> set1 c" and "c \<in> set_of P" and "a \<in> SET"
  2683           hence ac: "a \<in> sset c" using p1_rev by auto
  2684           hence "a = u c (p1 a) (p2 a)" using c by auto
  2685           moreover have "p2 a \<in> set2 c" using ac c by auto
  2686           ultimately show "a \<in> u c (p1 a) ` set2 c" by auto
  2687         qed auto
  2688         also have "... = setsum (\<lambda> b2. count M (u c b1 b2)) (set2 c)"
  2689           unfolding comp_def[symmetric] apply(rule setsum_reindex)
  2690           using inj unfolding inj_on_def inj2_def using b1 c u(3) by blast
  2691         also have "... = count N1 b1" unfolding ss1[OF c b1, symmetric]
  2692           apply(rule setsum_cong[OF refl]) apply (transfer fixing: Ms u c b1 set2)
  2693           using True h_u[OF c b1] set2_def u(2,3)[OF c b1] u_SET[OF c b1] by fastforce
  2694         finally show ?thesis .
  2695       qed
  2696       thus "count (mmap p1 M) b1 = count N1 b1" by transfer
  2697     qed
  2698   next
  2699     show "mmap p2 M = N2"
  2700     proof(intro multiset_eqI)
  2701       fix b2
  2702       let ?K = "{a. p2 a = b2 \<and> a \<in># M}"
  2703       have "setsum (count M) ?K = count N2 b2"
  2704       proof(cases "b2 \<in> set_of N2")
  2705         case False
  2706         hence "?K = {}" using sM(3) by auto
  2707         thus ?thesis using False by auto
  2708       next
  2709         case True
  2710         def c \<equiv> "f2 b2"
  2711         have c: "c \<in> set_of P" and b2: "b2 \<in> set2 c"
  2712           unfolding set2_def c_def P2 using True by (auto simp: comp_eq_dest[OF set_of_mmap])
  2713         with sM(1) have "setsum (count M) ?K = setsum (count M) {a. p2 a = b2 \<and> a \<in> SET}"
  2714           by transfer (force intro: setsum_mono_zero_cong_left split: split_if_asm)
  2715         also have "... = setsum (count M) ((\<lambda> b1. u c b1 b2) ` (set1 c))"
  2716           apply(rule setsum_cong) using c b2 proof safe
  2717           fix a assume p2a: "p2 a \<in> set2 c" and "c \<in> set_of P" and "a \<in> SET"
  2718           hence ac: "a \<in> sset c" using p2_rev by auto
  2719           hence "a = u c (p1 a) (p2 a)" using c by auto
  2720           moreover have "p1 a \<in> set1 c" using ac c by auto
  2721           ultimately show "a \<in> (\<lambda>x. u c x (p2 a)) ` set1 c" by auto
  2722         qed auto
  2723         also have "... = setsum (count M o (\<lambda> b1. u c b1 b2)) (set1 c)"
  2724           apply(rule setsum_reindex)
  2725           using inj unfolding inj_on_def inj2_def using b2 c u(2) by blast
  2726         also have "... = setsum (\<lambda> b1. count M (u c b1 b2)) (set1 c)" by simp
  2727         also have "... = count N2 b2" unfolding ss2[OF c b2, symmetric] comp_def
  2728           apply(rule setsum_cong[OF refl]) apply (transfer fixing: Ms u c b2 set1)
  2729           using True h_u1[OF c _ b2] u(2,3)[OF c _ b2] u_SET[OF c _ b2] set1_def by fastforce
  2730         finally show ?thesis .
  2731       qed
  2732       thus "count (mmap p2 M) b2 = count N2 b2" by transfer
  2733     qed
  2734   qed
  2735 qed
  2736 
  2737 lemma set_of_bd: "(card_of (set_of x), natLeq) \<in> ordLeq"
  2738   by transfer
  2739     (auto intro!: ordLess_imp_ordLeq simp: finite_iff_ordLess_natLeq[symmetric] multiset_def)
  2740 
  2741 lemma wppull_mmap:
  2742   assumes "wppull A B1 B2 f1 f2 e1 e2 p1 p2"
  2743   shows "wppull {M. set_of M \<subseteq> A} {N1. set_of N1 \<subseteq> B1} {N2. set_of N2 \<subseteq> B2}
  2744     (mmap f1) (mmap f2) (mmap e1) (mmap e2) (mmap p1) (mmap p2)"
  2745 proof -
  2746   from assms obtain j where j: "\<forall>a'\<in>thePull B1 B2 f1 f2.
  2747     j a' \<in> A \<and> e1 (p1 (j a')) = e1 (fst a') \<and> e2 (p2 (j a')) = e2 (snd a')" 
  2748     by (blast dest: wppull_thePull)
  2749   then show ?thesis
  2750     by (intro wpull_wppull[OF wpull_mmap[OF wpull_thePull], of _ _ _ _ "mmap j"])
  2751       (auto simp: comp_eq_dest_lhs[OF mmap_comp[symmetric]] comp_eq_dest[OF set_of_mmap]
  2752         intro!: mmap_cong simp del: mem_set_of_iff simp: mem_set_of_iff[symmetric])
  2753 qed
  2754 
  2755 bnf "'a multiset"
  2756   map: mmap
  2757   sets: set_of 
  2758   bd: natLeq
  2759   wits: "{#}"
  2760 by (auto simp add: mmap_id0 mmap_comp set_of_mmap natLeq_card_order natLeq_cinfinite set_of_bd
  2761   Grp_def relcompp.simps intro: mmap_cong)
  2762   (metis wppull_mmap[OF wppull_fstOp_sndOp, unfolded wppull_def
  2763     o_eq_dest_lhs[OF mmap_comp[symmetric]] fstOp_def sndOp_def comp_def, simplified])
  2764 
  2765 inductive rel_multiset' where
  2766   Zero[intro]: "rel_multiset' R {#} {#}"
  2767 | Plus[intro]: "\<lbrakk>R a b; rel_multiset' R M N\<rbrakk> \<Longrightarrow> rel_multiset' R (M + {#a#}) (N + {#b#})"
  2768 
  2769 lemma map_multiset_Zero_iff[simp]: "mmap f M = {#} \<longleftrightarrow> M = {#}"
  2770 by (metis image_is_empty multiset.set_map set_of_eq_empty_iff)
  2771 
  2772 lemma map_multiset_Zero[simp]: "mmap f {#} = {#}" by simp
  2773 
  2774 lemma rel_multiset_Zero: "rel_multiset R {#} {#}"
  2775 unfolding rel_multiset_def Grp_def by auto
  2776 
  2777 declare multiset.count[simp]
  2778 declare Abs_multiset_inverse[simp]
  2779 declare multiset.count_inverse[simp]
  2780 declare union_preserves_multiset[simp]
  2781 
  2782 lemma map_multiset_Plus[simp]: "mmap f (M1 + M2) = mmap f M1 + mmap f M2"
  2783 proof (intro multiset_eqI, transfer fixing: f)
  2784   fix x :: 'a and M1 M2 :: "'b \<Rightarrow> nat"
  2785   assume "M1 \<in> multiset" "M2 \<in> multiset"
  2786   hence "setsum M1 {a. f a = x \<and> 0 < M1 a} = setsum M1 {a. f a = x \<and> 0 < M1 a + M2 a}"
  2787         "setsum M2 {a. f a = x \<and> 0 < M2 a} = setsum M2 {a. f a = x \<and> 0 < M1 a + M2 a}"
  2788     by (auto simp: multiset_def intro!: setsum_mono_zero_cong_left)
  2789   then show "(\<Sum>a | f a = x \<and> 0 < M1 a + M2 a. M1 a + M2 a) =
  2790        setsum M1 {a. f a = x \<and> 0 < M1 a} +
  2791        setsum M2 {a. f a = x \<and> 0 < M2 a}"
  2792     by (auto simp: setsum.distrib[symmetric])
  2793 qed
  2794 
  2795 lemma map_multiset_single[simp]: "mmap f {#a#} = {#f a#}"
  2796   by transfer auto
  2797 
  2798 lemma rel_multiset_Plus:
  2799 assumes ab: "R a b" and MN: "rel_multiset R M N"
  2800 shows "rel_multiset R (M + {#a#}) (N + {#b#})"
  2801 proof-
  2802   {fix y assume "R a b" and "set_of y \<subseteq> {(x, y). R x y}"
  2803    hence "\<exists>ya. mmap fst y + {#a#} = mmap fst ya \<and>
  2804                mmap snd y + {#b#} = mmap snd ya \<and>
  2805                set_of ya \<subseteq> {(x, y). R x y}"
  2806    apply(intro exI[of _ "y + {#(a,b)#}"]) by auto
  2807   }
  2808   thus ?thesis
  2809   using assms
  2810   unfolding rel_multiset_def Grp_def by force
  2811 qed
  2812 
  2813 lemma rel_multiset'_imp_rel_multiset:
  2814 "rel_multiset' R M N \<Longrightarrow> rel_multiset R M N"
  2815 apply(induct rule: rel_multiset'.induct)
  2816 using rel_multiset_Zero rel_multiset_Plus by auto
  2817 
  2818 lemma mcard_mmap[simp]: "mcard (mmap f M) = mcard M"
  2819 proof -
  2820   def A \<equiv> "\<lambda> b. {a. f a = b \<and> a \<in># M}"
  2821   let ?B = "{b. 0 < setsum (count M) (A b)}"
  2822   have "{b. \<exists>a. f a = b \<and> a \<in># M} \<subseteq> f ` {a. a \<in># M}" by auto
  2823   moreover have "finite (f ` {a. a \<in># M})" apply(rule finite_imageI)
  2824   using finite_Collect_mem .
  2825   ultimately have fin: "finite {b. \<exists>a. f a = b \<and> a \<in># M}" by(rule finite_subset)
  2826   have i: "inj_on A ?B" unfolding inj_on_def A_def apply clarsimp
  2827     by (metis (lifting, full_types) mem_Collect_eq neq0_conv setsum.neutral)
  2828   have 0: "\<And> b. 0 < setsum (count M) (A b) \<longleftrightarrow> (\<exists> a \<in> A b. count M a > 0)"
  2829   apply safe
  2830     apply (metis less_not_refl setsum_gt_0_iff setsum_infinite)
  2831     by (metis A_def finite_Collect_conjI finite_Collect_mem setsum_gt_0_iff)
  2832   hence AB: "A ` ?B = {A b | b. \<exists> a \<in> A b. count M a > 0}" by auto
  2833 
  2834   have "setsum (\<lambda> x. setsum (count M) (A x)) ?B = setsum (setsum (count M) o A) ?B"
  2835   unfolding comp_def ..
  2836   also have "... = (\<Sum>x\<in> A ` ?B. setsum (count M) x)"
  2837   unfolding setsum.reindex [OF i, symmetric] ..
  2838   also have "... = setsum (count M) (\<Union>x\<in>A ` {b. 0 < setsum (count M) (A b)}. x)"
  2839   (is "_ = setsum (count M) ?J")
  2840   apply(rule setsum.UNION_disjoint[symmetric])
  2841   using 0 fin unfolding A_def by auto
  2842   also have "?J = {a. a \<in># M}" unfolding AB unfolding A_def by auto
  2843   finally have "setsum (\<lambda> x. setsum (count M) (A x)) ?B =
  2844                 setsum (count M) {a. a \<in># M}" .
  2845   then show ?thesis unfolding mcard_unfold_setsum A_def by transfer
  2846 qed
  2847 
  2848 lemma rel_multiset_mcard:
  2849 assumes "rel_multiset R M N"
  2850 shows "mcard M = mcard N"
  2851 using assms unfolding rel_multiset_def Grp_def by auto
  2852 
  2853 lemma multiset_induct2[case_names empty addL addR]:
  2854 assumes empty: "P {#} {#}"
  2855 and addL: "\<And>M N a. P M N \<Longrightarrow> P (M + {#a#}) N"
  2856 and addR: "\<And>M N a. P M N \<Longrightarrow> P M (N + {#a#})"
  2857 shows "P M N"
  2858 apply(induct N rule: multiset_induct)
  2859   apply(induct M rule: multiset_induct, rule empty, erule addL)
  2860   apply(induct M rule: multiset_induct, erule addR, erule addR)
  2861 done
  2862 
  2863 lemma multiset_induct2_mcard[consumes 1, case_names empty add]:
  2864 assumes c: "mcard M = mcard N"
  2865 and empty: "P {#} {#}"
  2866 and add: "\<And>M N a b. P M N \<Longrightarrow> P (M + {#a#}) (N + {#b#})"
  2867 shows "P M N"
  2868 using c proof(induct M arbitrary: N rule: measure_induct_rule[of mcard])
  2869   case (less M)  show ?case
  2870   proof(cases "M = {#}")
  2871     case True hence "N = {#}" using less.prems by auto
  2872     thus ?thesis using True empty by auto
  2873   next
  2874     case False then obtain M1 a where M: "M = M1 + {#a#}" by (metis multi_nonempty_split)
  2875     have "N \<noteq> {#}" using False less.prems by auto
  2876     then obtain N1 b where N: "N = N1 + {#b#}" by (metis multi_nonempty_split)
  2877     have "mcard M1 = mcard N1" using less.prems unfolding M N by auto
  2878     thus ?thesis using M N less.hyps add by auto
  2879   qed
  2880 qed
  2881 
  2882 lemma msed_map_invL:
  2883 assumes "mmap f (M + {#a#}) = N"
  2884 shows "\<exists> N1. N = N1 + {#f a#} \<and> mmap f M = N1"
  2885 proof-
  2886   have "f a \<in># N"
  2887   using assms multiset.set_map[of f "M + {#a#}"] by auto
  2888   then obtain N1 where N: "N = N1 + {#f a#}" using multi_member_split by metis
  2889   have "mmap f M = N1" using assms unfolding N by simp
  2890   thus ?thesis using N by blast
  2891 qed
  2892 
  2893 lemma msed_map_invR:
  2894 assumes "mmap f M = N + {#b#}"
  2895 shows "\<exists> M1 a. M = M1 + {#a#} \<and> f a = b \<and> mmap f M1 = N"
  2896 proof-
  2897   obtain a where a: "a \<in># M" and fa: "f a = b"
  2898   using multiset.set_map[of f M] unfolding assms
  2899   by (metis image_iff mem_set_of_iff union_single_eq_member)
  2900   then obtain M1 where M: "M = M1 + {#a#}" using multi_member_split by metis
  2901   have "mmap f M1 = N" using assms unfolding M fa[symmetric] by simp
  2902   thus ?thesis using M fa by blast
  2903 qed
  2904 
  2905 lemma msed_rel_invL:
  2906 assumes "rel_multiset R (M + {#a#}) N"
  2907 shows "\<exists> N1 b. N = N1 + {#b#} \<and> R a b \<and> rel_multiset R M N1"
  2908 proof-
  2909   obtain K where KM: "mmap fst K = M + {#a#}"
  2910   and KN: "mmap snd K = N" and sK: "set_of K \<subseteq> {(a, b). R a b}"
  2911   using assms
  2912   unfolding rel_multiset_def Grp_def by auto
  2913   obtain K1 ab where K: "K = K1 + {#ab#}" and a: "fst ab = a"
  2914   and K1M: "mmap fst K1 = M" using msed_map_invR[OF KM] by auto
  2915   obtain N1 where N: "N = N1 + {#snd ab#}" and K1N1: "mmap snd K1 = N1"
  2916   using msed_map_invL[OF KN[unfolded K]] by auto
  2917   have Rab: "R a (snd ab)" using sK a unfolding K by auto
  2918   have "rel_multiset R M N1" using sK K1M K1N1
  2919   unfolding K rel_multiset_def Grp_def by auto
  2920   thus ?thesis using N Rab by auto
  2921 qed
  2922 
  2923 lemma msed_rel_invR:
  2924 assumes "rel_multiset R M (N + {#b#})"
  2925 shows "\<exists> M1 a. M = M1 + {#a#} \<and> R a b \<and> rel_multiset R M1 N"
  2926 proof-
  2927   obtain K where KN: "mmap snd K = N + {#b#}"
  2928   and KM: "mmap fst K = M" and sK: "set_of K \<subseteq> {(a, b). R a b}"
  2929   using assms
  2930   unfolding rel_multiset_def Grp_def by auto
  2931   obtain K1 ab where K: "K = K1 + {#ab#}" and b: "snd ab = b"
  2932   and K1N: "mmap snd K1 = N" using msed_map_invR[OF KN] by auto
  2933   obtain M1 where M: "M = M1 + {#fst ab#}" and K1M1: "mmap fst K1 = M1"
  2934   using msed_map_invL[OF KM[unfolded K]] by auto
  2935   have Rab: "R (fst ab) b" using sK b unfolding K by auto
  2936   have "rel_multiset R M1 N" using sK K1N K1M1
  2937   unfolding K rel_multiset_def Grp_def by auto
  2938   thus ?thesis using M Rab by auto
  2939 qed
  2940 
  2941 lemma rel_multiset_imp_rel_multiset':
  2942 assumes "rel_multiset R M N"
  2943 shows "rel_multiset' R M N"
  2944 using assms proof(induct M arbitrary: N rule: measure_induct_rule[of mcard])
  2945   case (less M)
  2946   have c: "mcard M = mcard N" using rel_multiset_mcard[OF less.prems] .
  2947   show ?case
  2948   proof(cases "M = {#}")
  2949     case True hence "N = {#}" using c by simp
  2950     thus ?thesis using True rel_multiset'.Zero by auto
  2951   next
  2952     case False then obtain M1 a where M: "M = M1 + {#a#}" by (metis multi_nonempty_split)
  2953     obtain N1 b where N: "N = N1 + {#b#}" and R: "R a b" and ms: "rel_multiset R M1 N1"
  2954     using msed_rel_invL[OF less.prems[unfolded M]] by auto
  2955     have "rel_multiset' R M1 N1" using less.hyps[of M1 N1] ms unfolding M by simp
  2956     thus ?thesis using rel_multiset'.Plus[of R a b, OF R] unfolding M N by simp
  2957   qed
  2958 qed
  2959 
  2960 lemma rel_multiset_rel_multiset':
  2961 "rel_multiset R M N = rel_multiset' R M N"
  2962 using  rel_multiset_imp_rel_multiset' rel_multiset'_imp_rel_multiset by auto
  2963 
  2964 (* The main end product for rel_multiset: inductive characterization *)
  2965 theorems rel_multiset_induct[case_names empty add, induct pred: rel_multiset] =
  2966          rel_multiset'.induct[unfolded rel_multiset_rel_multiset'[symmetric]]
  2967 
  2968 end