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