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