src/HOL/Library/Multiset.thy
author kuncar
Fri Dec 09 18:07:04 2011 +0100 (2011-12-09)
changeset 45802 b16f976db515
parent 45694 4a8743618257
child 45866 e62b319c7696
permissions -rw-r--r--
Quotient_Info stores only relation maps
     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 context linorder
   861 begin
   862 
   863 lemma multiset_of_insort [simp]:
   864   "multiset_of (insort_key k x xs) = {#x#} + multiset_of xs"
   865   by (induct xs) (simp_all add: ac_simps)
   866  
   867 lemma multiset_of_sort [simp]:
   868   "multiset_of (sort_key k xs) = multiset_of xs"
   869   by (induct xs) (simp_all add: ac_simps)
   870 
   871 text {*
   872   This lemma shows which properties suffice to show that a function
   873   @{text "f"} with @{text "f xs = ys"} behaves like sort.
   874 *}
   875 
   876 lemma properties_for_sort_key:
   877   assumes "multiset_of ys = multiset_of xs"
   878   and "\<And>k. k \<in> set ys \<Longrightarrow> filter (\<lambda>x. f k = f x) ys = filter (\<lambda>x. f k = f x) xs"
   879   and "sorted (map f ys)"
   880   shows "sort_key f xs = ys"
   881 using assms proof (induct xs arbitrary: ys)
   882   case Nil then show ?case by simp
   883 next
   884   case (Cons x xs)
   885   from Cons.prems(2) have
   886     "\<forall>k \<in> set ys. filter (\<lambda>x. f k = f x) (remove1 x ys) = filter (\<lambda>x. f k = f x) xs"
   887     by (simp add: filter_remove1)
   888   with Cons.prems have "sort_key f xs = remove1 x ys"
   889     by (auto intro!: Cons.hyps simp add: sorted_map_remove1)
   890   moreover from Cons.prems have "x \<in> set ys"
   891     by (auto simp add: mem_set_multiset_eq intro!: ccontr)
   892   ultimately show ?case using Cons.prems by (simp add: insort_key_remove1)
   893 qed
   894 
   895 lemma properties_for_sort:
   896   assumes multiset: "multiset_of ys = multiset_of xs"
   897   and "sorted ys"
   898   shows "sort xs = ys"
   899 proof (rule properties_for_sort_key)
   900   from multiset show "multiset_of ys = multiset_of xs" .
   901   from `sorted ys` show "sorted (map (\<lambda>x. x) ys)" by simp
   902   from multiset have "\<And>k. length (filter (\<lambda>y. k = y) ys) = length (filter (\<lambda>x. k = x) xs)"
   903     by (rule multiset_of_eq_length_filter)
   904   then have "\<And>k. replicate (length (filter (\<lambda>y. k = y) ys)) k = replicate (length (filter (\<lambda>x. k = x) xs)) k"
   905     by simp
   906   then show "\<And>k. k \<in> set ys \<Longrightarrow> filter (\<lambda>y. k = y) ys = filter (\<lambda>x. k = x) xs"
   907     by (simp add: replicate_length_filter)
   908 qed
   909 
   910 lemma sort_key_by_quicksort:
   911   "sort_key f xs = sort_key f [x\<leftarrow>xs. f x < f (xs ! (length xs div 2))]
   912     @ [x\<leftarrow>xs. f x = f (xs ! (length xs div 2))]
   913     @ sort_key f [x\<leftarrow>xs. f x > f (xs ! (length xs div 2))]" (is "sort_key f ?lhs = ?rhs")
   914 proof (rule properties_for_sort_key)
   915   show "multiset_of ?rhs = multiset_of ?lhs"
   916     by (rule multiset_eqI) (auto simp add: multiset_of_filter)
   917 next
   918   show "sorted (map f ?rhs)"
   919     by (auto simp add: sorted_append intro: sorted_map_same)
   920 next
   921   fix l
   922   assume "l \<in> set ?rhs"
   923   let ?pivot = "f (xs ! (length xs div 2))"
   924   have *: "\<And>x. f l = f x \<longleftrightarrow> f x = f l" by auto
   925   have "[x \<leftarrow> sort_key f xs . f x = f l] = [x \<leftarrow> xs. f x = f l]"
   926     unfolding filter_sort by (rule properties_for_sort_key) (auto intro: sorted_map_same)
   927   with * have **: "[x \<leftarrow> sort_key f xs . f l = f x] = [x \<leftarrow> xs. f l = f x]" by simp
   928   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
   929   then have "\<And>P. [x \<leftarrow> sort_key f xs . P (f x) ?pivot \<and> f l = f x] =
   930     [x \<leftarrow> sort_key f xs. P (f l) ?pivot \<and> f l = f x]" by simp
   931   note *** = this [of "op <"] this [of "op >"] this [of "op ="]
   932   show "[x \<leftarrow> ?rhs. f l = f x] = [x \<leftarrow> ?lhs. f l = f x]"
   933   proof (cases "f l" ?pivot rule: linorder_cases)
   934     case less then moreover have "f l \<noteq> ?pivot" and "\<not> f l > ?pivot" by auto
   935     ultimately show ?thesis
   936       by (simp add: filter_sort [symmetric] ** ***)
   937   next
   938     case equal then show ?thesis
   939       by (simp add: * less_le)
   940   next
   941     case greater then moreover have "f l \<noteq> ?pivot" and "\<not> f l < ?pivot" by auto
   942     ultimately show ?thesis
   943       by (simp add: filter_sort [symmetric] ** ***)
   944   qed
   945 qed
   946 
   947 lemma sort_by_quicksort:
   948   "sort xs = sort [x\<leftarrow>xs. x < xs ! (length xs div 2)]
   949     @ [x\<leftarrow>xs. x = xs ! (length xs div 2)]
   950     @ sort [x\<leftarrow>xs. x > xs ! (length xs div 2)]" (is "sort ?lhs = ?rhs")
   951   using sort_key_by_quicksort [of "\<lambda>x. x", symmetric] by simp
   952 
   953 text {* A stable parametrized quicksort *}
   954 
   955 definition part :: "('b \<Rightarrow> 'a) \<Rightarrow> 'a \<Rightarrow> 'b list \<Rightarrow> 'b list \<times> 'b list \<times> 'b list" where
   956   "part f pivot xs = ([x \<leftarrow> xs. f x < pivot], [x \<leftarrow> xs. f x = pivot], [x \<leftarrow> xs. pivot < f x])"
   957 
   958 lemma part_code [code]:
   959   "part f pivot [] = ([], [], [])"
   960   "part f pivot (x # xs) = (let (lts, eqs, gts) = part f pivot xs; x' = f x in
   961      if x' < pivot then (x # lts, eqs, gts)
   962      else if x' > pivot then (lts, eqs, x # gts)
   963      else (lts, x # eqs, gts))"
   964   by (auto simp add: part_def Let_def split_def)
   965 
   966 lemma sort_key_by_quicksort_code [code]:
   967   "sort_key f xs = (case xs of [] \<Rightarrow> []
   968     | [x] \<Rightarrow> xs
   969     | [x, y] \<Rightarrow> (if f x \<le> f y then xs else [y, x])
   970     | _ \<Rightarrow> (let (lts, eqs, gts) = part f (f (xs ! (length xs div 2))) xs
   971        in sort_key f lts @ eqs @ sort_key f gts))"
   972 proof (cases xs)
   973   case Nil then show ?thesis by simp
   974 next
   975   case (Cons _ ys) note hyps = Cons show ?thesis proof (cases ys)
   976     case Nil with hyps show ?thesis by simp
   977   next
   978     case (Cons _ zs) note hyps = hyps Cons show ?thesis proof (cases zs)
   979       case Nil with hyps show ?thesis by auto
   980     next
   981       case Cons 
   982       from sort_key_by_quicksort [of f xs]
   983       have "sort_key f xs = (let (lts, eqs, gts) = part f (f (xs ! (length xs div 2))) xs
   984         in sort_key f lts @ eqs @ sort_key f gts)"
   985       by (simp only: split_def Let_def part_def fst_conv snd_conv)
   986       with hyps Cons show ?thesis by (simp only: list.cases)
   987     qed
   988   qed
   989 qed
   990 
   991 end
   992 
   993 hide_const (open) part
   994 
   995 lemma multiset_of_remdups_le: "multiset_of (remdups xs) \<le> multiset_of xs"
   996   by (induct xs) (auto intro: order_trans)
   997 
   998 lemma multiset_of_update:
   999   "i < length ls \<Longrightarrow> multiset_of (ls[i := v]) = multiset_of ls - {#ls ! i#} + {#v#}"
  1000 proof (induct ls arbitrary: i)
  1001   case Nil then show ?case by simp
  1002 next
  1003   case (Cons x xs)
  1004   show ?case
  1005   proof (cases i)
  1006     case 0 then show ?thesis by simp
  1007   next
  1008     case (Suc i')
  1009     with Cons show ?thesis
  1010       apply simp
  1011       apply (subst add_assoc)
  1012       apply (subst add_commute [of "{#v#}" "{#x#}"])
  1013       apply (subst add_assoc [symmetric])
  1014       apply simp
  1015       apply (rule mset_le_multiset_union_diff_commute)
  1016       apply (simp add: mset_le_single nth_mem_multiset_of)
  1017       done
  1018   qed
  1019 qed
  1020 
  1021 lemma multiset_of_swap:
  1022   "i < length ls \<Longrightarrow> j < length ls \<Longrightarrow>
  1023     multiset_of (ls[j := ls ! i, i := ls ! j]) = multiset_of ls"
  1024   by (cases "i = j") (simp_all add: multiset_of_update nth_mem_multiset_of)
  1025 
  1026 
  1027 subsubsection {* Association lists -- including rudimentary code generation *}
  1028 
  1029 definition count_of :: "('a \<times> nat) list \<Rightarrow> 'a \<Rightarrow> nat" where
  1030   "count_of xs x = (case map_of xs x of None \<Rightarrow> 0 | Some n \<Rightarrow> n)"
  1031 
  1032 lemma count_of_multiset:
  1033   "count_of xs \<in> multiset"
  1034 proof -
  1035   let ?A = "{x::'a. 0 < (case map_of xs x of None \<Rightarrow> 0\<Colon>nat | Some (n\<Colon>nat) \<Rightarrow> n)}"
  1036   have "?A \<subseteq> dom (map_of xs)"
  1037   proof
  1038     fix x
  1039     assume "x \<in> ?A"
  1040     then have "0 < (case map_of xs x of None \<Rightarrow> 0\<Colon>nat | Some (n\<Colon>nat) \<Rightarrow> n)" by simp
  1041     then have "map_of xs x \<noteq> None" by (cases "map_of xs x") auto
  1042     then show "x \<in> dom (map_of xs)" by auto
  1043   qed
  1044   with finite_dom_map_of [of xs] have "finite ?A"
  1045     by (auto intro: finite_subset)
  1046   then show ?thesis
  1047     by (simp add: count_of_def fun_eq_iff multiset_def)
  1048 qed
  1049 
  1050 lemma count_simps [simp]:
  1051   "count_of [] = (\<lambda>_. 0)"
  1052   "count_of ((x, n) # xs) = (\<lambda>y. if x = y then n else count_of xs y)"
  1053   by (simp_all add: count_of_def fun_eq_iff)
  1054 
  1055 lemma count_of_empty:
  1056   "x \<notin> fst ` set xs \<Longrightarrow> count_of xs x = 0"
  1057   by (induct xs) (simp_all add: count_of_def)
  1058 
  1059 lemma count_of_filter:
  1060   "count_of (filter (P \<circ> fst) xs) x = (if P x then count_of xs x else 0)"
  1061   by (induct xs) auto
  1062 
  1063 definition Bag :: "('a \<times> nat) list \<Rightarrow> 'a multiset" where
  1064   "Bag xs = Abs_multiset (count_of xs)"
  1065 
  1066 code_datatype Bag
  1067 
  1068 lemma count_Bag [simp, code]:
  1069   "count (Bag xs) = count_of xs"
  1070   by (simp add: Bag_def count_of_multiset Abs_multiset_inverse)
  1071 
  1072 lemma Mempty_Bag [code]:
  1073   "{#} = Bag []"
  1074   by (simp add: multiset_eq_iff)
  1075   
  1076 lemma single_Bag [code]:
  1077   "{#x#} = Bag [(x, 1)]"
  1078   by (simp add: multiset_eq_iff)
  1079 
  1080 lemma filter_Bag [code]:
  1081   "Multiset.filter P (Bag xs) = Bag (filter (P \<circ> fst) xs)"
  1082   by (rule multiset_eqI) (simp add: count_of_filter)
  1083 
  1084 lemma mset_less_eq_Bag [code]:
  1085   "Bag xs \<le> A \<longleftrightarrow> (\<forall>(x, n) \<in> set xs. count_of xs x \<le> count A x)"
  1086     (is "?lhs \<longleftrightarrow> ?rhs")
  1087 proof
  1088   assume ?lhs then show ?rhs
  1089     by (auto simp add: mset_le_def count_Bag)
  1090 next
  1091   assume ?rhs
  1092   show ?lhs
  1093   proof (rule mset_less_eqI)
  1094     fix x
  1095     from `?rhs` have "count_of xs x \<le> count A x"
  1096       by (cases "x \<in> fst ` set xs") (auto simp add: count_of_empty)
  1097     then show "count (Bag xs) x \<le> count A x"
  1098       by (simp add: mset_le_def count_Bag)
  1099   qed
  1100 qed
  1101 
  1102 instantiation multiset :: (equal) equal
  1103 begin
  1104 
  1105 definition
  1106   "HOL.equal A B \<longleftrightarrow> (A::'a multiset) \<le> B \<and> B \<le> A"
  1107 
  1108 instance proof
  1109 qed (simp add: equal_multiset_def eq_iff)
  1110 
  1111 end
  1112 
  1113 lemma [code nbe]:
  1114   "HOL.equal (A :: 'a::equal multiset) A \<longleftrightarrow> True"
  1115   by (fact equal_refl)
  1116 
  1117 definition (in term_syntax)
  1118   bagify :: "('a\<Colon>typerep \<times> nat) list \<times> (unit \<Rightarrow> Code_Evaluation.term)
  1119     \<Rightarrow> 'a multiset \<times> (unit \<Rightarrow> Code_Evaluation.term)" where
  1120   [code_unfold]: "bagify xs = Code_Evaluation.valtermify Bag {\<cdot>} xs"
  1121 
  1122 notation fcomp (infixl "\<circ>>" 60)
  1123 notation scomp (infixl "\<circ>\<rightarrow>" 60)
  1124 
  1125 instantiation multiset :: (random) random
  1126 begin
  1127 
  1128 definition
  1129   "Quickcheck.random i = Quickcheck.random i \<circ>\<rightarrow> (\<lambda>xs. Pair (bagify xs))"
  1130 
  1131 instance ..
  1132 
  1133 end
  1134 
  1135 no_notation fcomp (infixl "\<circ>>" 60)
  1136 no_notation scomp (infixl "\<circ>\<rightarrow>" 60)
  1137 
  1138 hide_const (open) bagify
  1139 
  1140 
  1141 subsection {* The multiset order *}
  1142 
  1143 subsubsection {* Well-foundedness *}
  1144 
  1145 definition mult1 :: "('a \<times> 'a) set => ('a multiset \<times> 'a multiset) set" where
  1146   "mult1 r = {(N, M). \<exists>a M0 K. M = M0 + {#a#} \<and> N = M0 + K \<and>
  1147       (\<forall>b. b :# K --> (b, a) \<in> r)}"
  1148 
  1149 definition mult :: "('a \<times> 'a) set => ('a multiset \<times> 'a multiset) set" where
  1150   "mult r = (mult1 r)\<^sup>+"
  1151 
  1152 lemma not_less_empty [iff]: "(M, {#}) \<notin> mult1 r"
  1153 by (simp add: mult1_def)
  1154 
  1155 lemma less_add: "(N, M0 + {#a#}) \<in> mult1 r ==>
  1156     (\<exists>M. (M, M0) \<in> mult1 r \<and> N = M + {#a#}) \<or>
  1157     (\<exists>K. (\<forall>b. b :# K --> (b, a) \<in> r) \<and> N = M0 + K)"
  1158   (is "_ \<Longrightarrow> ?case1 (mult1 r) \<or> ?case2")
  1159 proof (unfold mult1_def)
  1160   let ?r = "\<lambda>K a. \<forall>b. b :# K --> (b, a) \<in> r"
  1161   let ?R = "\<lambda>N M. \<exists>a M0 K. M = M0 + {#a#} \<and> N = M0 + K \<and> ?r K a"
  1162   let ?case1 = "?case1 {(N, M). ?R N M}"
  1163 
  1164   assume "(N, M0 + {#a#}) \<in> {(N, M). ?R N M}"
  1165   then have "\<exists>a' M0' K.
  1166       M0 + {#a#} = M0' + {#a'#} \<and> N = M0' + K \<and> ?r K a'" by simp
  1167   then show "?case1 \<or> ?case2"
  1168   proof (elim exE conjE)
  1169     fix a' M0' K
  1170     assume N: "N = M0' + K" and r: "?r K a'"
  1171     assume "M0 + {#a#} = M0' + {#a'#}"
  1172     then have "M0 = M0' \<and> a = a' \<or>
  1173         (\<exists>K'. M0 = K' + {#a'#} \<and> M0' = K' + {#a#})"
  1174       by (simp only: add_eq_conv_ex)
  1175     then show ?thesis
  1176     proof (elim disjE conjE exE)
  1177       assume "M0 = M0'" "a = a'"
  1178       with N r have "?r K a \<and> N = M0 + K" by simp
  1179       then have ?case2 .. then show ?thesis ..
  1180     next
  1181       fix K'
  1182       assume "M0' = K' + {#a#}"
  1183       with N have n: "N = K' + K + {#a#}" by (simp add: add_ac)
  1184 
  1185       assume "M0 = K' + {#a'#}"
  1186       with r have "?R (K' + K) M0" by blast
  1187       with n have ?case1 by simp then show ?thesis ..
  1188     qed
  1189   qed
  1190 qed
  1191 
  1192 lemma all_accessible: "wf r ==> \<forall>M. M \<in> acc (mult1 r)"
  1193 proof
  1194   let ?R = "mult1 r"
  1195   let ?W = "acc ?R"
  1196   {
  1197     fix M M0 a
  1198     assume M0: "M0 \<in> ?W"
  1199       and wf_hyp: "!!b. (b, a) \<in> r ==> (\<forall>M \<in> ?W. M + {#b#} \<in> ?W)"
  1200       and acc_hyp: "\<forall>M. (M, M0) \<in> ?R --> M + {#a#} \<in> ?W"
  1201     have "M0 + {#a#} \<in> ?W"
  1202     proof (rule accI [of "M0 + {#a#}"])
  1203       fix N
  1204       assume "(N, M0 + {#a#}) \<in> ?R"
  1205       then have "((\<exists>M. (M, M0) \<in> ?R \<and> N = M + {#a#}) \<or>
  1206           (\<exists>K. (\<forall>b. b :# K --> (b, a) \<in> r) \<and> N = M0 + K))"
  1207         by (rule less_add)
  1208       then show "N \<in> ?W"
  1209       proof (elim exE disjE conjE)
  1210         fix M assume "(M, M0) \<in> ?R" and N: "N = M + {#a#}"
  1211         from acc_hyp have "(M, M0) \<in> ?R --> M + {#a#} \<in> ?W" ..
  1212         from this and `(M, M0) \<in> ?R` have "M + {#a#} \<in> ?W" ..
  1213         then show "N \<in> ?W" by (simp only: N)
  1214       next
  1215         fix K
  1216         assume N: "N = M0 + K"
  1217         assume "\<forall>b. b :# K --> (b, a) \<in> r"
  1218         then have "M0 + K \<in> ?W"
  1219         proof (induct K)
  1220           case empty
  1221           from M0 show "M0 + {#} \<in> ?W" by simp
  1222         next
  1223           case (add K x)
  1224           from add.prems have "(x, a) \<in> r" by simp
  1225           with wf_hyp have "\<forall>M \<in> ?W. M + {#x#} \<in> ?W" by blast
  1226           moreover from add have "M0 + K \<in> ?W" by simp
  1227           ultimately have "(M0 + K) + {#x#} \<in> ?W" ..
  1228           then show "M0 + (K + {#x#}) \<in> ?W" by (simp only: add_assoc)
  1229         qed
  1230         then show "N \<in> ?W" by (simp only: N)
  1231       qed
  1232     qed
  1233   } note tedious_reasoning = this
  1234 
  1235   assume wf: "wf r"
  1236   fix M
  1237   show "M \<in> ?W"
  1238   proof (induct M)
  1239     show "{#} \<in> ?W"
  1240     proof (rule accI)
  1241       fix b assume "(b, {#}) \<in> ?R"
  1242       with not_less_empty show "b \<in> ?W" by contradiction
  1243     qed
  1244 
  1245     fix M a assume "M \<in> ?W"
  1246     from wf have "\<forall>M \<in> ?W. M + {#a#} \<in> ?W"
  1247     proof induct
  1248       fix a
  1249       assume r: "!!b. (b, a) \<in> r ==> (\<forall>M \<in> ?W. M + {#b#} \<in> ?W)"
  1250       show "\<forall>M \<in> ?W. M + {#a#} \<in> ?W"
  1251       proof
  1252         fix M assume "M \<in> ?W"
  1253         then show "M + {#a#} \<in> ?W"
  1254           by (rule acc_induct) (rule tedious_reasoning [OF _ r])
  1255       qed
  1256     qed
  1257     from this and `M \<in> ?W` show "M + {#a#} \<in> ?W" ..
  1258   qed
  1259 qed
  1260 
  1261 theorem wf_mult1: "wf r ==> wf (mult1 r)"
  1262 by (rule acc_wfI) (rule all_accessible)
  1263 
  1264 theorem wf_mult: "wf r ==> wf (mult r)"
  1265 unfolding mult_def by (rule wf_trancl) (rule wf_mult1)
  1266 
  1267 
  1268 subsubsection {* Closure-free presentation *}
  1269 
  1270 text {* One direction. *}
  1271 
  1272 lemma mult_implies_one_step:
  1273   "trans r ==> (M, N) \<in> mult r ==>
  1274     \<exists>I J K. N = I + J \<and> M = I + K \<and> J \<noteq> {#} \<and>
  1275     (\<forall>k \<in> set_of K. \<exists>j \<in> set_of J. (k, j) \<in> r)"
  1276 apply (unfold mult_def mult1_def set_of_def)
  1277 apply (erule converse_trancl_induct, clarify)
  1278  apply (rule_tac x = M0 in exI, simp, clarify)
  1279 apply (case_tac "a :# K")
  1280  apply (rule_tac x = I in exI)
  1281  apply (simp (no_asm))
  1282  apply (rule_tac x = "(K - {#a#}) + Ka" in exI)
  1283  apply (simp (no_asm_simp) add: add_assoc [symmetric])
  1284  apply (drule_tac f = "\<lambda>M. M - {#a#}" in arg_cong)
  1285  apply (simp add: diff_union_single_conv)
  1286  apply (simp (no_asm_use) add: trans_def)
  1287  apply blast
  1288 apply (subgoal_tac "a :# I")
  1289  apply (rule_tac x = "I - {#a#}" in exI)
  1290  apply (rule_tac x = "J + {#a#}" in exI)
  1291  apply (rule_tac x = "K + Ka" in exI)
  1292  apply (rule conjI)
  1293   apply (simp add: multiset_eq_iff split: nat_diff_split)
  1294  apply (rule conjI)
  1295   apply (drule_tac f = "\<lambda>M. M - {#a#}" in arg_cong, simp)
  1296   apply (simp add: multiset_eq_iff split: nat_diff_split)
  1297  apply (simp (no_asm_use) add: trans_def)
  1298  apply blast
  1299 apply (subgoal_tac "a :# (M0 + {#a#})")
  1300  apply simp
  1301 apply (simp (no_asm))
  1302 done
  1303 
  1304 lemma one_step_implies_mult_aux:
  1305   "trans r ==>
  1306     \<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))
  1307       --> (I + K, I + J) \<in> mult r"
  1308 apply (induct_tac n, auto)
  1309 apply (frule size_eq_Suc_imp_eq_union, clarify)
  1310 apply (rename_tac "J'", simp)
  1311 apply (erule notE, auto)
  1312 apply (case_tac "J' = {#}")
  1313  apply (simp add: mult_def)
  1314  apply (rule r_into_trancl)
  1315  apply (simp add: mult1_def set_of_def, blast)
  1316 txt {* Now we know @{term "J' \<noteq> {#}"}. *}
  1317 apply (cut_tac M = K and P = "\<lambda>x. (x, a) \<in> r" in multiset_partition)
  1318 apply (erule_tac P = "\<forall>k \<in> set_of K. ?P k" in rev_mp)
  1319 apply (erule ssubst)
  1320 apply (simp add: Ball_def, auto)
  1321 apply (subgoal_tac
  1322   "((I + {# x :# K. (x, a) \<in> r #}) + {# x :# K. (x, a) \<notin> r #},
  1323     (I + {# x :# K. (x, a) \<in> r #}) + J') \<in> mult r")
  1324  prefer 2
  1325  apply force
  1326 apply (simp (no_asm_use) add: add_assoc [symmetric] mult_def)
  1327 apply (erule trancl_trans)
  1328 apply (rule r_into_trancl)
  1329 apply (simp add: mult1_def set_of_def)
  1330 apply (rule_tac x = a in exI)
  1331 apply (rule_tac x = "I + J'" in exI)
  1332 apply (simp add: add_ac)
  1333 done
  1334 
  1335 lemma one_step_implies_mult:
  1336   "trans r ==> J \<noteq> {#} ==> \<forall>k \<in> set_of K. \<exists>j \<in> set_of J. (k, j) \<in> r
  1337     ==> (I + K, I + J) \<in> mult r"
  1338 using one_step_implies_mult_aux by blast
  1339 
  1340 
  1341 subsubsection {* Partial-order properties *}
  1342 
  1343 definition less_multiset :: "'a\<Colon>order multiset \<Rightarrow> 'a multiset \<Rightarrow> bool" (infix "<#" 50) where
  1344   "M' <# M \<longleftrightarrow> (M', M) \<in> mult {(x', x). x' < x}"
  1345 
  1346 definition le_multiset :: "'a\<Colon>order multiset \<Rightarrow> 'a multiset \<Rightarrow> bool" (infix "<=#" 50) where
  1347   "M' <=# M \<longleftrightarrow> M' <# M \<or> M' = M"
  1348 
  1349 notation (xsymbols) less_multiset (infix "\<subset>#" 50)
  1350 notation (xsymbols) le_multiset (infix "\<subseteq>#" 50)
  1351 
  1352 interpretation multiset_order: order le_multiset less_multiset
  1353 proof -
  1354   have irrefl: "\<And>M :: 'a multiset. \<not> M \<subset># M"
  1355   proof
  1356     fix M :: "'a multiset"
  1357     assume "M \<subset># M"
  1358     then have MM: "(M, M) \<in> mult {(x, y). x < y}" by (simp add: less_multiset_def)
  1359     have "trans {(x'::'a, x). x' < x}"
  1360       by (rule transI) simp
  1361     moreover note MM
  1362     ultimately have "\<exists>I J K. M = I + J \<and> M = I + K
  1363       \<and> J \<noteq> {#} \<and> (\<forall>k\<in>set_of K. \<exists>j\<in>set_of J. (k, j) \<in> {(x, y). x < y})"
  1364       by (rule mult_implies_one_step)
  1365     then obtain I J K where "M = I + J" and "M = I + K"
  1366       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
  1367     then have aux1: "K \<noteq> {#}" and aux2: "\<forall>k\<in>set_of K. \<exists>j\<in>set_of K. k < j" by auto
  1368     have "finite (set_of K)" by simp
  1369     moreover note aux2
  1370     ultimately have "set_of K = {}"
  1371       by (induct rule: finite_induct) (auto intro: order_less_trans)
  1372     with aux1 show False by simp
  1373   qed
  1374   have trans: "\<And>K M N :: 'a multiset. K \<subset># M \<Longrightarrow> M \<subset># N \<Longrightarrow> K \<subset># N"
  1375     unfolding less_multiset_def mult_def by (blast intro: trancl_trans)
  1376   show "class.order (le_multiset :: 'a multiset \<Rightarrow> _) less_multiset" proof
  1377   qed (auto simp add: le_multiset_def irrefl dest: trans)
  1378 qed
  1379 
  1380 lemma mult_less_irrefl [elim!]:
  1381   "M \<subset># (M::'a::order multiset) ==> R"
  1382   by (simp add: multiset_order.less_irrefl)
  1383 
  1384 
  1385 subsubsection {* Monotonicity of multiset union *}
  1386 
  1387 lemma mult1_union:
  1388   "(B, D) \<in> mult1 r ==> (C + B, C + D) \<in> mult1 r"
  1389 apply (unfold mult1_def)
  1390 apply auto
  1391 apply (rule_tac x = a in exI)
  1392 apply (rule_tac x = "C + M0" in exI)
  1393 apply (simp add: add_assoc)
  1394 done
  1395 
  1396 lemma union_less_mono2: "B \<subset># D ==> C + B \<subset># C + (D::'a::order multiset)"
  1397 apply (unfold less_multiset_def mult_def)
  1398 apply (erule trancl_induct)
  1399  apply (blast intro: mult1_union)
  1400 apply (blast intro: mult1_union trancl_trans)
  1401 done
  1402 
  1403 lemma union_less_mono1: "B \<subset># D ==> B + C \<subset># D + (C::'a::order multiset)"
  1404 apply (subst add_commute [of B C])
  1405 apply (subst add_commute [of D C])
  1406 apply (erule union_less_mono2)
  1407 done
  1408 
  1409 lemma union_less_mono:
  1410   "A \<subset># C ==> B \<subset># D ==> A + B \<subset># C + (D::'a::order multiset)"
  1411   by (blast intro!: union_less_mono1 union_less_mono2 multiset_order.less_trans)
  1412 
  1413 interpretation multiset_order: ordered_ab_semigroup_add plus le_multiset less_multiset
  1414 proof
  1415 qed (auto simp add: le_multiset_def intro: union_less_mono2)
  1416 
  1417 
  1418 subsection {* The fold combinator *}
  1419 
  1420 text {*
  1421   The intended behaviour is
  1422   @{text "fold_mset f z {#x\<^isub>1, ..., x\<^isub>n#} = f x\<^isub>1 (\<dots> (f x\<^isub>n z)\<dots>)"}
  1423   if @{text f} is associative-commutative. 
  1424 *}
  1425 
  1426 text {*
  1427   The graph of @{text "fold_mset"}, @{text "z"}: the start element,
  1428   @{text "f"}: folding function, @{text "A"}: the multiset, @{text
  1429   "y"}: the result.
  1430 *}
  1431 inductive 
  1432   fold_msetG :: "('a \<Rightarrow> 'b \<Rightarrow> 'b) \<Rightarrow> 'b \<Rightarrow> 'a multiset \<Rightarrow> 'b \<Rightarrow> bool" 
  1433   for f :: "'a \<Rightarrow> 'b \<Rightarrow> 'b" 
  1434   and z :: 'b
  1435 where
  1436   emptyI [intro]:  "fold_msetG f z {#} z"
  1437 | insertI [intro]: "fold_msetG f z A y \<Longrightarrow> fold_msetG f z (A + {#x#}) (f x y)"
  1438 
  1439 inductive_cases empty_fold_msetGE [elim!]: "fold_msetG f z {#} x"
  1440 inductive_cases insert_fold_msetGE: "fold_msetG f z (A + {#}) y" 
  1441 
  1442 definition
  1443   fold_mset :: "('a \<Rightarrow> 'b \<Rightarrow> 'b) \<Rightarrow> 'b \<Rightarrow> 'a multiset \<Rightarrow> 'b" where
  1444   "fold_mset f z A = (THE x. fold_msetG f z A x)"
  1445 
  1446 lemma Diff1_fold_msetG:
  1447   "fold_msetG f z (A - {#x#}) y \<Longrightarrow> x \<in># A \<Longrightarrow> fold_msetG f z A (f x y)"
  1448 apply (frule_tac x = x in fold_msetG.insertI)
  1449 apply auto
  1450 done
  1451 
  1452 lemma fold_msetG_nonempty: "\<exists>x. fold_msetG f z A x"
  1453 apply (induct A)
  1454  apply blast
  1455 apply clarsimp
  1456 apply (drule_tac x = x in fold_msetG.insertI)
  1457 apply auto
  1458 done
  1459 
  1460 lemma fold_mset_empty[simp]: "fold_mset f z {#} = z"
  1461 unfolding fold_mset_def by blast
  1462 
  1463 context comp_fun_commute
  1464 begin
  1465 
  1466 lemma fold_msetG_determ:
  1467   "fold_msetG f z A x \<Longrightarrow> fold_msetG f z A y \<Longrightarrow> y = x"
  1468 proof (induct arbitrary: x y z rule: full_multiset_induct)
  1469   case (less M x\<^isub>1 x\<^isub>2 Z)
  1470   have IH: "\<forall>A. A < M \<longrightarrow> 
  1471     (\<forall>x x' x''. fold_msetG f x'' A x \<longrightarrow> fold_msetG f x'' A x'
  1472                \<longrightarrow> x' = x)" by fact
  1473   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+
  1474   show ?case
  1475   proof (rule fold_msetG.cases [OF Mfoldx\<^isub>1])
  1476     assume "M = {#}" and "x\<^isub>1 = Z"
  1477     then show ?case using Mfoldx\<^isub>2 by auto 
  1478   next
  1479     fix B b u
  1480     assume "M = B + {#b#}" and "x\<^isub>1 = f b u" and Bu: "fold_msetG f Z B u"
  1481     then have MBb: "M = B + {#b#}" and x\<^isub>1: "x\<^isub>1 = f b u" by auto
  1482     show ?case
  1483     proof (rule fold_msetG.cases [OF Mfoldx\<^isub>2])
  1484       assume "M = {#}" "x\<^isub>2 = Z"
  1485       then show ?case using Mfoldx\<^isub>1 by auto
  1486     next
  1487       fix C c v
  1488       assume "M = C + {#c#}" and "x\<^isub>2 = f c v" and Cv: "fold_msetG f Z C v"
  1489       then have MCc: "M = C + {#c#}" and x\<^isub>2: "x\<^isub>2 = f c v" by auto
  1490       then have CsubM: "C < M" by simp
  1491       from MBb have BsubM: "B < M" by simp
  1492       show ?case
  1493       proof cases
  1494         assume "b=c"
  1495         then moreover have "B = C" using MBb MCc by auto
  1496         ultimately show ?thesis using Bu Cv x\<^isub>1 x\<^isub>2 CsubM IH by auto
  1497       next
  1498         assume diff: "b \<noteq> c"
  1499         let ?D = "B - {#c#}"
  1500         have cinB: "c \<in># B" and binC: "b \<in># C" using MBb MCc diff
  1501           by (auto intro: insert_noteq_member dest: sym)
  1502         have "B - {#c#} < B" using cinB by (rule mset_less_diff_self)
  1503         then have DsubM: "?D < M" using BsubM by (blast intro: order_less_trans)
  1504         from MBb MCc have "B + {#b#} = C + {#c#}" by blast
  1505         then have [simp]: "B + {#b#} - {#c#} = C"
  1506           using MBb MCc binC cinB by auto
  1507         have B: "B = ?D + {#c#}" and C: "C = ?D + {#b#}"
  1508           using MBb MCc diff binC cinB
  1509           by (auto simp: multiset_add_sub_el_shuffle)
  1510         then obtain d where Dfoldd: "fold_msetG f Z ?D d"
  1511           using fold_msetG_nonempty by iprover
  1512         then have "fold_msetG f Z B (f c d)" using cinB
  1513           by (rule Diff1_fold_msetG)
  1514         then have "f c d = u" using IH BsubM Bu by blast
  1515         moreover 
  1516         have "fold_msetG f Z C (f b d)" using binC cinB diff Dfoldd
  1517           by (auto simp: multiset_add_sub_el_shuffle 
  1518             dest: fold_msetG.insertI [where x=b])
  1519         then have "f b d = v" using IH CsubM Cv by blast
  1520         ultimately show ?thesis using x\<^isub>1 x\<^isub>2
  1521           by (auto simp: fun_left_comm)
  1522       qed
  1523     qed
  1524   qed
  1525 qed
  1526         
  1527 lemma fold_mset_insert_aux:
  1528   "(fold_msetG f z (A + {#x#}) v) =
  1529     (\<exists>y. fold_msetG f z A y \<and> v = f x y)"
  1530 apply (rule iffI)
  1531  prefer 2
  1532  apply blast
  1533 apply (rule_tac A1=A and f1=f in fold_msetG_nonempty [THEN exE])
  1534 apply (blast intro: fold_msetG_determ)
  1535 done
  1536 
  1537 lemma fold_mset_equality: "fold_msetG f z A y \<Longrightarrow> fold_mset f z A = y"
  1538 unfolding fold_mset_def by (blast intro: fold_msetG_determ)
  1539 
  1540 lemma fold_mset_insert:
  1541   "fold_mset f z (A + {#x#}) = f x (fold_mset f z A)"
  1542 apply (simp add: fold_mset_def fold_mset_insert_aux)
  1543 apply (rule the_equality)
  1544  apply (auto cong add: conj_cong 
  1545      simp add: fold_mset_def [symmetric] fold_mset_equality fold_msetG_nonempty)
  1546 done
  1547 
  1548 lemma fold_mset_commute: "f x (fold_mset f z A) = fold_mset f (f x z) A"
  1549 by (induct A) (auto simp: fold_mset_insert fun_left_comm [of x])
  1550 
  1551 lemma fold_mset_single [simp]: "fold_mset f z {#x#} = f x z"
  1552 using fold_mset_insert [of z "{#}"] by simp
  1553 
  1554 lemma fold_mset_union [simp]:
  1555   "fold_mset f z (A+B) = fold_mset f (fold_mset f z A) B"
  1556 proof (induct A)
  1557   case empty then show ?case by simp
  1558 next
  1559   case (add A x)
  1560   have "A + {#x#} + B = (A+B) + {#x#}" by (simp add: add_ac)
  1561   then have "fold_mset f z (A + {#x#} + B) = f x (fold_mset f z (A + B))" 
  1562     by (simp add: fold_mset_insert)
  1563   also have "\<dots> = fold_mset f (fold_mset f z (A + {#x#})) B"
  1564     by (simp add: fold_mset_commute[of x,symmetric] add fold_mset_insert)
  1565   finally show ?case .
  1566 qed
  1567 
  1568 lemma fold_mset_fusion:
  1569   assumes "comp_fun_commute g"
  1570   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")
  1571 proof -
  1572   interpret comp_fun_commute g by (fact assms)
  1573   show "PROP ?P" by (induct A) auto
  1574 qed
  1575 
  1576 lemma fold_mset_rec:
  1577   assumes "a \<in># A" 
  1578   shows "fold_mset f z A = f a (fold_mset f z (A - {#a#}))"
  1579 proof -
  1580   from assms obtain A' where "A = A' + {#a#}"
  1581     by (blast dest: multi_member_split)
  1582   then show ?thesis by simp
  1583 qed
  1584 
  1585 end
  1586 
  1587 text {*
  1588   A note on code generation: When defining some function containing a
  1589   subterm @{term"fold_mset F"}, code generation is not automatic. When
  1590   interpreting locale @{text left_commutative} with @{text F}, the
  1591   would be code thms for @{const fold_mset} become thms like
  1592   @{term"fold_mset F z {#} = z"} where @{text F} is not a pattern but
  1593   contains defined symbols, i.e.\ is not a code thm. Hence a separate
  1594   constant with its own code thms needs to be introduced for @{text
  1595   F}. See the image operator below.
  1596 *}
  1597 
  1598 
  1599 subsection {* Image *}
  1600 
  1601 definition image_mset :: "('a \<Rightarrow> 'b) \<Rightarrow> 'a multiset \<Rightarrow> 'b multiset" where
  1602   "image_mset f = fold_mset (op + o single o f) {#}"
  1603 
  1604 interpretation image_fun_commute: comp_fun_commute "op + o single o f" for f
  1605 proof qed (simp add: add_ac fun_eq_iff)
  1606 
  1607 lemma image_mset_empty [simp]: "image_mset f {#} = {#}"
  1608 by (simp add: image_mset_def)
  1609 
  1610 lemma image_mset_single [simp]: "image_mset f {#x#} = {#f x#}"
  1611 by (simp add: image_mset_def)
  1612 
  1613 lemma image_mset_insert:
  1614   "image_mset f (M + {#a#}) = image_mset f M + {#f a#}"
  1615 by (simp add: image_mset_def add_ac)
  1616 
  1617 lemma image_mset_union [simp]:
  1618   "image_mset f (M+N) = image_mset f M + image_mset f N"
  1619 apply (induct N)
  1620  apply simp
  1621 apply (simp add: add_assoc [symmetric] image_mset_insert)
  1622 done
  1623 
  1624 lemma size_image_mset [simp]: "size (image_mset f M) = size M"
  1625 by (induct M) simp_all
  1626 
  1627 lemma image_mset_is_empty_iff [simp]: "image_mset f M = {#} \<longleftrightarrow> M = {#}"
  1628 by (cases M) auto
  1629 
  1630 syntax
  1631   "_comprehension1_mset" :: "'a \<Rightarrow> 'b \<Rightarrow> 'b multiset \<Rightarrow> 'a multiset"
  1632       ("({#_/. _ :# _#})")
  1633 translations
  1634   "{#e. x:#M#}" == "CONST image_mset (%x. e) M"
  1635 
  1636 syntax
  1637   "_comprehension2_mset" :: "'a \<Rightarrow> 'b \<Rightarrow> 'b multiset \<Rightarrow> bool \<Rightarrow> 'a multiset"
  1638       ("({#_/ | _ :# _./ _#})")
  1639 translations
  1640   "{#e | x:#M. P#}" => "{#e. x :# {# x:#M. P#}#}"
  1641 
  1642 text {*
  1643   This allows to write not just filters like @{term "{#x:#M. x<c#}"}
  1644   but also images like @{term "{#x+x. x:#M #}"} and @{term [source]
  1645   "{#x+x|x:#M. x<c#}"}, where the latter is currently displayed as
  1646   @{term "{#x+x|x:#M. x<c#}"}.
  1647 *}
  1648 
  1649 enriched_type image_mset: image_mset proof -
  1650   fix f g 
  1651   show "image_mset f \<circ> image_mset g = image_mset (f \<circ> g)"
  1652   proof
  1653     fix A
  1654     show "(image_mset f \<circ> image_mset g) A = image_mset (f \<circ> g) A"
  1655       by (induct A) simp_all
  1656   qed
  1657 next
  1658   show "image_mset id = id"
  1659   proof
  1660     fix A
  1661     show "image_mset id A = id A"
  1662       by (induct A) simp_all
  1663   qed
  1664 qed
  1665 
  1666 
  1667 subsection {* Termination proofs with multiset orders *}
  1668 
  1669 lemma multi_member_skip: "x \<in># XS \<Longrightarrow> x \<in># {# y #} + XS"
  1670   and multi_member_this: "x \<in># {# x #} + XS"
  1671   and multi_member_last: "x \<in># {# x #}"
  1672   by auto
  1673 
  1674 definition "ms_strict = mult pair_less"
  1675 definition "ms_weak = ms_strict \<union> Id"
  1676 
  1677 lemma ms_reduction_pair: "reduction_pair (ms_strict, ms_weak)"
  1678 unfolding reduction_pair_def ms_strict_def ms_weak_def pair_less_def
  1679 by (auto intro: wf_mult1 wf_trancl simp: mult_def)
  1680 
  1681 lemma smsI:
  1682   "(set_of A, set_of B) \<in> max_strict \<Longrightarrow> (Z + A, Z + B) \<in> ms_strict"
  1683   unfolding ms_strict_def
  1684 by (rule one_step_implies_mult) (auto simp add: max_strict_def pair_less_def elim!:max_ext.cases)
  1685 
  1686 lemma wmsI:
  1687   "(set_of A, set_of B) \<in> max_strict \<or> A = {#} \<and> B = {#}
  1688   \<Longrightarrow> (Z + A, Z + B) \<in> ms_weak"
  1689 unfolding ms_weak_def ms_strict_def
  1690 by (auto simp add: pair_less_def max_strict_def elim!:max_ext.cases intro: one_step_implies_mult)
  1691 
  1692 inductive pw_leq
  1693 where
  1694   pw_leq_empty: "pw_leq {#} {#}"
  1695 | pw_leq_step:  "\<lbrakk>(x,y) \<in> pair_leq; pw_leq X Y \<rbrakk> \<Longrightarrow> pw_leq ({#x#} + X) ({#y#} + Y)"
  1696 
  1697 lemma pw_leq_lstep:
  1698   "(x, y) \<in> pair_leq \<Longrightarrow> pw_leq {#x#} {#y#}"
  1699 by (drule pw_leq_step) (rule pw_leq_empty, simp)
  1700 
  1701 lemma pw_leq_split:
  1702   assumes "pw_leq X Y"
  1703   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 = {#}))"
  1704   using assms
  1705 proof (induct)
  1706   case pw_leq_empty thus ?case by auto
  1707 next
  1708   case (pw_leq_step x y X Y)
  1709   then obtain A B Z where
  1710     [simp]: "X = A + Z" "Y = B + Z" 
  1711       and 1[simp]: "(set_of A, set_of B) \<in> max_strict \<or> (B = {#} \<and> A = {#})" 
  1712     by auto
  1713   from pw_leq_step have "x = y \<or> (x, y) \<in> pair_less" 
  1714     unfolding pair_leq_def by auto
  1715   thus ?case
  1716   proof
  1717     assume [simp]: "x = y"
  1718     have
  1719       "{#x#} + X = A + ({#y#}+Z) 
  1720       \<and> {#y#} + Y = B + ({#y#}+Z)
  1721       \<and> ((set_of A, set_of B) \<in> max_strict \<or> (B = {#} \<and> A = {#}))"
  1722       by (auto simp: add_ac)
  1723     thus ?case by (intro exI)
  1724   next
  1725     assume A: "(x, y) \<in> pair_less"
  1726     let ?A' = "{#x#} + A" and ?B' = "{#y#} + B"
  1727     have "{#x#} + X = ?A' + Z"
  1728       "{#y#} + Y = ?B' + Z"
  1729       by (auto simp add: add_ac)
  1730     moreover have 
  1731       "(set_of ?A', set_of ?B') \<in> max_strict"
  1732       using 1 A unfolding max_strict_def 
  1733       by (auto elim!: max_ext.cases)
  1734     ultimately show ?thesis by blast
  1735   qed
  1736 qed
  1737 
  1738 lemma 
  1739   assumes pwleq: "pw_leq Z Z'"
  1740   shows ms_strictI: "(set_of A, set_of B) \<in> max_strict \<Longrightarrow> (Z + A, Z' + B) \<in> ms_strict"
  1741   and   ms_weakI1:  "(set_of A, set_of B) \<in> max_strict \<Longrightarrow> (Z + A, Z' + B) \<in> ms_weak"
  1742   and   ms_weakI2:  "(Z + {#}, Z' + {#}) \<in> ms_weak"
  1743 proof -
  1744   from pw_leq_split[OF pwleq] 
  1745   obtain A' B' Z''
  1746     where [simp]: "Z = A' + Z''" "Z' = B' + Z''"
  1747     and mx_or_empty: "(set_of A', set_of B') \<in> max_strict \<or> (A' = {#} \<and> B' = {#})"
  1748     by blast
  1749   {
  1750     assume max: "(set_of A, set_of B) \<in> max_strict"
  1751     from mx_or_empty
  1752     have "(Z'' + (A + A'), Z'' + (B + B')) \<in> ms_strict"
  1753     proof
  1754       assume max': "(set_of A', set_of B') \<in> max_strict"
  1755       with max have "(set_of (A + A'), set_of (B + B')) \<in> max_strict"
  1756         by (auto simp: max_strict_def intro: max_ext_additive)
  1757       thus ?thesis by (rule smsI) 
  1758     next
  1759       assume [simp]: "A' = {#} \<and> B' = {#}"
  1760       show ?thesis by (rule smsI) (auto intro: max)
  1761     qed
  1762     thus "(Z + A, Z' + B) \<in> ms_strict" by (simp add:add_ac)
  1763     thus "(Z + A, Z' + B) \<in> ms_weak" by (simp add: ms_weak_def)
  1764   }
  1765   from mx_or_empty
  1766   have "(Z'' + A', Z'' + B') \<in> ms_weak" by (rule wmsI)
  1767   thus "(Z + {#}, Z' + {#}) \<in> ms_weak" by (simp add:add_ac)
  1768 qed
  1769 
  1770 lemma empty_neutral: "{#} + x = x" "x + {#} = x"
  1771 and nonempty_plus: "{# x #} + rs \<noteq> {#}"
  1772 and nonempty_single: "{# x #} \<noteq> {#}"
  1773 by auto
  1774 
  1775 setup {*
  1776 let
  1777   fun msetT T = Type (@{type_name multiset}, [T]);
  1778 
  1779   fun mk_mset T [] = Const (@{const_abbrev Mempty}, msetT T)
  1780     | mk_mset T [x] = Const (@{const_name single}, T --> msetT T) $ x
  1781     | mk_mset T (x :: xs) =
  1782           Const (@{const_name plus}, msetT T --> msetT T --> msetT T) $
  1783                 mk_mset T [x] $ mk_mset T xs
  1784 
  1785   fun mset_member_tac m i =
  1786       (if m <= 0 then
  1787            rtac @{thm multi_member_this} i ORELSE rtac @{thm multi_member_last} i
  1788        else
  1789            rtac @{thm multi_member_skip} i THEN mset_member_tac (m - 1) i)
  1790 
  1791   val mset_nonempty_tac =
  1792       rtac @{thm nonempty_plus} ORELSE' rtac @{thm nonempty_single}
  1793 
  1794   val regroup_munion_conv =
  1795       Function_Lib.regroup_conv @{const_abbrev Mempty} @{const_name plus}
  1796         (map (fn t => t RS eq_reflection) (@{thms add_ac} @ @{thms empty_neutral}))
  1797 
  1798   fun unfold_pwleq_tac i =
  1799     (rtac @{thm pw_leq_step} i THEN (fn st => unfold_pwleq_tac (i + 1) st))
  1800       ORELSE (rtac @{thm pw_leq_lstep} i)
  1801       ORELSE (rtac @{thm pw_leq_empty} i)
  1802 
  1803   val set_of_simps = [@{thm set_of_empty}, @{thm set_of_single}, @{thm set_of_union},
  1804                       @{thm Un_insert_left}, @{thm Un_empty_left}]
  1805 in
  1806   ScnpReconstruct.multiset_setup (ScnpReconstruct.Multiset 
  1807   {
  1808     msetT=msetT, mk_mset=mk_mset, mset_regroup_conv=regroup_munion_conv,
  1809     mset_member_tac=mset_member_tac, mset_nonempty_tac=mset_nonempty_tac,
  1810     mset_pwleq_tac=unfold_pwleq_tac, set_of_simps=set_of_simps,
  1811     smsI'= @{thm ms_strictI}, wmsI2''= @{thm ms_weakI2}, wmsI1= @{thm ms_weakI1},
  1812     reduction_pair= @{thm ms_reduction_pair}
  1813   })
  1814 end
  1815 *}
  1816 
  1817 
  1818 subsection {* Legacy theorem bindings *}
  1819 
  1820 lemmas multi_count_eq = multiset_eq_iff [symmetric]
  1821 
  1822 lemma union_commute: "M + N = N + (M::'a multiset)"
  1823   by (fact add_commute)
  1824 
  1825 lemma union_assoc: "(M + N) + K = M + (N + (K::'a multiset))"
  1826   by (fact add_assoc)
  1827 
  1828 lemma union_lcomm: "M + (N + K) = N + (M + (K::'a multiset))"
  1829   by (fact add_left_commute)
  1830 
  1831 lemmas union_ac = union_assoc union_commute union_lcomm
  1832 
  1833 lemma union_right_cancel: "M + K = N + K \<longleftrightarrow> M = (N::'a multiset)"
  1834   by (fact add_right_cancel)
  1835 
  1836 lemma union_left_cancel: "K + M = K + N \<longleftrightarrow> M = (N::'a multiset)"
  1837   by (fact add_left_cancel)
  1838 
  1839 lemma multi_union_self_other_eq: "(A::'a multiset) + X = A + Y \<Longrightarrow> X = Y"
  1840   by (fact add_imp_eq)
  1841 
  1842 lemma mset_less_trans: "(M::'a multiset) < K \<Longrightarrow> K < N \<Longrightarrow> M < N"
  1843   by (fact order_less_trans)
  1844 
  1845 lemma multiset_inter_commute: "A #\<inter> B = B #\<inter> A"
  1846   by (fact inf.commute)
  1847 
  1848 lemma multiset_inter_assoc: "A #\<inter> (B #\<inter> C) = A #\<inter> B #\<inter> C"
  1849   by (fact inf.assoc [symmetric])
  1850 
  1851 lemma multiset_inter_left_commute: "A #\<inter> (B #\<inter> C) = B #\<inter> (A #\<inter> C)"
  1852   by (fact inf.left_commute)
  1853 
  1854 lemmas multiset_inter_ac =
  1855   multiset_inter_commute
  1856   multiset_inter_assoc
  1857   multiset_inter_left_commute
  1858 
  1859 lemma mult_less_not_refl:
  1860   "\<not> M \<subset># (M::'a::order multiset)"
  1861   by (fact multiset_order.less_irrefl)
  1862 
  1863 lemma mult_less_trans:
  1864   "K \<subset># M ==> M \<subset># N ==> K \<subset># (N::'a::order multiset)"
  1865   by (fact multiset_order.less_trans)
  1866     
  1867 lemma mult_less_not_sym:
  1868   "M \<subset># N ==> \<not> N \<subset># (M::'a::order multiset)"
  1869   by (fact multiset_order.less_not_sym)
  1870 
  1871 lemma mult_less_asym:
  1872   "M \<subset># N ==> (\<not> P ==> N \<subset># (M::'a::order multiset)) ==> P"
  1873   by (fact multiset_order.less_asym)
  1874 
  1875 ML {*
  1876 fun multiset_postproc _ maybe_name all_values (T as Type (_, [elem_T]))
  1877                       (Const _ $ t') =
  1878     let
  1879       val (maybe_opt, ps) =
  1880         Nitpick_Model.dest_plain_fun t' ||> op ~~
  1881         ||> map (apsnd (snd o HOLogic.dest_number))
  1882       fun elems_for t =
  1883         case AList.lookup (op =) ps t of
  1884           SOME n => replicate n t
  1885         | NONE => [Const (maybe_name, elem_T --> elem_T) $ t]
  1886     in
  1887       case maps elems_for (all_values elem_T) @
  1888            (if maybe_opt then [Const (Nitpick_Model.unrep (), elem_T)]
  1889             else []) of
  1890         [] => Const (@{const_name zero_class.zero}, T)
  1891       | ts => foldl1 (fn (t1, t2) =>
  1892                          Const (@{const_name plus_class.plus}, T --> T --> T)
  1893                          $ t1 $ t2)
  1894                      (map (curry (op $) (Const (@{const_name single},
  1895                                                 elem_T --> T))) ts)
  1896     end
  1897   | multiset_postproc _ _ _ _ t = t
  1898 *}
  1899 
  1900 declaration {*
  1901 Nitpick_Model.register_term_postprocessor @{typ "'a multiset"}
  1902     multiset_postproc
  1903 *}
  1904 
  1905 end