src/HOL/Library/Multiset.thy
author wenzelm
Thu Feb 11 23:00:22 2010 +0100 (2010-02-11)
changeset 35115 446c5063e4fd
parent 35028 108662d50512
child 35268 04673275441a
permissions -rw-r--r--
modernized translations;
formal markup of @{syntax_const} and @{const_syntax};
minor tuning;
     1 (*  Title:      HOL/Library/Multiset.thy
     2     Author:     Tobias Nipkow, Markus Wenzel, Lawrence C Paulson, Norbert Voelker
     3 *)
     4 
     5 header {* (Finite) multisets *}
     6 
     7 theory Multiset
     8 imports Main
     9 begin
    10 
    11 subsection {* The type of multisets *}
    12 
    13 typedef 'a multiset = "{f :: 'a => nat. finite {x. f x > 0}}"
    14   morphisms count Abs_multiset
    15 proof
    16   show "(\<lambda>x. 0::nat) \<in> ?multiset" by simp
    17 qed
    18 
    19 lemmas multiset_typedef = Abs_multiset_inverse count_inverse count
    20 
    21 abbreviation Melem :: "'a => 'a multiset => bool"  ("(_/ :# _)" [50, 51] 50) where
    22   "a :# M == 0 < count M a"
    23 
    24 notation (xsymbols)
    25   Melem (infix "\<in>#" 50)
    26 
    27 lemma multiset_eq_conv_count_eq:
    28   "M = N \<longleftrightarrow> (\<forall>a. count M a = count N a)"
    29   by (simp only: count_inject [symmetric] expand_fun_eq)
    30 
    31 lemma multi_count_ext:
    32   "(\<And>x. count A x = count B x) \<Longrightarrow> A = B"
    33   using multiset_eq_conv_count_eq by auto
    34 
    35 text {*
    36  \medskip Preservation of the representing set @{term multiset}.
    37 *}
    38 
    39 lemma const0_in_multiset:
    40   "(\<lambda>a. 0) \<in> multiset"
    41   by (simp add: multiset_def)
    42 
    43 lemma only1_in_multiset:
    44   "(\<lambda>b. if b = a then n else 0) \<in> multiset"
    45   by (simp add: multiset_def)
    46 
    47 lemma union_preserves_multiset:
    48   "M \<in> multiset \<Longrightarrow> N \<in> multiset \<Longrightarrow> (\<lambda>a. M a + N a) \<in> multiset"
    49   by (simp add: multiset_def)
    50 
    51 lemma diff_preserves_multiset:
    52   assumes "M \<in> multiset"
    53   shows "(\<lambda>a. M a - N a) \<in> multiset"
    54 proof -
    55   have "{x. N x < M x} \<subseteq> {x. 0 < M x}"
    56     by auto
    57   with assms show ?thesis
    58     by (auto simp add: multiset_def intro: finite_subset)
    59 qed
    60 
    61 lemma MCollect_preserves_multiset:
    62   assumes "M \<in> multiset"
    63   shows "(\<lambda>x. if P x then M x else 0) \<in> multiset"
    64 proof -
    65   have "{x. (P x \<longrightarrow> 0 < M x) \<and> P x} \<subseteq> {x. 0 < M x}"
    66     by auto
    67   with assms show ?thesis
    68     by (auto simp add: multiset_def intro: finite_subset)
    69 qed
    70 
    71 lemmas in_multiset = const0_in_multiset only1_in_multiset
    72   union_preserves_multiset diff_preserves_multiset MCollect_preserves_multiset
    73 
    74 
    75 subsection {* Representing multisets *}
    76 
    77 text {* Multiset comprehension *}
    78 
    79 definition MCollect :: "'a multiset => ('a => bool) => 'a multiset" where
    80   "MCollect M P = Abs_multiset (\<lambda>x. if P x then count M x else 0)"
    81 
    82 syntax
    83   "_MCollect" :: "pttrn => 'a multiset => bool => 'a multiset"    ("(1{# _ :# _./ _#})")
    84 translations
    85   "{#x :# M. P#}" == "CONST MCollect M (\<lambda>x. P)"
    86 
    87 
    88 text {* Multiset enumeration *}
    89 
    90 instantiation multiset :: (type) "{zero, plus}"
    91 begin
    92 
    93 definition Mempty_def:
    94   "0 = Abs_multiset (\<lambda>a. 0)"
    95 
    96 abbreviation Mempty :: "'a multiset" ("{#}") where
    97   "Mempty \<equiv> 0"
    98 
    99 definition union_def:
   100   "M + N = Abs_multiset (\<lambda>a. count M a + count N a)"
   101 
   102 instance ..
   103 
   104 end
   105 
   106 definition single :: "'a => 'a multiset" where
   107   "single a = Abs_multiset (\<lambda>b. if b = a then 1 else 0)"
   108 
   109 syntax
   110   "_multiset" :: "args => 'a multiset"    ("{#(_)#}")
   111 translations
   112   "{#x, xs#}" == "{#x#} + {#xs#}"
   113   "{#x#}" == "CONST single x"
   114 
   115 lemma count_empty [simp]: "count {#} a = 0"
   116   by (simp add: Mempty_def in_multiset multiset_typedef)
   117 
   118 lemma count_single [simp]: "count {#b#} a = (if b = a then 1 else 0)"
   119   by (simp add: single_def in_multiset multiset_typedef)
   120 
   121 
   122 subsection {* Basic operations *}
   123 
   124 subsubsection {* Union *}
   125 
   126 lemma count_union [simp]: "count (M + N) a = count M a + count N a"
   127   by (simp add: union_def in_multiset multiset_typedef)
   128 
   129 instance multiset :: (type) cancel_comm_monoid_add proof
   130 qed (simp_all add: multiset_eq_conv_count_eq)
   131 
   132 
   133 subsubsection {* Difference *}
   134 
   135 instantiation multiset :: (type) minus
   136 begin
   137 
   138 definition diff_def:
   139   "M - N = Abs_multiset (\<lambda>a. count M a - count N a)"
   140 
   141 instance ..
   142 
   143 end
   144 
   145 lemma count_diff [simp]: "count (M - N) a = count M a - count N a"
   146   by (simp add: diff_def in_multiset multiset_typedef)
   147 
   148 lemma diff_empty [simp]: "M - {#} = M \<and> {#} - M = {#}"
   149   by (simp add: Mempty_def diff_def in_multiset multiset_typedef)
   150 
   151 lemma diff_union_inverse2 [simp]: "M + {#a#} - {#a#} = M"
   152   by (rule multi_count_ext)
   153     (auto simp del: count_single simp add: union_def diff_def in_multiset multiset_typedef)
   154 
   155 lemma diff_cancel: "A - A = {#}"
   156   by (rule multi_count_ext) simp
   157 
   158 lemma insert_DiffM:
   159   "x \<in># M \<Longrightarrow> {#x#} + (M - {#x#}) = M"
   160   by (clarsimp simp: multiset_eq_conv_count_eq)
   161 
   162 lemma insert_DiffM2 [simp]:
   163   "x \<in># M \<Longrightarrow> M - {#x#} + {#x#} = M"
   164   by (clarsimp simp: multiset_eq_conv_count_eq)
   165 
   166 lemma diff_right_commute:
   167   "(M::'a multiset) - N - Q = M - Q - N"
   168   by (auto simp add: multiset_eq_conv_count_eq)
   169 
   170 lemma diff_union_swap:
   171   "a \<noteq> b \<Longrightarrow> M - {#a#} + {#b#} = M + {#b#} - {#a#}"
   172   by (auto simp add: multiset_eq_conv_count_eq)
   173 
   174 lemma diff_union_single_conv:
   175   "a \<in># J \<Longrightarrow> I + J - {#a#} = I + (J - {#a#})"
   176   by (simp add: multiset_eq_conv_count_eq)
   177 
   178 
   179 subsubsection {* Intersection *}
   180 
   181 definition multiset_inter :: "'a multiset \<Rightarrow> 'a multiset \<Rightarrow> 'a multiset" (infixl "#\<inter>" 70) where
   182   "multiset_inter A B = A - (A - B)"
   183 
   184 lemma multiset_inter_count:
   185   "count (A #\<inter> B) x = min (count A x) (count B x)"
   186   by (simp add: multiset_inter_def multiset_typedef)
   187 
   188 lemma multiset_inter_commute: "A #\<inter> B = B #\<inter> A"
   189   by (rule multi_count_ext) (simp add: multiset_inter_count)
   190 
   191 lemma multiset_inter_assoc: "A #\<inter> (B #\<inter> C) = A #\<inter> B #\<inter> C"
   192   by (rule multi_count_ext) (simp add: multiset_inter_count)
   193 
   194 lemma multiset_inter_left_commute: "A #\<inter> (B #\<inter> C) = B #\<inter> (A #\<inter> C)"
   195   by (rule multi_count_ext) (simp add: multiset_inter_count)
   196 
   197 lemmas multiset_inter_ac =
   198   multiset_inter_commute
   199   multiset_inter_assoc
   200   multiset_inter_left_commute
   201 
   202 lemma multiset_inter_single: "a \<noteq> b \<Longrightarrow> {#a#} #\<inter> {#b#} = {#}"
   203   by (rule multi_count_ext) (auto simp add: multiset_inter_count)
   204 
   205 lemma multiset_union_diff_commute:
   206   assumes "B #\<inter> C = {#}"
   207   shows "A + B - C = A - C + B"
   208 proof (rule multi_count_ext)
   209   fix x
   210   from assms have "min (count B x) (count C x) = 0"
   211     by (auto simp add: multiset_inter_count multiset_eq_conv_count_eq)
   212   then have "count B x = 0 \<or> count C x = 0"
   213     by auto
   214   then show "count (A + B - C) x = count (A - C + B) x"
   215     by auto
   216 qed
   217 
   218 
   219 subsubsection {* Comprehension (filter) *}
   220 
   221 lemma count_MCollect [simp]:
   222   "count {# x:#M. P x #} a = (if P a then count M a else 0)"
   223   by (simp add: MCollect_def in_multiset multiset_typedef)
   224 
   225 lemma MCollect_empty [simp]: "MCollect {#} P = {#}"
   226   by (rule multi_count_ext) simp
   227 
   228 lemma MCollect_single [simp]:
   229   "MCollect {#x#} P = (if P x then {#x#} else {#})"
   230   by (rule multi_count_ext) simp
   231 
   232 lemma MCollect_union [simp]:
   233   "MCollect (M + N) f = MCollect M f + MCollect N f"
   234   by (rule multi_count_ext) simp
   235 
   236 
   237 subsubsection {* Equality of multisets *}
   238 
   239 lemma single_not_empty [simp]: "{#a#} \<noteq> {#} \<and> {#} \<noteq> {#a#}"
   240   by (simp add: multiset_eq_conv_count_eq)
   241 
   242 lemma single_eq_single [simp]: "{#a#} = {#b#} \<longleftrightarrow> a = b"
   243   by (auto simp add: multiset_eq_conv_count_eq)
   244 
   245 lemma union_eq_empty [iff]: "M + N = {#} \<longleftrightarrow> M = {#} \<and> N = {#}"
   246   by (auto simp add: multiset_eq_conv_count_eq)
   247 
   248 lemma empty_eq_union [iff]: "{#} = M + N \<longleftrightarrow> M = {#} \<and> N = {#}"
   249   by (auto simp add: multiset_eq_conv_count_eq)
   250 
   251 lemma multi_self_add_other_not_self [simp]: "M = M + {#x#} \<longleftrightarrow> False"
   252   by (auto simp add: multiset_eq_conv_count_eq)
   253 
   254 lemma diff_single_trivial:
   255   "\<not> x \<in># M \<Longrightarrow> M - {#x#} = M"
   256   by (auto simp add: multiset_eq_conv_count_eq)
   257 
   258 lemma diff_single_eq_union:
   259   "x \<in># M \<Longrightarrow> M - {#x#} = N \<longleftrightarrow> M = N + {#x#}"
   260   by auto
   261 
   262 lemma union_single_eq_diff:
   263   "M + {#x#} = N \<Longrightarrow> M = N - {#x#}"
   264   by (auto dest: sym)
   265 
   266 lemma union_single_eq_member:
   267   "M + {#x#} = N \<Longrightarrow> x \<in># N"
   268   by auto
   269 
   270 lemma union_is_single:
   271   "M + N = {#a#} \<longleftrightarrow> M = {#a#} \<and> N={#} \<or> M = {#} \<and> N = {#a#}" (is "?lhs = ?rhs")
   272 proof
   273   assume ?rhs then show ?lhs by auto
   274 next
   275   assume ?lhs
   276   then have "\<And>b. count (M + N) b = (if b = a then 1 else 0)" by auto
   277   then have *: "\<And>b. count M b + count N b = (if b = a then 1 else 0)" by auto
   278   then have "count M a + count N a = 1" by auto
   279   then have **: "count M a = 1 \<and> count N a = 0 \<or> count M a = 0 \<and> count N a = 1"
   280     by auto
   281   from * have "\<And>b. b \<noteq> a \<Longrightarrow> count M b + count N b = 0" by auto
   282   then have ***: "\<And>b. b \<noteq> a \<Longrightarrow> count M b = 0 \<and> count N b = 0" by auto
   283   from ** and *** have
   284     "(\<forall>b. count M b = (if b = a then 1 else 0) \<and> count N b = 0) \<or>
   285       (\<forall>b. count M b = 0 \<and> count N b = (if b = a then 1 else 0))"
   286     by auto
   287   then have
   288     "(\<forall>b. count M b = (if b = a then 1 else 0)) \<and> (\<forall>b. count N b = 0) \<or>
   289       (\<forall>b. count M b = 0) \<and> (\<forall>b. count N b = (if b = a then 1 else 0))"
   290     by auto
   291   then show ?rhs by (auto simp add: multiset_eq_conv_count_eq)
   292 qed
   293 
   294 lemma single_is_union:
   295   "{#a#} = M + N \<longleftrightarrow> {#a#} = M \<and> N = {#} \<or> M = {#} \<and> {#a#} = N"
   296   by (auto simp add: eq_commute [of "{#a#}" "M + N"] union_is_single)
   297 
   298 lemma add_eq_conv_diff:
   299   "M + {#a#} = N + {#b#} \<longleftrightarrow> M = N \<and> a = b \<or> M = N - {#a#} + {#b#} \<and> N = M - {#b#} + {#a#}"  (is "?lhs = ?rhs")
   300 proof
   301   assume ?rhs then show ?lhs
   302   by (auto simp add: add_assoc add_commute [of "{#b#}"])
   303     (drule sym, simp add: add_assoc [symmetric])
   304 next
   305   assume ?lhs
   306   show ?rhs
   307   proof (cases "a = b")
   308     case True with `?lhs` show ?thesis by simp
   309   next
   310     case False
   311     from `?lhs` have "a \<in># N + {#b#}" by (rule union_single_eq_member)
   312     with False have "a \<in># N" by auto
   313     moreover from `?lhs` have "M = N + {#b#} - {#a#}" by (rule union_single_eq_diff)
   314     moreover note False
   315     ultimately show ?thesis by (auto simp add: diff_right_commute [of _ "{#a#}"] diff_union_swap)
   316   qed
   317 qed
   318 
   319 lemma insert_noteq_member: 
   320   assumes BC: "B + {#b#} = C + {#c#}"
   321    and bnotc: "b \<noteq> c"
   322   shows "c \<in># B"
   323 proof -
   324   have "c \<in># C + {#c#}" by simp
   325   have nc: "\<not> c \<in># {#b#}" using bnotc by simp
   326   then have "c \<in># B + {#b#}" using BC by simp
   327   then show "c \<in># B" using nc by simp
   328 qed
   329 
   330 lemma add_eq_conv_ex:
   331   "(M + {#a#} = N + {#b#}) =
   332     (M = N \<and> a = b \<or> (\<exists>K. M = K + {#b#} \<and> N = K + {#a#}))"
   333   by (auto simp add: add_eq_conv_diff)
   334 
   335 
   336 subsubsection {* Pointwise ordering induced by count *}
   337 
   338 definition mset_le :: "'a multiset \<Rightarrow> 'a multiset \<Rightarrow> bool"  (infix "\<le>#" 50) where
   339   "A \<le># B \<longleftrightarrow> (\<forall>a. count A a \<le> count B a)"
   340 
   341 definition mset_less :: "'a multiset \<Rightarrow> 'a multiset \<Rightarrow> bool"  (infix "<#" 50) where
   342   "A <# B \<longleftrightarrow> A \<le># B \<and> A \<noteq> B"
   343 
   344 notation mset_le  (infix "\<subseteq>#" 50)
   345 notation mset_less  (infix "\<subset>#" 50)
   346 
   347 lemma mset_less_eqI:
   348   "(\<And>x. count A x \<le> count B x) \<Longrightarrow> A \<subseteq># B"
   349   by (simp add: mset_le_def)
   350 
   351 lemma mset_le_refl[simp]: "A \<le># A"
   352 unfolding mset_le_def by auto
   353 
   354 lemma mset_le_trans: "A \<le># B \<Longrightarrow> B \<le># C \<Longrightarrow> A \<le># C"
   355 unfolding mset_le_def by (fast intro: order_trans)
   356 
   357 lemma mset_le_antisym: "A \<le># B \<Longrightarrow> B \<le># A \<Longrightarrow> A = B"
   358 apply (unfold mset_le_def)
   359 apply (rule multiset_eq_conv_count_eq [THEN iffD2])
   360 apply (blast intro: order_antisym)
   361 done
   362 
   363 lemma mset_le_exists_conv: "(A \<le># B) = (\<exists>C. B = A + C)"
   364 apply (unfold mset_le_def, rule iffI, rule_tac x = "B - A" in exI)
   365 apply (auto intro: multiset_eq_conv_count_eq [THEN iffD2])
   366 done
   367 
   368 lemma mset_le_mono_add_right_cancel[simp]: "(A + C \<le># B + C) = (A \<le># B)"
   369 unfolding mset_le_def by auto
   370 
   371 lemma mset_le_mono_add_left_cancel[simp]: "(C + A \<le># C + B) = (A \<le># B)"
   372 unfolding mset_le_def by auto
   373 
   374 lemma mset_le_mono_add: "\<lbrakk> A \<le># B; C \<le># D \<rbrakk> \<Longrightarrow> A + C \<le># B + D"
   375 apply (unfold mset_le_def)
   376 apply auto
   377 apply (erule_tac x = a in allE)+
   378 apply auto
   379 done
   380 
   381 lemma mset_le_add_left[simp]: "A \<le># A + B"
   382 unfolding mset_le_def by auto
   383 
   384 lemma mset_le_add_right[simp]: "B \<le># A + B"
   385 unfolding mset_le_def by auto
   386 
   387 lemma mset_le_single: "a :# B \<Longrightarrow> {#a#} \<le># B"
   388 by (simp add: mset_le_def)
   389 
   390 lemma multiset_diff_union_assoc: "C \<le># B \<Longrightarrow> A + B - C = A + (B - C)"
   391 by (simp add: multiset_eq_conv_count_eq mset_le_def)
   392 
   393 lemma mset_le_multiset_union_diff_commute:
   394 assumes "B \<le># A"
   395 shows "A - B + C = A + C - B"
   396 proof -
   397   from mset_le_exists_conv [of "B" "A"] assms have "\<exists>D. A = B + D" ..
   398   from this obtain D where "A = B + D" ..
   399   then show ?thesis
   400     apply simp
   401     apply (subst add_commute)
   402     apply (subst multiset_diff_union_assoc)
   403     apply simp
   404     apply (simp add: diff_cancel)
   405     apply (subst add_assoc)
   406     apply (subst add_commute [of "B" _])
   407     apply (subst multiset_diff_union_assoc)
   408     apply simp
   409     apply (simp add: diff_cancel)
   410     done
   411 qed
   412 
   413 interpretation mset_order: order "op \<le>#" "op <#"
   414 proof qed (auto intro: order.intro mset_le_refl mset_le_antisym
   415   mset_le_trans simp: mset_less_def)
   416 
   417 interpretation mset_order_cancel_semigroup:
   418   ordered_cancel_ab_semigroup_add "op +" "op \<le>#" "op <#"
   419 proof qed (erule mset_le_mono_add [OF mset_le_refl])
   420 
   421 interpretation mset_order_semigroup_cancel:
   422   ordered_ab_semigroup_add_imp_le "op +" "op \<le>#" "op <#"
   423 proof qed simp
   424 
   425 lemma mset_lessD: "A \<subset># B \<Longrightarrow> x \<in># A \<Longrightarrow> x \<in># B"
   426 apply (clarsimp simp: mset_le_def mset_less_def)
   427 apply (erule_tac x=x in allE)
   428 apply auto
   429 done
   430 
   431 lemma mset_leD: "A \<subseteq># B \<Longrightarrow> x \<in># A \<Longrightarrow> x \<in># B"
   432 apply (clarsimp simp: mset_le_def mset_less_def)
   433 apply (erule_tac x = x in allE)
   434 apply auto
   435 done
   436   
   437 lemma mset_less_insertD: "(A + {#x#} \<subset># B) \<Longrightarrow> (x \<in># B \<and> A \<subset># B)"
   438 apply (rule conjI)
   439  apply (simp add: mset_lessD)
   440 apply (clarsimp simp: mset_le_def mset_less_def)
   441 apply safe
   442  apply (erule_tac x = a in allE)
   443  apply (auto split: split_if_asm)
   444 done
   445 
   446 lemma mset_le_insertD: "(A + {#x#} \<subseteq># B) \<Longrightarrow> (x \<in># B \<and> A \<subseteq># B)"
   447 apply (rule conjI)
   448  apply (simp add: mset_leD)
   449 apply (force simp: mset_le_def mset_less_def split: split_if_asm)
   450 done
   451 
   452 lemma mset_less_of_empty[simp]: "A \<subset># {#} \<longleftrightarrow> False"
   453   by (auto simp add: mset_less_def mset_le_def multiset_eq_conv_count_eq)
   454 
   455 lemma multi_psub_of_add_self[simp]: "A \<subset># A + {#x#}"
   456 by (auto simp: mset_le_def mset_less_def)
   457 
   458 lemma multi_psub_self[simp]: "A \<subset># A = False"
   459 by (auto simp: mset_le_def mset_less_def)
   460 
   461 lemma mset_less_add_bothsides:
   462   "T + {#x#} \<subset># S + {#x#} \<Longrightarrow> T \<subset># S"
   463 by (auto simp: mset_le_def mset_less_def)
   464 
   465 lemma mset_less_empty_nonempty: "({#} \<subset># S) = (S \<noteq> {#})"
   466 by (auto simp: mset_le_def mset_less_def)
   467 
   468 lemma mset_less_diff_self: "c \<in># B \<Longrightarrow> B - {#c#} \<subset># B"
   469   by (auto simp: mset_le_def mset_less_def multiset_eq_conv_count_eq)
   470 
   471 
   472 subsubsection {* Set of elements *}
   473 
   474 definition set_of :: "'a multiset => 'a set" where
   475   "set_of M = {x. x :# M}"
   476 
   477 lemma set_of_empty [simp]: "set_of {#} = {}"
   478 by (simp add: set_of_def)
   479 
   480 lemma set_of_single [simp]: "set_of {#b#} = {b}"
   481 by (simp add: set_of_def)
   482 
   483 lemma set_of_union [simp]: "set_of (M + N) = set_of M \<union> set_of N"
   484 by (auto simp add: set_of_def)
   485 
   486 lemma set_of_eq_empty_iff [simp]: "(set_of M = {}) = (M = {#})"
   487 by (auto simp add: set_of_def multiset_eq_conv_count_eq)
   488 
   489 lemma mem_set_of_iff [simp]: "(x \<in> set_of M) = (x :# M)"
   490 by (auto simp add: set_of_def)
   491 
   492 lemma set_of_MCollect [simp]: "set_of {# x:#M. P x #} = set_of M \<inter> {x. P x}"
   493 by (auto simp add: set_of_def)
   494 
   495 lemma finite_set_of [iff]: "finite (set_of M)"
   496   using count [of M] by (simp add: multiset_def set_of_def)
   497 
   498 
   499 subsubsection {* Size *}
   500 
   501 instantiation multiset :: (type) size
   502 begin
   503 
   504 definition size_def:
   505   "size M = setsum (count M) (set_of M)"
   506 
   507 instance ..
   508 
   509 end
   510 
   511 lemma size_empty [simp]: "size {#} = 0"
   512 by (simp add: size_def)
   513 
   514 lemma size_single [simp]: "size {#b#} = 1"
   515 by (simp add: size_def)
   516 
   517 lemma setsum_count_Int:
   518   "finite A ==> setsum (count N) (A \<inter> set_of N) = setsum (count N) A"
   519 apply (induct rule: finite_induct)
   520  apply simp
   521 apply (simp add: Int_insert_left set_of_def)
   522 done
   523 
   524 lemma size_union [simp]: "size (M + N::'a multiset) = size M + size N"
   525 apply (unfold size_def)
   526 apply (subgoal_tac "count (M + N) = (\<lambda>a. count M a + count N a)")
   527  prefer 2
   528  apply (rule ext, simp)
   529 apply (simp (no_asm_simp) add: setsum_Un_nat setsum_addf setsum_count_Int)
   530 apply (subst Int_commute)
   531 apply (simp (no_asm_simp) add: setsum_count_Int)
   532 done
   533 
   534 lemma size_eq_0_iff_empty [iff]: "(size M = 0) = (M = {#})"
   535 by (auto simp add: size_def multiset_eq_conv_count_eq)
   536 
   537 lemma nonempty_has_size: "(S \<noteq> {#}) = (0 < size S)"
   538 by (metis gr0I gr_implies_not0 size_empty size_eq_0_iff_empty)
   539 
   540 lemma size_eq_Suc_imp_elem: "size M = Suc n ==> \<exists>a. a :# M"
   541 apply (unfold size_def)
   542 apply (drule setsum_SucD)
   543 apply auto
   544 done
   545 
   546 lemma size_eq_Suc_imp_eq_union:
   547   assumes "size M = Suc n"
   548   shows "\<exists>a N. M = N + {#a#}"
   549 proof -
   550   from assms obtain a where "a \<in># M"
   551     by (erule size_eq_Suc_imp_elem [THEN exE])
   552   then have "M = M - {#a#} + {#a#}" by simp
   553   then show ?thesis by blast
   554 qed
   555 
   556 
   557 subsection {* Induction and case splits *}
   558 
   559 lemma setsum_decr:
   560   "finite F ==> (0::nat) < f a ==>
   561     setsum (f (a := f a - 1)) F = (if a\<in>F then setsum f F - 1 else setsum f F)"
   562 apply (induct rule: finite_induct)
   563  apply auto
   564 apply (drule_tac a = a in mk_disjoint_insert, auto)
   565 done
   566 
   567 lemma rep_multiset_induct_aux:
   568 assumes 1: "P (\<lambda>a. (0::nat))"
   569   and 2: "!!f b. f \<in> multiset ==> P f ==> P (f (b := f b + 1))"
   570 shows "\<forall>f. f \<in> multiset --> setsum f {x. f x \<noteq> 0} = n --> P f"
   571 apply (unfold multiset_def)
   572 apply (induct_tac n, simp, clarify)
   573  apply (subgoal_tac "f = (\<lambda>a.0)")
   574   apply simp
   575   apply (rule 1)
   576  apply (rule ext, force, clarify)
   577 apply (frule setsum_SucD, clarify)
   578 apply (rename_tac a)
   579 apply (subgoal_tac "finite {x. (f (a := f a - 1)) x > 0}")
   580  prefer 2
   581  apply (rule finite_subset)
   582   prefer 2
   583   apply assumption
   584  apply simp
   585  apply blast
   586 apply (subgoal_tac "f = (f (a := f a - 1))(a := (f (a := f a - 1)) a + 1)")
   587  prefer 2
   588  apply (rule ext)
   589  apply (simp (no_asm_simp))
   590  apply (erule ssubst, rule 2 [unfolded multiset_def], blast)
   591 apply (erule allE, erule impE, erule_tac [2] mp, blast)
   592 apply (simp (no_asm_simp) add: setsum_decr del: fun_upd_apply One_nat_def)
   593 apply (subgoal_tac "{x. x \<noteq> a --> f x \<noteq> 0} = {x. f x \<noteq> 0}")
   594  prefer 2
   595  apply blast
   596 apply (subgoal_tac "{x. x \<noteq> a \<and> f x \<noteq> 0} = {x. f x \<noteq> 0} - {a}")
   597  prefer 2
   598  apply blast
   599 apply (simp add: le_imp_diff_is_add setsum_diff1_nat cong: conj_cong)
   600 done
   601 
   602 theorem rep_multiset_induct:
   603   "f \<in> multiset ==> P (\<lambda>a. 0) ==>
   604     (!!f b. f \<in> multiset ==> P f ==> P (f (b := f b + 1))) ==> P f"
   605 using rep_multiset_induct_aux by blast
   606 
   607 theorem multiset_induct [case_names empty add, induct type: multiset]:
   608 assumes empty: "P {#}"
   609   and add: "!!M x. P M ==> P (M + {#x#})"
   610 shows "P M"
   611 proof -
   612   note defns = union_def single_def Mempty_def
   613   note add' = add [unfolded defns, simplified]
   614   have aux: "\<And>a::'a. count (Abs_multiset (\<lambda>b. if b = a then 1 else 0)) =
   615     (\<lambda>b. if b = a then 1 else 0)" by (simp add: Abs_multiset_inverse in_multiset) 
   616   show ?thesis
   617     apply (rule count_inverse [THEN subst])
   618     apply (rule count [THEN rep_multiset_induct])
   619      apply (rule empty [unfolded defns])
   620     apply (subgoal_tac "f(b := f b + 1) = (\<lambda>a. f a + (if a=b then 1 else 0))")
   621      prefer 2
   622      apply (simp add: expand_fun_eq)
   623     apply (erule ssubst)
   624     apply (erule Abs_multiset_inverse [THEN subst])
   625     apply (drule add')
   626     apply (simp add: aux)
   627     done
   628 qed
   629 
   630 lemma multi_nonempty_split: "M \<noteq> {#} \<Longrightarrow> \<exists>A a. M = A + {#a#}"
   631 by (induct M) auto
   632 
   633 lemma multiset_cases [cases type, case_names empty add]:
   634 assumes em:  "M = {#} \<Longrightarrow> P"
   635 assumes add: "\<And>N x. M = N + {#x#} \<Longrightarrow> P"
   636 shows "P"
   637 proof (cases "M = {#}")
   638   assume "M = {#}" then show ?thesis using em by simp
   639 next
   640   assume "M \<noteq> {#}"
   641   then obtain M' m where "M = M' + {#m#}" 
   642     by (blast dest: multi_nonempty_split)
   643   then show ?thesis using add by simp
   644 qed
   645 
   646 lemma multi_member_split: "x \<in># M \<Longrightarrow> \<exists>A. M = A + {#x#}"
   647 apply (cases M)
   648  apply simp
   649 apply (rule_tac x="M - {#x#}" in exI, simp)
   650 done
   651 
   652 lemma multi_drop_mem_not_eq: "c \<in># B \<Longrightarrow> B - {#c#} \<noteq> B"
   653 by (cases "B = {#}") (auto dest: multi_member_split)
   654 
   655 lemma multiset_partition: "M = {# x:#M. P x #} + {# x:#M. \<not> P x #}"
   656 apply (subst multiset_eq_conv_count_eq)
   657 apply auto
   658 done
   659 
   660 lemma mset_less_size: "A \<subset># B \<Longrightarrow> size A < size B"
   661 proof (induct A arbitrary: B)
   662   case (empty M)
   663   then have "M \<noteq> {#}" by (simp add: mset_less_empty_nonempty)
   664   then obtain M' x where "M = M' + {#x#}" 
   665     by (blast dest: multi_nonempty_split)
   666   then show ?case by simp
   667 next
   668   case (add S x T)
   669   have IH: "\<And>B. S \<subset># B \<Longrightarrow> size S < size B" by fact
   670   have SxsubT: "S + {#x#} \<subset># T" by fact
   671   then have "x \<in># T" and "S \<subset># T" by (auto dest: mset_less_insertD)
   672   then obtain T' where T: "T = T' + {#x#}" 
   673     by (blast dest: multi_member_split)
   674   then have "S \<subset># T'" using SxsubT 
   675     by (blast intro: mset_less_add_bothsides)
   676   then have "size S < size T'" using IH by simp
   677   then show ?case using T by simp
   678 qed
   679 
   680 
   681 subsubsection {* Strong induction and subset induction for multisets *}
   682 
   683 text {* Well-foundedness of proper subset operator: *}
   684 
   685 text {* proper multiset subset *}
   686 
   687 definition
   688   mset_less_rel :: "('a multiset * 'a multiset) set" where
   689   "mset_less_rel = {(A,B). A \<subset># B}"
   690 
   691 lemma multiset_add_sub_el_shuffle: 
   692   assumes "c \<in># B" and "b \<noteq> c" 
   693   shows "B - {#c#} + {#b#} = B + {#b#} - {#c#}"
   694 proof -
   695   from `c \<in># B` obtain A where B: "B = A + {#c#}" 
   696     by (blast dest: multi_member_split)
   697   have "A + {#b#} = A + {#b#} + {#c#} - {#c#}" by simp
   698   then have "A + {#b#} = A + {#c#} + {#b#} - {#c#}" 
   699     by (simp add: add_ac)
   700   then show ?thesis using B by simp
   701 qed
   702 
   703 lemma wf_mset_less_rel: "wf mset_less_rel"
   704 apply (unfold mset_less_rel_def)
   705 apply (rule wf_measure [THEN wf_subset, where f1=size])
   706 apply (clarsimp simp: measure_def inv_image_def mset_less_size)
   707 done
   708 
   709 text {* The induction rules: *}
   710 
   711 lemma full_multiset_induct [case_names less]:
   712 assumes ih: "\<And>B. \<forall>A. A \<subset># B \<longrightarrow> P A \<Longrightarrow> P B"
   713 shows "P B"
   714 apply (rule wf_mset_less_rel [THEN wf_induct])
   715 apply (rule ih, auto simp: mset_less_rel_def)
   716 done
   717 
   718 lemma multi_subset_induct [consumes 2, case_names empty add]:
   719 assumes "F \<subseteq># A"
   720   and empty: "P {#}"
   721   and insert: "\<And>a F. a \<in># A \<Longrightarrow> P F \<Longrightarrow> P (F + {#a#})"
   722 shows "P F"
   723 proof -
   724   from `F \<subseteq># A`
   725   show ?thesis
   726   proof (induct F)
   727     show "P {#}" by fact
   728   next
   729     fix x F
   730     assume P: "F \<subseteq># A \<Longrightarrow> P F" and i: "F + {#x#} \<subseteq># A"
   731     show "P (F + {#x#})"
   732     proof (rule insert)
   733       from i show "x \<in># A" by (auto dest: mset_le_insertD)
   734       from i have "F \<subseteq># A" by (auto dest: mset_le_insertD)
   735       with P show "P F" .
   736     qed
   737   qed
   738 qed
   739 
   740 
   741 subsection {* Alternative representations *}
   742 
   743 subsubsection {* Lists *}
   744 
   745 primrec multiset_of :: "'a list \<Rightarrow> 'a multiset" where
   746   "multiset_of [] = {#}" |
   747   "multiset_of (a # x) = multiset_of x + {# a #}"
   748 
   749 lemma multiset_of_zero_iff[simp]: "(multiset_of x = {#}) = (x = [])"
   750 by (induct x) auto
   751 
   752 lemma multiset_of_zero_iff_right[simp]: "({#} = multiset_of x) = (x = [])"
   753 by (induct x) auto
   754 
   755 lemma set_of_multiset_of[simp]: "set_of(multiset_of x) = set x"
   756 by (induct x) auto
   757 
   758 lemma mem_set_multiset_eq: "x \<in> set xs = (x :# multiset_of xs)"
   759 by (induct xs) auto
   760 
   761 lemma multiset_of_append [simp]:
   762   "multiset_of (xs @ ys) = multiset_of xs + multiset_of ys"
   763   by (induct xs arbitrary: ys) (auto simp: add_ac)
   764 
   765 lemma surj_multiset_of: "surj multiset_of"
   766 apply (unfold surj_def)
   767 apply (rule allI)
   768 apply (rule_tac M = y in multiset_induct)
   769  apply auto
   770 apply (rule_tac x = "x # xa" in exI)
   771 apply auto
   772 done
   773 
   774 lemma set_count_greater_0: "set x = {a. count (multiset_of x) a > 0}"
   775 by (induct x) auto
   776 
   777 lemma distinct_count_atmost_1:
   778   "distinct x = (! a. count (multiset_of x) a = (if a \<in> set x then 1 else 0))"
   779 apply (induct x, simp, rule iffI, simp_all)
   780 apply (rule conjI)
   781 apply (simp_all add: set_of_multiset_of [THEN sym] del: set_of_multiset_of)
   782 apply (erule_tac x = a in allE, simp, clarify)
   783 apply (erule_tac x = aa in allE, simp)
   784 done
   785 
   786 lemma multiset_of_eq_setD:
   787   "multiset_of xs = multiset_of ys \<Longrightarrow> set xs = set ys"
   788 by (rule) (auto simp add:multiset_eq_conv_count_eq set_count_greater_0)
   789 
   790 lemma set_eq_iff_multiset_of_eq_distinct:
   791   "distinct x \<Longrightarrow> distinct y \<Longrightarrow>
   792     (set x = set y) = (multiset_of x = multiset_of y)"
   793 by (auto simp: multiset_eq_conv_count_eq distinct_count_atmost_1)
   794 
   795 lemma set_eq_iff_multiset_of_remdups_eq:
   796    "(set x = set y) = (multiset_of (remdups x) = multiset_of (remdups y))"
   797 apply (rule iffI)
   798 apply (simp add: set_eq_iff_multiset_of_eq_distinct[THEN iffD1])
   799 apply (drule distinct_remdups [THEN distinct_remdups
   800       [THEN set_eq_iff_multiset_of_eq_distinct [THEN iffD2]]])
   801 apply simp
   802 done
   803 
   804 lemma multiset_of_compl_union [simp]:
   805   "multiset_of [x\<leftarrow>xs. P x] + multiset_of [x\<leftarrow>xs. \<not>P x] = multiset_of xs"
   806   by (induct xs) (auto simp: add_ac)
   807 
   808 lemma count_filter:
   809   "count (multiset_of xs) x = length [y \<leftarrow> xs. y = x]"
   810 by (induct xs) auto
   811 
   812 lemma nth_mem_multiset_of: "i < length ls \<Longrightarrow> (ls ! i) :# multiset_of ls"
   813 apply (induct ls arbitrary: i)
   814  apply simp
   815 apply (case_tac i)
   816  apply auto
   817 done
   818 
   819 lemma multiset_of_remove1: "multiset_of (remove1 a xs) = multiset_of xs - {#a#}"
   820 by (induct xs) (auto simp add: multiset_eq_conv_count_eq)
   821 
   822 lemma multiset_of_eq_length:
   823 assumes "multiset_of xs = multiset_of ys"
   824 shows "length xs = length ys"
   825 using assms
   826 proof (induct arbitrary: ys rule: length_induct)
   827   case (1 xs ys)
   828   show ?case
   829   proof (cases xs)
   830     case Nil with "1.prems" show ?thesis by simp
   831   next
   832     case (Cons x xs')
   833     note xCons = Cons
   834     show ?thesis
   835     proof (cases ys)
   836       case Nil
   837       with "1.prems" Cons show ?thesis by simp
   838     next
   839       case (Cons y ys')
   840       have x_in_ys: "x = y \<or> x \<in> set ys'"
   841       proof (cases "x = y")
   842         case True then show ?thesis ..
   843       next
   844         case False
   845         from "1.prems" [symmetric] xCons Cons have "x :# multiset_of ys' + {#y#}" by simp
   846         with False show ?thesis by (simp add: mem_set_multiset_eq)
   847       qed
   848       from "1.hyps" have IH: "length xs' < length xs \<longrightarrow>
   849         (\<forall>x. multiset_of xs' = multiset_of x \<longrightarrow> length xs' = length x)" by blast
   850       from "1.prems" x_in_ys Cons xCons have "multiset_of xs' = multiset_of (remove1 x (y#ys'))"
   851         apply -
   852         apply (simp add: multiset_of_remove1, simp only: add_eq_conv_diff)
   853         apply fastsimp
   854         done
   855       with IH xCons have IH': "length xs' = length (remove1 x (y#ys'))" by fastsimp
   856       from x_in_ys have "x \<noteq> y \<Longrightarrow> length ys' > 0" by auto
   857       with Cons xCons x_in_ys IH' show ?thesis by (auto simp add: length_remove1)
   858     qed
   859   qed
   860 qed
   861 
   862 text {*
   863   This lemma shows which properties suffice to show that a function
   864   @{text "f"} with @{text "f xs = ys"} behaves like sort.
   865 *}
   866 lemma properties_for_sort:
   867   "multiset_of ys = multiset_of xs \<Longrightarrow> sorted ys \<Longrightarrow> sort xs = ys"
   868 proof (induct xs arbitrary: ys)
   869   case Nil then show ?case by simp
   870 next
   871   case (Cons x xs)
   872   then have "x \<in> set ys"
   873     by (auto simp add:  mem_set_multiset_eq intro!: ccontr)
   874   with Cons.prems Cons.hyps [of "remove1 x ys"] show ?case
   875     by (simp add: sorted_remove1 multiset_of_remove1 insort_remove1)
   876 qed
   877 
   878 lemma multiset_of_remdups_le: "multiset_of (remdups xs) \<le># multiset_of xs"
   879 apply (induct xs)
   880  apply auto
   881 apply (rule mset_le_trans)
   882  apply auto
   883 done
   884 
   885 lemma multiset_of_update:
   886   "i < length ls \<Longrightarrow> multiset_of (ls[i := v]) = multiset_of ls - {#ls ! i#} + {#v#}"
   887 proof (induct ls arbitrary: i)
   888   case Nil then show ?case by simp
   889 next
   890   case (Cons x xs)
   891   show ?case
   892   proof (cases i)
   893     case 0 then show ?thesis by simp
   894   next
   895     case (Suc i')
   896     with Cons show ?thesis
   897       apply simp
   898       apply (subst add_assoc)
   899       apply (subst add_commute [of "{#v#}" "{#x#}"])
   900       apply (subst add_assoc [symmetric])
   901       apply simp
   902       apply (rule mset_le_multiset_union_diff_commute)
   903       apply (simp add: mset_le_single nth_mem_multiset_of)
   904       done
   905   qed
   906 qed
   907 
   908 lemma multiset_of_swap:
   909   "i < length ls \<Longrightarrow> j < length ls \<Longrightarrow>
   910     multiset_of (ls[j := ls ! i, i := ls ! j]) = multiset_of ls"
   911   by (cases "i = j") (simp_all add: multiset_of_update nth_mem_multiset_of)
   912 
   913 
   914 subsubsection {* Association lists -- including rudimentary code generation *}
   915 
   916 definition count_of :: "('a \<times> nat) list \<Rightarrow> 'a \<Rightarrow> nat" where
   917   "count_of xs x = (case map_of xs x of None \<Rightarrow> 0 | Some n \<Rightarrow> n)"
   918 
   919 lemma count_of_multiset:
   920   "count_of xs \<in> multiset"
   921 proof -
   922   let ?A = "{x::'a. 0 < (case map_of xs x of None \<Rightarrow> 0\<Colon>nat | Some (n\<Colon>nat) \<Rightarrow> n)}"
   923   have "?A \<subseteq> dom (map_of xs)"
   924   proof
   925     fix x
   926     assume "x \<in> ?A"
   927     then have "0 < (case map_of xs x of None \<Rightarrow> 0\<Colon>nat | Some (n\<Colon>nat) \<Rightarrow> n)" by simp
   928     then have "map_of xs x \<noteq> None" by (cases "map_of xs x") auto
   929     then show "x \<in> dom (map_of xs)" by auto
   930   qed
   931   with finite_dom_map_of [of xs] have "finite ?A"
   932     by (auto intro: finite_subset)
   933   then show ?thesis
   934     by (simp add: count_of_def expand_fun_eq multiset_def)
   935 qed
   936 
   937 lemma count_simps [simp]:
   938   "count_of [] = (\<lambda>_. 0)"
   939   "count_of ((x, n) # xs) = (\<lambda>y. if x = y then n else count_of xs y)"
   940   by (simp_all add: count_of_def expand_fun_eq)
   941 
   942 lemma count_of_empty:
   943   "x \<notin> fst ` set xs \<Longrightarrow> count_of xs x = 0"
   944   by (induct xs) (simp_all add: count_of_def)
   945 
   946 lemma count_of_filter:
   947   "count_of (filter (P \<circ> fst) xs) x = (if P x then count_of xs x else 0)"
   948   by (induct xs) auto
   949 
   950 definition Bag :: "('a \<times> nat) list \<Rightarrow> 'a multiset" where
   951   "Bag xs = Abs_multiset (count_of xs)"
   952 
   953 code_datatype Bag
   954 
   955 lemma count_Bag [simp, code]:
   956   "count (Bag xs) = count_of xs"
   957   by (simp add: Bag_def count_of_multiset Abs_multiset_inverse)
   958 
   959 lemma Mempty_Bag [code]:
   960   "{#} = Bag []"
   961   by (simp add: multiset_eq_conv_count_eq)
   962   
   963 lemma single_Bag [code]:
   964   "{#x#} = Bag [(x, 1)]"
   965   by (simp add: multiset_eq_conv_count_eq)
   966 
   967 lemma MCollect_Bag [code]:
   968   "MCollect (Bag xs) P = Bag (filter (P \<circ> fst) xs)"
   969   by (simp add: multiset_eq_conv_count_eq count_of_filter)
   970 
   971 lemma mset_less_eq_Bag [code]:
   972   "Bag xs \<subseteq># A \<longleftrightarrow> (\<forall>(x, n) \<in> set xs. count_of xs x \<le> count A x)"
   973     (is "?lhs \<longleftrightarrow> ?rhs")
   974 proof
   975   assume ?lhs then show ?rhs
   976     by (auto simp add: mset_le_def count_Bag)
   977 next
   978   assume ?rhs
   979   show ?lhs
   980   proof (rule mset_less_eqI)
   981     fix x
   982     from `?rhs` have "count_of xs x \<le> count A x"
   983       by (cases "x \<in> fst ` set xs") (auto simp add: count_of_empty)
   984     then show "count (Bag xs) x \<le> count A x"
   985       by (simp add: mset_le_def count_Bag)
   986   qed
   987 qed
   988 
   989 instantiation multiset :: (eq) eq
   990 begin
   991 
   992 definition
   993   "HOL.eq A B \<longleftrightarrow> A \<subseteq># B \<and> B \<subseteq># A"
   994 
   995 instance proof
   996 qed (simp add: eq_multiset_def mset_order.eq_iff)
   997 
   998 end
   999 
  1000 definition (in term_syntax)
  1001   bagify :: "('a\<Colon>typerep \<times> nat) list \<times> (unit \<Rightarrow> Code_Evaluation.term)
  1002     \<Rightarrow> 'a multiset \<times> (unit \<Rightarrow> Code_Evaluation.term)" where
  1003   [code_unfold]: "bagify xs = Code_Evaluation.valtermify Bag {\<cdot>} xs"
  1004 
  1005 notation fcomp (infixl "o>" 60)
  1006 notation scomp (infixl "o\<rightarrow>" 60)
  1007 
  1008 instantiation multiset :: (random) random
  1009 begin
  1010 
  1011 definition
  1012   "Quickcheck.random i = Quickcheck.random i o\<rightarrow> (\<lambda>xs. Pair (bagify xs))"
  1013 
  1014 instance ..
  1015 
  1016 end
  1017 
  1018 no_notation fcomp (infixl "o>" 60)
  1019 no_notation scomp (infixl "o\<rightarrow>" 60)
  1020 
  1021 hide (open) const bagify
  1022 
  1023 
  1024 subsection {* The multiset order *}
  1025 
  1026 subsubsection {* Well-foundedness *}
  1027 
  1028 definition mult1 :: "('a \<times> 'a) set => ('a multiset \<times> 'a multiset) set" where
  1029   [code del]: "mult1 r = {(N, M). \<exists>a M0 K. M = M0 + {#a#} \<and> N = M0 + K \<and>
  1030       (\<forall>b. b :# K --> (b, a) \<in> r)}"
  1031 
  1032 definition mult :: "('a \<times> 'a) set => ('a multiset \<times> 'a multiset) set" where
  1033   [code del]: "mult r = (mult1 r)\<^sup>+"
  1034 
  1035 lemma not_less_empty [iff]: "(M, {#}) \<notin> mult1 r"
  1036 by (simp add: mult1_def)
  1037 
  1038 lemma less_add: "(N, M0 + {#a#}) \<in> mult1 r ==>
  1039     (\<exists>M. (M, M0) \<in> mult1 r \<and> N = M + {#a#}) \<or>
  1040     (\<exists>K. (\<forall>b. b :# K --> (b, a) \<in> r) \<and> N = M0 + K)"
  1041   (is "_ \<Longrightarrow> ?case1 (mult1 r) \<or> ?case2")
  1042 proof (unfold mult1_def)
  1043   let ?r = "\<lambda>K a. \<forall>b. b :# K --> (b, a) \<in> r"
  1044   let ?R = "\<lambda>N M. \<exists>a M0 K. M = M0 + {#a#} \<and> N = M0 + K \<and> ?r K a"
  1045   let ?case1 = "?case1 {(N, M). ?R N M}"
  1046 
  1047   assume "(N, M0 + {#a#}) \<in> {(N, M). ?R N M}"
  1048   then have "\<exists>a' M0' K.
  1049       M0 + {#a#} = M0' + {#a'#} \<and> N = M0' + K \<and> ?r K a'" by simp
  1050   then show "?case1 \<or> ?case2"
  1051   proof (elim exE conjE)
  1052     fix a' M0' K
  1053     assume N: "N = M0' + K" and r: "?r K a'"
  1054     assume "M0 + {#a#} = M0' + {#a'#}"
  1055     then have "M0 = M0' \<and> a = a' \<or>
  1056         (\<exists>K'. M0 = K' + {#a'#} \<and> M0' = K' + {#a#})"
  1057       by (simp only: add_eq_conv_ex)
  1058     then show ?thesis
  1059     proof (elim disjE conjE exE)
  1060       assume "M0 = M0'" "a = a'"
  1061       with N r have "?r K a \<and> N = M0 + K" by simp
  1062       then have ?case2 .. then show ?thesis ..
  1063     next
  1064       fix K'
  1065       assume "M0' = K' + {#a#}"
  1066       with N have n: "N = K' + K + {#a#}" by (simp add: add_ac)
  1067 
  1068       assume "M0 = K' + {#a'#}"
  1069       with r have "?R (K' + K) M0" by blast
  1070       with n have ?case1 by simp then show ?thesis ..
  1071     qed
  1072   qed
  1073 qed
  1074 
  1075 lemma all_accessible: "wf r ==> \<forall>M. M \<in> acc (mult1 r)"
  1076 proof
  1077   let ?R = "mult1 r"
  1078   let ?W = "acc ?R"
  1079   {
  1080     fix M M0 a
  1081     assume M0: "M0 \<in> ?W"
  1082       and wf_hyp: "!!b. (b, a) \<in> r ==> (\<forall>M \<in> ?W. M + {#b#} \<in> ?W)"
  1083       and acc_hyp: "\<forall>M. (M, M0) \<in> ?R --> M + {#a#} \<in> ?W"
  1084     have "M0 + {#a#} \<in> ?W"
  1085     proof (rule accI [of "M0 + {#a#}"])
  1086       fix N
  1087       assume "(N, M0 + {#a#}) \<in> ?R"
  1088       then have "((\<exists>M. (M, M0) \<in> ?R \<and> N = M + {#a#}) \<or>
  1089           (\<exists>K. (\<forall>b. b :# K --> (b, a) \<in> r) \<and> N = M0 + K))"
  1090         by (rule less_add)
  1091       then show "N \<in> ?W"
  1092       proof (elim exE disjE conjE)
  1093         fix M assume "(M, M0) \<in> ?R" and N: "N = M + {#a#}"
  1094         from acc_hyp have "(M, M0) \<in> ?R --> M + {#a#} \<in> ?W" ..
  1095         from this and `(M, M0) \<in> ?R` have "M + {#a#} \<in> ?W" ..
  1096         then show "N \<in> ?W" by (simp only: N)
  1097       next
  1098         fix K
  1099         assume N: "N = M0 + K"
  1100         assume "\<forall>b. b :# K --> (b, a) \<in> r"
  1101         then have "M0 + K \<in> ?W"
  1102         proof (induct K)
  1103           case empty
  1104           from M0 show "M0 + {#} \<in> ?W" by simp
  1105         next
  1106           case (add K x)
  1107           from add.prems have "(x, a) \<in> r" by simp
  1108           with wf_hyp have "\<forall>M \<in> ?W. M + {#x#} \<in> ?W" by blast
  1109           moreover from add have "M0 + K \<in> ?W" by simp
  1110           ultimately have "(M0 + K) + {#x#} \<in> ?W" ..
  1111           then show "M0 + (K + {#x#}) \<in> ?W" by (simp only: add_assoc)
  1112         qed
  1113         then show "N \<in> ?W" by (simp only: N)
  1114       qed
  1115     qed
  1116   } note tedious_reasoning = this
  1117 
  1118   assume wf: "wf r"
  1119   fix M
  1120   show "M \<in> ?W"
  1121   proof (induct M)
  1122     show "{#} \<in> ?W"
  1123     proof (rule accI)
  1124       fix b assume "(b, {#}) \<in> ?R"
  1125       with not_less_empty show "b \<in> ?W" by contradiction
  1126     qed
  1127 
  1128     fix M a assume "M \<in> ?W"
  1129     from wf have "\<forall>M \<in> ?W. M + {#a#} \<in> ?W"
  1130     proof induct
  1131       fix a
  1132       assume r: "!!b. (b, a) \<in> r ==> (\<forall>M \<in> ?W. M + {#b#} \<in> ?W)"
  1133       show "\<forall>M \<in> ?W. M + {#a#} \<in> ?W"
  1134       proof
  1135         fix M assume "M \<in> ?W"
  1136         then show "M + {#a#} \<in> ?W"
  1137           by (rule acc_induct) (rule tedious_reasoning [OF _ r])
  1138       qed
  1139     qed
  1140     from this and `M \<in> ?W` show "M + {#a#} \<in> ?W" ..
  1141   qed
  1142 qed
  1143 
  1144 theorem wf_mult1: "wf r ==> wf (mult1 r)"
  1145 by (rule acc_wfI) (rule all_accessible)
  1146 
  1147 theorem wf_mult: "wf r ==> wf (mult r)"
  1148 unfolding mult_def by (rule wf_trancl) (rule wf_mult1)
  1149 
  1150 
  1151 subsubsection {* Closure-free presentation *}
  1152 
  1153 text {* One direction. *}
  1154 
  1155 lemma mult_implies_one_step:
  1156   "trans r ==> (M, N) \<in> mult r ==>
  1157     \<exists>I J K. N = I + J \<and> M = I + K \<and> J \<noteq> {#} \<and>
  1158     (\<forall>k \<in> set_of K. \<exists>j \<in> set_of J. (k, j) \<in> r)"
  1159 apply (unfold mult_def mult1_def set_of_def)
  1160 apply (erule converse_trancl_induct, clarify)
  1161  apply (rule_tac x = M0 in exI, simp, clarify)
  1162 apply (case_tac "a :# K")
  1163  apply (rule_tac x = I in exI)
  1164  apply (simp (no_asm))
  1165  apply (rule_tac x = "(K - {#a#}) + Ka" in exI)
  1166  apply (simp (no_asm_simp) add: add_assoc [symmetric])
  1167  apply (drule_tac f = "\<lambda>M. M - {#a#}" in arg_cong)
  1168  apply (simp add: diff_union_single_conv)
  1169  apply (simp (no_asm_use) add: trans_def)
  1170  apply blast
  1171 apply (subgoal_tac "a :# I")
  1172  apply (rule_tac x = "I - {#a#}" in exI)
  1173  apply (rule_tac x = "J + {#a#}" in exI)
  1174  apply (rule_tac x = "K + Ka" in exI)
  1175  apply (rule conjI)
  1176   apply (simp add: multiset_eq_conv_count_eq split: nat_diff_split)
  1177  apply (rule conjI)
  1178   apply (drule_tac f = "\<lambda>M. M - {#a#}" in arg_cong, simp)
  1179   apply (simp add: multiset_eq_conv_count_eq split: nat_diff_split)
  1180  apply (simp (no_asm_use) add: trans_def)
  1181  apply blast
  1182 apply (subgoal_tac "a :# (M0 + {#a#})")
  1183  apply simp
  1184 apply (simp (no_asm))
  1185 done
  1186 
  1187 lemma one_step_implies_mult_aux:
  1188   "trans r ==>
  1189     \<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))
  1190       --> (I + K, I + J) \<in> mult r"
  1191 apply (induct_tac n, auto)
  1192 apply (frule size_eq_Suc_imp_eq_union, clarify)
  1193 apply (rename_tac "J'", simp)
  1194 apply (erule notE, auto)
  1195 apply (case_tac "J' = {#}")
  1196  apply (simp add: mult_def)
  1197  apply (rule r_into_trancl)
  1198  apply (simp add: mult1_def set_of_def, blast)
  1199 txt {* Now we know @{term "J' \<noteq> {#}"}. *}
  1200 apply (cut_tac M = K and P = "\<lambda>x. (x, a) \<in> r" in multiset_partition)
  1201 apply (erule_tac P = "\<forall>k \<in> set_of K. ?P k" in rev_mp)
  1202 apply (erule ssubst)
  1203 apply (simp add: Ball_def, auto)
  1204 apply (subgoal_tac
  1205   "((I + {# x :# K. (x, a) \<in> r #}) + {# x :# K. (x, a) \<notin> r #},
  1206     (I + {# x :# K. (x, a) \<in> r #}) + J') \<in> mult r")
  1207  prefer 2
  1208  apply force
  1209 apply (simp (no_asm_use) add: add_assoc [symmetric] mult_def)
  1210 apply (erule trancl_trans)
  1211 apply (rule r_into_trancl)
  1212 apply (simp add: mult1_def set_of_def)
  1213 apply (rule_tac x = a in exI)
  1214 apply (rule_tac x = "I + J'" in exI)
  1215 apply (simp add: add_ac)
  1216 done
  1217 
  1218 lemma one_step_implies_mult:
  1219   "trans r ==> J \<noteq> {#} ==> \<forall>k \<in> set_of K. \<exists>j \<in> set_of J. (k, j) \<in> r
  1220     ==> (I + K, I + J) \<in> mult r"
  1221 using one_step_implies_mult_aux by blast
  1222 
  1223 
  1224 subsubsection {* Partial-order properties *}
  1225 
  1226 instantiation multiset :: (order) order
  1227 begin
  1228 
  1229 definition less_multiset_def:
  1230   "M' < M \<longleftrightarrow> (M', M) \<in> mult {(x', x). x' < x}"
  1231 
  1232 definition le_multiset_def:
  1233   "M' <= M \<longleftrightarrow> M' = M \<or> M' < (M::'a multiset)"
  1234 
  1235 lemma trans_base_order: "trans {(x', x). x' < (x::'a::order)}"
  1236 unfolding trans_def by (blast intro: order_less_trans)
  1237 
  1238 text {*
  1239  \medskip Irreflexivity.
  1240 *}
  1241 
  1242 lemma mult_irrefl_aux:
  1243   "finite A ==> (\<forall>x \<in> A. \<exists>y \<in> A. x < (y::'a::order)) \<Longrightarrow> A = {}"
  1244 by (induct rule: finite_induct) (auto intro: order_less_trans)
  1245 
  1246 lemma mult_less_not_refl: "\<not> M < (M::'a::order multiset)"
  1247 apply (unfold less_multiset_def, auto)
  1248 apply (drule trans_base_order [THEN mult_implies_one_step], auto)
  1249 apply (drule finite_set_of [THEN mult_irrefl_aux [rule_format (no_asm)]])
  1250 apply (simp add: set_of_eq_empty_iff)
  1251 done
  1252 
  1253 lemma mult_less_irrefl [elim!]: "M < (M::'a::order multiset) ==> R"
  1254 using insert mult_less_not_refl by fast
  1255 
  1256 
  1257 text {* Transitivity. *}
  1258 
  1259 theorem mult_less_trans: "K < M ==> M < N ==> K < (N::'a::order multiset)"
  1260 unfolding less_multiset_def mult_def by (blast intro: trancl_trans)
  1261 
  1262 text {* Asymmetry. *}
  1263 
  1264 theorem mult_less_not_sym: "M < N ==> \<not> N < (M::'a::order multiset)"
  1265 apply auto
  1266 apply (rule mult_less_not_refl [THEN notE])
  1267 apply (erule mult_less_trans, assumption)
  1268 done
  1269 
  1270 theorem mult_less_asym:
  1271   "M < N ==> (\<not> P ==> N < (M::'a::order multiset)) ==> P"
  1272 using mult_less_not_sym by blast
  1273 
  1274 theorem mult_le_refl [iff]: "M <= (M::'a::order multiset)"
  1275 unfolding le_multiset_def by auto
  1276 
  1277 text {* Anti-symmetry. *}
  1278 
  1279 theorem mult_le_antisym:
  1280   "M <= N ==> N <= M ==> M = (N::'a::order multiset)"
  1281 unfolding le_multiset_def by (blast dest: mult_less_not_sym)
  1282 
  1283 text {* Transitivity. *}
  1284 
  1285 theorem mult_le_trans:
  1286   "K <= M ==> M <= N ==> K <= (N::'a::order multiset)"
  1287 unfolding le_multiset_def by (blast intro: mult_less_trans)
  1288 
  1289 theorem mult_less_le: "(M < N) = (M <= N \<and> M \<noteq> (N::'a::order multiset))"
  1290 unfolding le_multiset_def by auto
  1291 
  1292 instance proof
  1293 qed (auto simp add: mult_less_le dest: mult_le_antisym elim: mult_le_trans)
  1294 
  1295 end
  1296 
  1297 
  1298 subsubsection {* Monotonicity of multiset union *}
  1299 
  1300 lemma mult1_union:
  1301   "(B, D) \<in> mult1 r ==> trans r ==> (C + B, C + D) \<in> mult1 r"
  1302 apply (unfold mult1_def)
  1303 apply auto
  1304 apply (rule_tac x = a in exI)
  1305 apply (rule_tac x = "C + M0" in exI)
  1306 apply (simp add: add_assoc)
  1307 done
  1308 
  1309 lemma union_less_mono2: "B < D ==> C + B < C + (D::'a::order multiset)"
  1310 apply (unfold less_multiset_def mult_def)
  1311 apply (erule trancl_induct)
  1312  apply (blast intro: mult1_union transI order_less_trans r_into_trancl)
  1313 apply (blast intro: mult1_union transI order_less_trans r_into_trancl trancl_trans)
  1314 done
  1315 
  1316 lemma union_less_mono1: "B < D ==> B + C < D + (C::'a::order multiset)"
  1317 apply (subst add_commute [of B C])
  1318 apply (subst add_commute [of D C])
  1319 apply (erule union_less_mono2)
  1320 done
  1321 
  1322 lemma union_less_mono:
  1323   "A < C ==> B < D ==> A + B < C + (D::'a::order multiset)"
  1324 by (blast intro!: union_less_mono1 union_less_mono2 mult_less_trans)
  1325 
  1326 lemma union_le_mono:
  1327   "A <= C ==> B <= D ==> A + B <= C + (D::'a::order multiset)"
  1328 unfolding le_multiset_def
  1329 by (blast intro: union_less_mono union_less_mono1 union_less_mono2)
  1330 
  1331 lemma empty_leI [iff]: "{#} <= (M::'a::order multiset)"
  1332 apply (unfold le_multiset_def less_multiset_def)
  1333 apply (case_tac "M = {#}")
  1334  prefer 2
  1335  apply (subgoal_tac "({#} + {#}, {#} + M) \<in> mult (Collect (split op <))")
  1336   prefer 2
  1337   apply (rule one_step_implies_mult)
  1338     apply (simp only: trans_def)
  1339     apply auto
  1340 done
  1341 
  1342 lemma union_upper1: "A <= A + (B::'a::order multiset)"
  1343 proof -
  1344   have "A + {#} <= A + B" by (blast intro: union_le_mono)
  1345   then show ?thesis by simp
  1346 qed
  1347 
  1348 lemma union_upper2: "B <= A + (B::'a::order multiset)"
  1349 by (subst add_commute) (rule union_upper1)
  1350 
  1351 instance multiset :: (order) ordered_ab_semigroup_add
  1352 apply intro_classes
  1353 apply (erule union_le_mono[OF mult_le_refl])
  1354 done
  1355 
  1356 
  1357 subsection {* The fold combinator *}
  1358 
  1359 text {*
  1360   The intended behaviour is
  1361   @{text "fold_mset f z {#x\<^isub>1, ..., x\<^isub>n#} = f x\<^isub>1 (\<dots> (f x\<^isub>n z)\<dots>)"}
  1362   if @{text f} is associative-commutative. 
  1363 *}
  1364 
  1365 text {*
  1366   The graph of @{text "fold_mset"}, @{text "z"}: the start element,
  1367   @{text "f"}: folding function, @{text "A"}: the multiset, @{text
  1368   "y"}: the result.
  1369 *}
  1370 inductive 
  1371   fold_msetG :: "('a \<Rightarrow> 'b \<Rightarrow> 'b) \<Rightarrow> 'b \<Rightarrow> 'a multiset \<Rightarrow> 'b \<Rightarrow> bool" 
  1372   for f :: "'a \<Rightarrow> 'b \<Rightarrow> 'b" 
  1373   and z :: 'b
  1374 where
  1375   emptyI [intro]:  "fold_msetG f z {#} z"
  1376 | insertI [intro]: "fold_msetG f z A y \<Longrightarrow> fold_msetG f z (A + {#x#}) (f x y)"
  1377 
  1378 inductive_cases empty_fold_msetGE [elim!]: "fold_msetG f z {#} x"
  1379 inductive_cases insert_fold_msetGE: "fold_msetG f z (A + {#}) y" 
  1380 
  1381 definition
  1382   fold_mset :: "('a \<Rightarrow> 'b \<Rightarrow> 'b) \<Rightarrow> 'b \<Rightarrow> 'a multiset \<Rightarrow> 'b" where
  1383   "fold_mset f z A = (THE x. fold_msetG f z A x)"
  1384 
  1385 lemma Diff1_fold_msetG:
  1386   "fold_msetG f z (A - {#x#}) y \<Longrightarrow> x \<in># A \<Longrightarrow> fold_msetG f z A (f x y)"
  1387 apply (frule_tac x = x in fold_msetG.insertI)
  1388 apply auto
  1389 done
  1390 
  1391 lemma fold_msetG_nonempty: "\<exists>x. fold_msetG f z A x"
  1392 apply (induct A)
  1393  apply blast
  1394 apply clarsimp
  1395 apply (drule_tac x = x in fold_msetG.insertI)
  1396 apply auto
  1397 done
  1398 
  1399 lemma fold_mset_empty[simp]: "fold_mset f z {#} = z"
  1400 unfolding fold_mset_def by blast
  1401 
  1402 context fun_left_comm
  1403 begin
  1404 
  1405 lemma fold_msetG_determ:
  1406   "fold_msetG f z A x \<Longrightarrow> fold_msetG f z A y \<Longrightarrow> y = x"
  1407 proof (induct arbitrary: x y z rule: full_multiset_induct)
  1408   case (less M x\<^isub>1 x\<^isub>2 Z)
  1409   have IH: "\<forall>A. A \<subset># M \<longrightarrow> 
  1410     (\<forall>x x' x''. fold_msetG f x'' A x \<longrightarrow> fold_msetG f x'' A x'
  1411                \<longrightarrow> x' = x)" by fact
  1412   have Mfoldx\<^isub>1: "fold_msetG f Z M x\<^isub>1" and Mfoldx\<^isub>2: "fold_msetG f Z M x\<^isub>2" by fact+
  1413   show ?case
  1414   proof (rule fold_msetG.cases [OF Mfoldx\<^isub>1])
  1415     assume "M = {#}" and "x\<^isub>1 = Z"
  1416     then show ?case using Mfoldx\<^isub>2 by auto 
  1417   next
  1418     fix B b u
  1419     assume "M = B + {#b#}" and "x\<^isub>1 = f b u" and Bu: "fold_msetG f Z B u"
  1420     then have MBb: "M = B + {#b#}" and x\<^isub>1: "x\<^isub>1 = f b u" by auto
  1421     show ?case
  1422     proof (rule fold_msetG.cases [OF Mfoldx\<^isub>2])
  1423       assume "M = {#}" "x\<^isub>2 = Z"
  1424       then show ?case using Mfoldx\<^isub>1 by auto
  1425     next
  1426       fix C c v
  1427       assume "M = C + {#c#}" and "x\<^isub>2 = f c v" and Cv: "fold_msetG f Z C v"
  1428       then have MCc: "M = C + {#c#}" and x\<^isub>2: "x\<^isub>2 = f c v" by auto
  1429       then have CsubM: "C \<subset># M" by simp
  1430       from MBb have BsubM: "B \<subset># M" by simp
  1431       show ?case
  1432       proof cases
  1433         assume "b=c"
  1434         then moreover have "B = C" using MBb MCc by auto
  1435         ultimately show ?thesis using Bu Cv x\<^isub>1 x\<^isub>2 CsubM IH by auto
  1436       next
  1437         assume diff: "b \<noteq> c"
  1438         let ?D = "B - {#c#}"
  1439         have cinB: "c \<in># B" and binC: "b \<in># C" using MBb MCc diff
  1440           by (auto intro: insert_noteq_member dest: sym)
  1441         have "B - {#c#} \<subset># B" using cinB by (rule mset_less_diff_self)
  1442         then have DsubM: "?D \<subset># M" using BsubM by (blast intro: mset_order.less_trans)
  1443         from MBb MCc have "B + {#b#} = C + {#c#}" by blast
  1444         then have [simp]: "B + {#b#} - {#c#} = C"
  1445           using MBb MCc binC cinB by auto
  1446         have B: "B = ?D + {#c#}" and C: "C = ?D + {#b#}"
  1447           using MBb MCc diff binC cinB
  1448           by (auto simp: multiset_add_sub_el_shuffle)
  1449         then obtain d where Dfoldd: "fold_msetG f Z ?D d"
  1450           using fold_msetG_nonempty by iprover
  1451         then have "fold_msetG f Z B (f c d)" using cinB
  1452           by (rule Diff1_fold_msetG)
  1453         then have "f c d = u" using IH BsubM Bu by blast
  1454         moreover 
  1455         have "fold_msetG f Z C (f b d)" using binC cinB diff Dfoldd
  1456           by (auto simp: multiset_add_sub_el_shuffle 
  1457             dest: fold_msetG.insertI [where x=b])
  1458         then have "f b d = v" using IH CsubM Cv by blast
  1459         ultimately show ?thesis using x\<^isub>1 x\<^isub>2
  1460           by (auto simp: fun_left_comm)
  1461       qed
  1462     qed
  1463   qed
  1464 qed
  1465         
  1466 lemma fold_mset_insert_aux:
  1467   "(fold_msetG f z (A + {#x#}) v) =
  1468     (\<exists>y. fold_msetG f z A y \<and> v = f x y)"
  1469 apply (rule iffI)
  1470  prefer 2
  1471  apply blast
  1472 apply (rule_tac A=A and f=f in fold_msetG_nonempty [THEN exE, standard])
  1473 apply (blast intro: fold_msetG_determ)
  1474 done
  1475 
  1476 lemma fold_mset_equality: "fold_msetG f z A y \<Longrightarrow> fold_mset f z A = y"
  1477 unfolding fold_mset_def by (blast intro: fold_msetG_determ)
  1478 
  1479 lemma fold_mset_insert:
  1480   "fold_mset f z (A + {#x#}) = f x (fold_mset f z A)"
  1481 apply (simp add: fold_mset_def fold_mset_insert_aux add_commute)  
  1482 apply (rule the_equality)
  1483  apply (auto cong add: conj_cong 
  1484      simp add: fold_mset_def [symmetric] fold_mset_equality fold_msetG_nonempty)
  1485 done
  1486 
  1487 lemma fold_mset_insert_idem:
  1488   "fold_mset f z (A + {#a#}) = f a (fold_mset f z A)"
  1489 apply (simp add: fold_mset_def fold_mset_insert_aux)
  1490 apply (rule the_equality)
  1491  apply (auto cong add: conj_cong 
  1492      simp add: fold_mset_def [symmetric] fold_mset_equality fold_msetG_nonempty)
  1493 done
  1494 
  1495 lemma fold_mset_commute: "f x (fold_mset f z A) = fold_mset f (f x z) A"
  1496 by (induct A) (auto simp: fold_mset_insert fun_left_comm [of x])
  1497 
  1498 lemma fold_mset_single [simp]: "fold_mset f z {#x#} = f x z"
  1499 using fold_mset_insert [of z "{#}"] by simp
  1500 
  1501 lemma fold_mset_union [simp]:
  1502   "fold_mset f z (A+B) = fold_mset f (fold_mset f z A) B"
  1503 proof (induct A)
  1504   case empty then show ?case by simp
  1505 next
  1506   case (add A x)
  1507   have "A + {#x#} + B = (A+B) + {#x#}" by (simp add: add_ac)
  1508   then have "fold_mset f z (A + {#x#} + B) = f x (fold_mset f z (A + B))" 
  1509     by (simp add: fold_mset_insert)
  1510   also have "\<dots> = fold_mset f (fold_mset f z (A + {#x#})) B"
  1511     by (simp add: fold_mset_commute[of x,symmetric] add fold_mset_insert)
  1512   finally show ?case .
  1513 qed
  1514 
  1515 lemma fold_mset_fusion:
  1516   assumes "fun_left_comm g"
  1517   shows "(\<And>x y. h (g x y) = f x (h y)) \<Longrightarrow> h (fold_mset g w A) = fold_mset f (h w) A" (is "PROP ?P")
  1518 proof -
  1519   interpret fun_left_comm g by (fact assms)
  1520   show "PROP ?P" by (induct A) auto
  1521 qed
  1522 
  1523 lemma fold_mset_rec:
  1524   assumes "a \<in># A" 
  1525   shows "fold_mset f z A = f a (fold_mset f z (A - {#a#}))"
  1526 proof -
  1527   from assms obtain A' where "A = A' + {#a#}"
  1528     by (blast dest: multi_member_split)
  1529   then show ?thesis by simp
  1530 qed
  1531 
  1532 end
  1533 
  1534 text {*
  1535   A note on code generation: When defining some function containing a
  1536   subterm @{term"fold_mset F"}, code generation is not automatic. When
  1537   interpreting locale @{text left_commutative} with @{text F}, the
  1538   would be code thms for @{const fold_mset} become thms like
  1539   @{term"fold_mset F z {#} = z"} where @{text F} is not a pattern but
  1540   contains defined symbols, i.e.\ is not a code thm. Hence a separate
  1541   constant with its own code thms needs to be introduced for @{text
  1542   F}. See the image operator below.
  1543 *}
  1544 
  1545 
  1546 subsection {* Image *}
  1547 
  1548 definition image_mset :: "('a \<Rightarrow> 'b) \<Rightarrow> 'a multiset \<Rightarrow> 'b multiset" where
  1549   "image_mset f = fold_mset (op + o single o f) {#}"
  1550 
  1551 interpretation image_left_comm: fun_left_comm "op + o single o f"
  1552 proof qed (simp add: add_ac)
  1553 
  1554 lemma image_mset_empty [simp]: "image_mset f {#} = {#}"
  1555 by (simp add: image_mset_def)
  1556 
  1557 lemma image_mset_single [simp]: "image_mset f {#x#} = {#f x#}"
  1558 by (simp add: image_mset_def)
  1559 
  1560 lemma image_mset_insert:
  1561   "image_mset f (M + {#a#}) = image_mset f M + {#f a#}"
  1562 by (simp add: image_mset_def add_ac)
  1563 
  1564 lemma image_mset_union [simp]:
  1565   "image_mset f (M+N) = image_mset f M + image_mset f N"
  1566 apply (induct N)
  1567  apply simp
  1568 apply (simp add: add_assoc [symmetric] image_mset_insert)
  1569 done
  1570 
  1571 lemma size_image_mset [simp]: "size (image_mset f M) = size M"
  1572 by (induct M) simp_all
  1573 
  1574 lemma image_mset_is_empty_iff [simp]: "image_mset f M = {#} \<longleftrightarrow> M = {#}"
  1575 by (cases M) auto
  1576 
  1577 syntax
  1578   comprehension1_mset :: "'a \<Rightarrow> 'b \<Rightarrow> 'b multiset \<Rightarrow> 'a multiset"
  1579       ("({#_/. _ :# _#})")
  1580 translations
  1581   "{#e. x:#M#}" == "CONST image_mset (%x. e) M"
  1582 
  1583 syntax
  1584   comprehension2_mset :: "'a \<Rightarrow> 'b \<Rightarrow> 'b multiset \<Rightarrow> bool \<Rightarrow> 'a multiset"
  1585       ("({#_/ | _ :# _./ _#})")
  1586 translations
  1587   "{#e | x:#M. P#}" => "{#e. x :# {# x:#M. P#}#}"
  1588 
  1589 text {*
  1590   This allows to write not just filters like @{term "{#x:#M. x<c#}"}
  1591   but also images like @{term "{#x+x. x:#M #}"} and @{term [source]
  1592   "{#x+x|x:#M. x<c#}"}, where the latter is currently displayed as
  1593   @{term "{#x+x|x:#M. x<c#}"}.
  1594 *}
  1595 
  1596 
  1597 subsection {* Termination proofs with multiset orders *}
  1598 
  1599 lemma multi_member_skip: "x \<in># XS \<Longrightarrow> x \<in># {# y #} + XS"
  1600   and multi_member_this: "x \<in># {# x #} + XS"
  1601   and multi_member_last: "x \<in># {# x #}"
  1602   by auto
  1603 
  1604 definition "ms_strict = mult pair_less"
  1605 definition [code del]: "ms_weak = ms_strict \<union> Id"
  1606 
  1607 lemma ms_reduction_pair: "reduction_pair (ms_strict, ms_weak)"
  1608 unfolding reduction_pair_def ms_strict_def ms_weak_def pair_less_def
  1609 by (auto intro: wf_mult1 wf_trancl simp: mult_def)
  1610 
  1611 lemma smsI:
  1612   "(set_of A, set_of B) \<in> max_strict \<Longrightarrow> (Z + A, Z + B) \<in> ms_strict"
  1613   unfolding ms_strict_def
  1614 by (rule one_step_implies_mult) (auto simp add: max_strict_def pair_less_def elim!:max_ext.cases)
  1615 
  1616 lemma wmsI:
  1617   "(set_of A, set_of B) \<in> max_strict \<or> A = {#} \<and> B = {#}
  1618   \<Longrightarrow> (Z + A, Z + B) \<in> ms_weak"
  1619 unfolding ms_weak_def ms_strict_def
  1620 by (auto simp add: pair_less_def max_strict_def elim!:max_ext.cases intro: one_step_implies_mult)
  1621 
  1622 inductive pw_leq
  1623 where
  1624   pw_leq_empty: "pw_leq {#} {#}"
  1625 | pw_leq_step:  "\<lbrakk>(x,y) \<in> pair_leq; pw_leq X Y \<rbrakk> \<Longrightarrow> pw_leq ({#x#} + X) ({#y#} + Y)"
  1626 
  1627 lemma pw_leq_lstep:
  1628   "(x, y) \<in> pair_leq \<Longrightarrow> pw_leq {#x#} {#y#}"
  1629 by (drule pw_leq_step) (rule pw_leq_empty, simp)
  1630 
  1631 lemma pw_leq_split:
  1632   assumes "pw_leq X Y"
  1633   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 = {#}))"
  1634   using assms
  1635 proof (induct)
  1636   case pw_leq_empty thus ?case by auto
  1637 next
  1638   case (pw_leq_step x y X Y)
  1639   then obtain A B Z where
  1640     [simp]: "X = A + Z" "Y = B + Z" 
  1641       and 1[simp]: "(set_of A, set_of B) \<in> max_strict \<or> (B = {#} \<and> A = {#})" 
  1642     by auto
  1643   from pw_leq_step have "x = y \<or> (x, y) \<in> pair_less" 
  1644     unfolding pair_leq_def by auto
  1645   thus ?case
  1646   proof
  1647     assume [simp]: "x = y"
  1648     have
  1649       "{#x#} + X = A + ({#y#}+Z) 
  1650       \<and> {#y#} + Y = B + ({#y#}+Z)
  1651       \<and> ((set_of A, set_of B) \<in> max_strict \<or> (B = {#} \<and> A = {#}))"
  1652       by (auto simp: add_ac)
  1653     thus ?case by (intro exI)
  1654   next
  1655     assume A: "(x, y) \<in> pair_less"
  1656     let ?A' = "{#x#} + A" and ?B' = "{#y#} + B"
  1657     have "{#x#} + X = ?A' + Z"
  1658       "{#y#} + Y = ?B' + Z"
  1659       by (auto simp add: add_ac)
  1660     moreover have 
  1661       "(set_of ?A', set_of ?B') \<in> max_strict"
  1662       using 1 A unfolding max_strict_def 
  1663       by (auto elim!: max_ext.cases)
  1664     ultimately show ?thesis by blast
  1665   qed
  1666 qed
  1667 
  1668 lemma 
  1669   assumes pwleq: "pw_leq Z Z'"
  1670   shows ms_strictI: "(set_of A, set_of B) \<in> max_strict \<Longrightarrow> (Z + A, Z' + B) \<in> ms_strict"
  1671   and   ms_weakI1:  "(set_of A, set_of B) \<in> max_strict \<Longrightarrow> (Z + A, Z' + B) \<in> ms_weak"
  1672   and   ms_weakI2:  "(Z + {#}, Z' + {#}) \<in> ms_weak"
  1673 proof -
  1674   from pw_leq_split[OF pwleq] 
  1675   obtain A' B' Z''
  1676     where [simp]: "Z = A' + Z''" "Z' = B' + Z''"
  1677     and mx_or_empty: "(set_of A', set_of B') \<in> max_strict \<or> (A' = {#} \<and> B' = {#})"
  1678     by blast
  1679   {
  1680     assume max: "(set_of A, set_of B) \<in> max_strict"
  1681     from mx_or_empty
  1682     have "(Z'' + (A + A'), Z'' + (B + B')) \<in> ms_strict"
  1683     proof
  1684       assume max': "(set_of A', set_of B') \<in> max_strict"
  1685       with max have "(set_of (A + A'), set_of (B + B')) \<in> max_strict"
  1686         by (auto simp: max_strict_def intro: max_ext_additive)
  1687       thus ?thesis by (rule smsI) 
  1688     next
  1689       assume [simp]: "A' = {#} \<and> B' = {#}"
  1690       show ?thesis by (rule smsI) (auto intro: max)
  1691     qed
  1692     thus "(Z + A, Z' + B) \<in> ms_strict" by (simp add:add_ac)
  1693     thus "(Z + A, Z' + B) \<in> ms_weak" by (simp add: ms_weak_def)
  1694   }
  1695   from mx_or_empty
  1696   have "(Z'' + A', Z'' + B') \<in> ms_weak" by (rule wmsI)
  1697   thus "(Z + {#}, Z' + {#}) \<in> ms_weak" by (simp add:add_ac)
  1698 qed
  1699 
  1700 lemma empty_idemp: "{#} + x = x" "x + {#} = x"
  1701 and nonempty_plus: "{# x #} + rs \<noteq> {#}"
  1702 and nonempty_single: "{# x #} \<noteq> {#}"
  1703 by auto
  1704 
  1705 setup {*
  1706 let
  1707   fun msetT T = Type ("Multiset.multiset", [T]);
  1708 
  1709   fun mk_mset T [] = Const (@{const_name Mempty}, msetT T)
  1710     | mk_mset T [x] = Const (@{const_name single}, T --> msetT T) $ x
  1711     | mk_mset T (x :: xs) =
  1712           Const (@{const_name plus}, msetT T --> msetT T --> msetT T) $
  1713                 mk_mset T [x] $ mk_mset T xs
  1714 
  1715   fun mset_member_tac m i =
  1716       (if m <= 0 then
  1717            rtac @{thm multi_member_this} i ORELSE rtac @{thm multi_member_last} i
  1718        else
  1719            rtac @{thm multi_member_skip} i THEN mset_member_tac (m - 1) i)
  1720 
  1721   val mset_nonempty_tac =
  1722       rtac @{thm nonempty_plus} ORELSE' rtac @{thm nonempty_single}
  1723 
  1724   val regroup_munion_conv =
  1725       Function_Lib.regroup_conv @{const_name Multiset.Mempty} @{const_name plus}
  1726         (map (fn t => t RS eq_reflection) (@{thms add_ac} @ @{thms empty_idemp}))
  1727 
  1728   fun unfold_pwleq_tac i =
  1729     (rtac @{thm pw_leq_step} i THEN (fn st => unfold_pwleq_tac (i + 1) st))
  1730       ORELSE (rtac @{thm pw_leq_lstep} i)
  1731       ORELSE (rtac @{thm pw_leq_empty} i)
  1732 
  1733   val set_of_simps = [@{thm set_of_empty}, @{thm set_of_single}, @{thm set_of_union},
  1734                       @{thm Un_insert_left}, @{thm Un_empty_left}]
  1735 in
  1736   ScnpReconstruct.multiset_setup (ScnpReconstruct.Multiset 
  1737   {
  1738     msetT=msetT, mk_mset=mk_mset, mset_regroup_conv=regroup_munion_conv,
  1739     mset_member_tac=mset_member_tac, mset_nonempty_tac=mset_nonempty_tac,
  1740     mset_pwleq_tac=unfold_pwleq_tac, set_of_simps=set_of_simps,
  1741     smsI'= @{thm ms_strictI}, wmsI2''= @{thm ms_weakI2}, wmsI1= @{thm ms_weakI1},
  1742     reduction_pair= @{thm ms_reduction_pair}
  1743   })
  1744 end
  1745 *}
  1746 
  1747 
  1748 subsection {* Legacy theorem bindings *}
  1749 
  1750 lemmas multi_count_eq = multiset_eq_conv_count_eq [symmetric]
  1751 
  1752 lemma union_commute: "M + N = N + (M::'a multiset)"
  1753   by (fact add_commute)
  1754 
  1755 lemma union_assoc: "(M + N) + K = M + (N + (K::'a multiset))"
  1756   by (fact add_assoc)
  1757 
  1758 lemma union_lcomm: "M + (N + K) = N + (M + (K::'a multiset))"
  1759   by (fact add_left_commute)
  1760 
  1761 lemmas union_ac = union_assoc union_commute union_lcomm
  1762 
  1763 lemma union_right_cancel: "M + K = N + K \<longleftrightarrow> M = (N::'a multiset)"
  1764   by (fact add_right_cancel)
  1765 
  1766 lemma union_left_cancel: "K + M = K + N \<longleftrightarrow> M = (N::'a multiset)"
  1767   by (fact add_left_cancel)
  1768 
  1769 lemma multi_union_self_other_eq: "(A::'a multiset) + X = A + Y \<Longrightarrow> X = Y"
  1770   by (fact add_imp_eq)
  1771 
  1772 lemmas mset_less_trans = mset_order.less_trans
  1773 
  1774 end