src/HOL/Library/Multiset.thy
author Thomas Sewell <thomas.sewell@nicta.com.au>
Wed Jun 11 14:24:23 2014 +1000 (2014-06-11)
changeset 57492 74bf65a1910a
parent 57418 6ab1c7cb0b8d
child 57512 cc97b347b301
permissions -rw-r--r--
Hypsubst preserves equality hypotheses

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