src/HOL/Library/Multiset.thy
 author wenzelm Wed Jun 17 18:22:29 2015 +0200 (2015-06-17) changeset 60503 47df24e05b1c parent 60498 c8141ac6f03f parent 60502 aa58872267ee child 60513 55c7316f76d6 permissions -rw-r--r--
merged
1 (*  Title:      HOL/Library/Multiset.thy
2     Author:     Tobias Nipkow, Markus Wenzel, Lawrence C Paulson, Norbert Voelker
3     Author:     Andrei Popescu, TU Muenchen
4     Author:     Jasmin Blanchette, Inria, LORIA, MPII
5     Author:     Dmitriy Traytel, TU Muenchen
6     Author:     Mathias Fleury, MPII
7 *)
9 section \<open>(Finite) multisets\<close>
11 theory Multiset
12 imports Main
13 begin
15 subsection \<open>The type of multisets\<close>
17 definition "multiset = {f :: 'a => nat. finite {x. f x > 0}}"
19 typedef 'a multiset = "multiset :: ('a => nat) set"
20   morphisms count Abs_multiset
21   unfolding multiset_def
22 proof
23   show "(\<lambda>x. 0::nat) \<in> {f. finite {x. f x > 0}}" by simp
24 qed
26 setup_lifting type_definition_multiset
28 abbreviation Melem :: "'a => 'a multiset => bool"  ("(_/ :# _)" [50, 51] 50) where
29   "a :# M == 0 < count M a"
31 notation (xsymbols)
32   Melem (infix "\<in>#" 50)
34 lemma multiset_eq_iff:
35   "M = N \<longleftrightarrow> (\<forall>a. count M a = count N a)"
36   by (simp only: count_inject [symmetric] fun_eq_iff)
38 lemma multiset_eqI:
39   "(\<And>x. count A x = count B x) \<Longrightarrow> A = B"
40   using multiset_eq_iff by auto
42 text \<open>
43  \medskip Preservation of the representing set @{term multiset}.
44 \<close>
46 lemma const0_in_multiset:
47   "(\<lambda>a. 0) \<in> multiset"
48   by (simp add: multiset_def)
50 lemma only1_in_multiset:
51   "(\<lambda>b. if b = a then n else 0) \<in> multiset"
52   by (simp add: multiset_def)
54 lemma union_preserves_multiset:
55   "M \<in> multiset \<Longrightarrow> N \<in> multiset \<Longrightarrow> (\<lambda>a. M a + N a) \<in> multiset"
56   by (simp add: multiset_def)
58 lemma diff_preserves_multiset:
59   assumes "M \<in> multiset"
60   shows "(\<lambda>a. M a - N a) \<in> multiset"
61 proof -
62   have "{x. N x < M x} \<subseteq> {x. 0 < M x}"
63     by auto
64   with assms show ?thesis
65     by (auto simp add: multiset_def intro: finite_subset)
66 qed
68 lemma filter_preserves_multiset:
69   assumes "M \<in> multiset"
70   shows "(\<lambda>x. if P x then M x else 0) \<in> multiset"
71 proof -
72   have "{x. (P x \<longrightarrow> 0 < M x) \<and> P x} \<subseteq> {x. 0 < M x}"
73     by auto
74   with assms show ?thesis
75     by (auto simp add: multiset_def intro: finite_subset)
76 qed
78 lemmas in_multiset = const0_in_multiset only1_in_multiset
79   union_preserves_multiset diff_preserves_multiset filter_preserves_multiset
82 subsection \<open>Representing multisets\<close>
84 text \<open>Multiset enumeration\<close>
86 instantiation multiset :: (type) cancel_comm_monoid_add
87 begin
89 lift_definition zero_multiset :: "'a multiset" is "\<lambda>a. 0"
90 by (rule const0_in_multiset)
92 abbreviation Mempty :: "'a multiset" ("{#}") where
93   "Mempty \<equiv> 0"
95 lift_definition plus_multiset :: "'a multiset => 'a multiset => 'a multiset" is "\<lambda>M N. (\<lambda>a. M a + N a)"
96 by (rule union_preserves_multiset)
98 lift_definition minus_multiset :: "'a multiset => 'a multiset => 'a multiset" is "\<lambda> M N. \<lambda>a. M a - N a"
99 by (rule diff_preserves_multiset)
101 instance
102   by default (transfer, simp add: fun_eq_iff)+
104 end
106 lift_definition single :: "'a => 'a multiset" is "\<lambda>a b. if b = a then 1 else 0"
107 by (rule only1_in_multiset)
109 syntax
110   "_multiset" :: "args => 'a multiset"    ("{#(_)#}")
111 translations
112   "{#x, xs#}" == "{#x#} + {#xs#}"
113   "{#x#}" == "CONST single x"
115 lemma count_empty [simp]: "count {#} a = 0"
116   by (simp add: zero_multiset.rep_eq)
118 lemma count_single [simp]: "count {#b#} a = (if b = a then 1 else 0)"
119   by (simp add: single.rep_eq)
122 subsection \<open>Basic operations\<close>
124 subsubsection \<open>Union\<close>
126 lemma count_union [simp]: "count (M + N) a = count M a + count N a"
127   by (simp add: plus_multiset.rep_eq)
130 subsubsection \<open>Difference\<close>
132 instantiation multiset :: (type) comm_monoid_diff
133 begin
135 instance
136 by default (transfer, simp add: fun_eq_iff)+
138 end
140 lemma count_diff [simp]: "count (M - N) a = count M a - count N a"
141   by (simp add: minus_multiset.rep_eq)
143 lemma diff_empty [simp]: "M - {#} = M \<and> {#} - M = {#}"
144   by rule (fact Groups.diff_zero, fact Groups.zero_diff)
146 lemma diff_cancel[simp]: "A - A = {#}"
147   by (fact Groups.diff_cancel)
149 lemma diff_union_cancelR [simp]: "M + N - N = (M::'a multiset)"
150   by (fact add_diff_cancel_right')
152 lemma diff_union_cancelL [simp]: "N + M - N = (M::'a multiset)"
153   by (fact add_diff_cancel_left')
155 lemma diff_right_commute:
156   "(M::'a multiset) - N - Q = M - Q - N"
157   by (fact diff_right_commute)
160   "(M::'a multiset) - (N + Q) = M - N - Q"
161   by (rule sym) (fact diff_diff_add)
163 lemma insert_DiffM:
164   "x \<in># M \<Longrightarrow> {#x#} + (M - {#x#}) = M"
165   by (clarsimp simp: multiset_eq_iff)
167 lemma insert_DiffM2 [simp]:
168   "x \<in># M \<Longrightarrow> M - {#x#} + {#x#} = M"
169   by (clarsimp simp: multiset_eq_iff)
171 lemma diff_union_swap:
172   "a \<noteq> b \<Longrightarrow> M - {#a#} + {#b#} = M + {#b#} - {#a#}"
173   by (auto simp add: multiset_eq_iff)
175 lemma diff_union_single_conv:
176   "a \<in># J \<Longrightarrow> I + J - {#a#} = I + (J - {#a#})"
177   by (simp add: multiset_eq_iff)
180 subsubsection \<open>Equality of multisets\<close>
182 lemma single_not_empty [simp]: "{#a#} \<noteq> {#} \<and> {#} \<noteq> {#a#}"
183   by (simp add: multiset_eq_iff)
185 lemma single_eq_single [simp]: "{#a#} = {#b#} \<longleftrightarrow> a = b"
186   by (auto simp add: multiset_eq_iff)
188 lemma union_eq_empty [iff]: "M + N = {#} \<longleftrightarrow> M = {#} \<and> N = {#}"
189   by (auto simp add: multiset_eq_iff)
191 lemma empty_eq_union [iff]: "{#} = M + N \<longleftrightarrow> M = {#} \<and> N = {#}"
192   by (auto simp add: multiset_eq_iff)
194 lemma multi_self_add_other_not_self [simp]: "M = M + {#x#} \<longleftrightarrow> False"
195   by (auto simp add: multiset_eq_iff)
197 lemma diff_single_trivial:
198   "\<not> x \<in># M \<Longrightarrow> M - {#x#} = M"
199   by (auto simp add: multiset_eq_iff)
201 lemma diff_single_eq_union:
202   "x \<in># M \<Longrightarrow> M - {#x#} = N \<longleftrightarrow> M = N + {#x#}"
203   by auto
205 lemma union_single_eq_diff:
206   "M + {#x#} = N \<Longrightarrow> M = N - {#x#}"
207   by (auto dest: sym)
209 lemma union_single_eq_member:
210   "M + {#x#} = N \<Longrightarrow> x \<in># N"
211   by auto
213 lemma union_is_single:
214   "M + N = {#a#} \<longleftrightarrow> M = {#a#} \<and> N={#} \<or> M = {#} \<and> N = {#a#}" (is "?lhs = ?rhs")
215 proof
216   assume ?rhs then show ?lhs by auto
217 next
218   assume ?lhs then show ?rhs
219     by (simp add: multiset_eq_iff split:if_splits) (metis add_is_1)
220 qed
222 lemma single_is_union:
223   "{#a#} = M + N \<longleftrightarrow> {#a#} = M \<and> N = {#} \<or> M = {#} \<and> {#a#} = N"
224   by (auto simp add: eq_commute [of "{#a#}" "M + N"] union_is_single)
227   "M + {#a#} = N + {#b#} \<longleftrightarrow> M = N \<and> a = b \<or> M = N - {#a#} + {#b#} \<and> N = M - {#b#} + {#a#}"  (is "?lhs = ?rhs")
228 (* shorter: by (simp add: multiset_eq_iff) fastforce *)
229 proof
230   assume ?rhs then show ?lhs
232     (drule sym, simp add: add.assoc [symmetric])
233 next
234   assume ?lhs
235   show ?rhs
236   proof (cases "a = b")
237     case True with \<open>?lhs\<close> show ?thesis by simp
238   next
239     case False
240     from \<open>?lhs\<close> have "a \<in># N + {#b#}" by (rule union_single_eq_member)
241     with False have "a \<in># N" by auto
242     moreover from \<open>?lhs\<close> have "M = N + {#b#} - {#a#}" by (rule union_single_eq_diff)
243     moreover note False
244     ultimately show ?thesis by (auto simp add: diff_right_commute [of _ "{#a#}"] diff_union_swap)
245   qed
246 qed
248 lemma insert_noteq_member:
249   assumes BC: "B + {#b#} = C + {#c#}"
250    and bnotc: "b \<noteq> c"
251   shows "c \<in># B"
252 proof -
253   have "c \<in># C + {#c#}" by simp
254   have nc: "\<not> c \<in># {#b#}" using bnotc by simp
255   then have "c \<in># B + {#b#}" using BC by simp
256   then show "c \<in># B" using nc by simp
257 qed
260   "(M + {#a#} = N + {#b#}) =
261     (M = N \<and> a = b \<or> (\<exists>K. M = K + {#b#} \<and> N = K + {#a#}))"
264 lemma multi_member_split:
265   "x \<in># M \<Longrightarrow> \<exists>A. M = A + {#x#}"
266   by (rule_tac x = "M - {#x#}" in exI, simp)
269   assumes "c \<in># B" and "b \<noteq> c"
270   shows "B - {#c#} + {#b#} = B + {#b#} - {#c#}"
271 proof -
272   from \<open>c \<in># B\<close> obtain A where B: "B = A + {#c#}"
273     by (blast dest: multi_member_split)
274   have "A + {#b#} = A + {#b#} + {#c#} - {#c#}" by simp
275   then have "A + {#b#} = A + {#c#} + {#b#} - {#c#}"
276     by (simp add: ac_simps)
277   then show ?thesis using B by simp
278 qed
281 subsubsection \<open>Pointwise ordering induced by count\<close>
283 definition subseteq_mset :: "'a multiset \<Rightarrow> 'a multiset \<Rightarrow> bool" (infix "<=#" 50) where
284 "subseteq_mset A B = (\<forall>a. count A a \<le> count B a)"
286 definition subset_mset :: "'a multiset \<Rightarrow> 'a multiset \<Rightarrow> bool" (infix "<#" 50) where
287 "subset_mset A B = (A <=# B \<and> A \<noteq> B)"
289 notation subseteq_mset (infix "\<le>#" 50)
290 notation (xsymbols) subseteq_mset (infix "\<subseteq>#" 50)
292 notation (xsymbols) subset_mset (infix "\<subset>#" 50)
294 interpretation subset_mset: ordered_ab_semigroup_add_imp_le "op +" "op -" "op <=#" "op <#"
295   by default (auto simp add: subset_mset_def subseteq_mset_def multiset_eq_iff intro: order_trans antisym)
297 lemma mset_less_eqI:
298   "(\<And>x. count A x \<le> count B x) \<Longrightarrow> A \<le># B"
299   by (simp add: subseteq_mset_def)
301 lemma mset_le_exists_conv:
302   "(A::'a multiset) \<le># B \<longleftrightarrow> (\<exists>C. B = A + C)"
303 apply (unfold subseteq_mset_def, rule iffI, rule_tac x = "B - A" in exI)
304 apply (auto intro: multiset_eq_iff [THEN iffD2])
305 done
307 interpretation subset_mset: ordered_cancel_comm_monoid_diff  "op +" "op -" 0 "op \<le>#" "op <#"
308   by default (simp, fact mset_le_exists_conv)
310 lemma mset_le_mono_add_right_cancel [simp]:
311   "(A::'a multiset) + C \<le># B + C \<longleftrightarrow> A \<le># B"
312   by (fact subset_mset.add_le_cancel_right)
314 lemma mset_le_mono_add_left_cancel [simp]:
315   "C + (A::'a multiset) \<le># C + B \<longleftrightarrow> A \<le># B"
316   by (fact subset_mset.add_le_cancel_left)
319   "(A::'a multiset) \<le># B \<Longrightarrow> C \<le># D \<Longrightarrow> A + C \<le># B + D"
320   by (fact subset_mset.add_mono)
322 lemma mset_le_add_left [simp]:
323   "(A::'a multiset) \<le># A + B"
324   unfolding subseteq_mset_def by auto
326 lemma mset_le_add_right [simp]:
327   "B \<le># (A::'a multiset) + B"
328   unfolding subseteq_mset_def by auto
330 lemma mset_le_single:
331   "a :# B \<Longrightarrow> {#a#} \<le># B"
332   by (simp add: subseteq_mset_def)
334 lemma multiset_diff_union_assoc:
335   "C \<le># B \<Longrightarrow> (A::'a multiset) + B - C = A + (B - C)"
338 lemma mset_le_multiset_union_diff_commute:
339   "B \<le># A \<Longrightarrow> (A::'a multiset) - B + C = A + C - B"
342 lemma diff_le_self[simp]: "(M::'a multiset) - N \<le># M"
343 by(simp add: subseteq_mset_def)
345 lemma mset_lessD: "A <# B \<Longrightarrow> x \<in># A \<Longrightarrow> x \<in># B"
346 apply (clarsimp simp: subset_mset_def subseteq_mset_def)
347 apply (erule_tac x=x in allE)
348 apply auto
349 done
351 lemma mset_leD: "A \<le># B \<Longrightarrow> x \<in># A \<Longrightarrow> x \<in># B"
352 apply (clarsimp simp: subset_mset_def subseteq_mset_def)
353 apply (erule_tac x = x in allE)
354 apply auto
355 done
357 lemma mset_less_insertD: "(A + {#x#} <# B) \<Longrightarrow> (x \<in># B \<and> A <# B)"
358 apply (rule conjI)
359  apply (simp add: mset_lessD)
360 apply (clarsimp simp: subset_mset_def subseteq_mset_def)
361 apply safe
362  apply (erule_tac x = a in allE)
363  apply (auto split: split_if_asm)
364 done
366 lemma mset_le_insertD: "(A + {#x#} \<le># B) \<Longrightarrow> (x \<in># B \<and> A \<le># B)"
367 apply (rule conjI)
368  apply (simp add: mset_leD)
369 apply (force simp: subset_mset_def subseteq_mset_def split: split_if_asm)
370 done
372 lemma mset_less_of_empty[simp]: "A <# {#} \<longleftrightarrow> False"
373   by (auto simp add: subseteq_mset_def subset_mset_def multiset_eq_iff)
375 lemma empty_le[simp]: "{#} \<le># A"
376   unfolding mset_le_exists_conv by auto
378 lemma le_empty[simp]: "(M \<le># {#}) = (M = {#})"
379   unfolding mset_le_exists_conv by auto
381 lemma multi_psub_of_add_self[simp]: "A <# A + {#x#}"
382   by (auto simp: subset_mset_def subseteq_mset_def)
384 lemma multi_psub_self[simp]: "(A::'a multiset) <# A = False"
385   by simp
387 lemma mset_less_add_bothsides: "N + {#x#} <# M + {#x#} \<Longrightarrow> N <# M"
388   by (fact subset_mset.add_less_imp_less_right)
390 lemma mset_less_empty_nonempty:
391   "{#} <# S \<longleftrightarrow> S \<noteq> {#}"
392   by (auto simp: subset_mset_def subseteq_mset_def)
394 lemma mset_less_diff_self:
395   "c \<in># B \<Longrightarrow> B - {#c#} <# B"
396   by (auto simp: subset_mset_def subseteq_mset_def multiset_eq_iff)
399 subsubsection \<open>Intersection\<close>
401 definition inf_subset_mset :: "'a multiset \<Rightarrow> 'a multiset \<Rightarrow> 'a multiset" (infixl "#\<inter>" 70) where
402   multiset_inter_def: "inf_subset_mset A B = A - (A - B)"
404 interpretation subset_mset: semilattice_inf inf_subset_mset "op \<le>#" "op <#"
405 proof -
406    have aux: "\<And>m n q :: nat. m \<le> n \<Longrightarrow> m \<le> q \<Longrightarrow> m \<le> n - (n - q)" by arith
407    show "class.semilattice_inf op #\<inter> op \<le># op <#"
408      by default (auto simp add: multiset_inter_def subseteq_mset_def aux)
409 qed
412 lemma multiset_inter_count [simp]:
413   "count ((A::'a multiset) #\<inter> B) x = min (count A x) (count B x)"
414   by (simp add: multiset_inter_def)
416 lemma multiset_inter_single: "a \<noteq> b \<Longrightarrow> {#a#} #\<inter> {#b#} = {#}"
417   by (rule multiset_eqI) auto
419 lemma multiset_union_diff_commute:
420   assumes "B #\<inter> C = {#}"
421   shows "A + B - C = A - C + B"
422 proof (rule multiset_eqI)
423   fix x
424   from assms have "min (count B x) (count C x) = 0"
425     by (auto simp add: multiset_eq_iff)
426   then have "count B x = 0 \<or> count C x = 0"
427     by auto
428   then show "count (A + B - C) x = count (A - C + B) x"
429     by auto
430 qed
432 lemma empty_inter [simp]:
433   "{#} #\<inter> M = {#}"
434   by (simp add: multiset_eq_iff)
436 lemma inter_empty [simp]:
437   "M #\<inter> {#} = {#}"
438   by (simp add: multiset_eq_iff)
441   "\<not> x \<in># N \<Longrightarrow> (M + {#x#}) #\<inter> N = M #\<inter> N"
442   by (simp add: multiset_eq_iff)
445   "x \<in># N \<Longrightarrow> (M + {#x#}) #\<inter> N = (M #\<inter> (N - {#x#})) + {#x#}"
446   by (simp add: multiset_eq_iff)
449   "\<not> x \<in># N \<Longrightarrow> N #\<inter> (M + {#x#}) = N #\<inter> M"
450   by (simp add: multiset_eq_iff)
453   "x \<in># N \<Longrightarrow> N #\<inter> (M + {#x#}) = ((N - {#x#}) #\<inter> M) + {#x#}"
454   by (simp add: multiset_eq_iff)
457 subsubsection \<open>Bounded union\<close>
458 definition sup_subset_mset :: "'a multiset \<Rightarrow> 'a multiset \<Rightarrow> 'a multiset"(infixl "#\<union>" 70)  where
459   "sup_subset_mset A B = A + (B - A)"
461 interpretation subset_mset: semilattice_sup sup_subset_mset "op \<le>#" "op <#"
462 proof -
463   have aux: "\<And>m n q :: nat. m \<le> n \<Longrightarrow> q \<le> n \<Longrightarrow> m + (q - m) \<le> n" by arith
464   show "class.semilattice_sup op #\<union> op \<le># op <#"
465     by default (auto simp add: sup_subset_mset_def subseteq_mset_def aux)
466 qed
468 lemma sup_subset_mset_count [simp]:
469   "count (A #\<union> B) x = max (count A x) (count B x)"
470   by (simp add: sup_subset_mset_def)
472 lemma empty_sup [simp]:
473   "{#} #\<union> M = M"
474   by (simp add: multiset_eq_iff)
476 lemma sup_empty [simp]:
477   "M #\<union> {#} = M"
478   by (simp add: multiset_eq_iff)
481   "\<not> x \<in># N \<Longrightarrow> (M + {#x#}) #\<union> N = (M #\<union> N) + {#x#}"
482   by (simp add: multiset_eq_iff)
485   "x \<in># N \<Longrightarrow> (M + {#x#}) #\<union> N = (M #\<union> (N - {#x#})) + {#x#}"
486   by (simp add: multiset_eq_iff)
489   "\<not> x \<in># N \<Longrightarrow> N #\<union> (M + {#x#}) = (N #\<union> M) + {#x#}"
490   by (simp add: multiset_eq_iff)
493   "x \<in># N \<Longrightarrow> N #\<union> (M + {#x#}) = ((N - {#x#}) #\<union> M) + {#x#}"
494   by (simp add: multiset_eq_iff)
496 subsubsection \<open>Subset is an order\<close>
497 interpretation subset_mset: order "op \<le>#" "op <#" by unfold_locales auto
499 subsubsection \<open>Filter (with comprehension syntax)\<close>
501 text \<open>Multiset comprehension\<close>
503 lift_definition filter_mset :: "('a \<Rightarrow> bool) \<Rightarrow> 'a multiset \<Rightarrow> 'a multiset"
504 is "\<lambda>P M. \<lambda>x. if P x then M x else 0"
505 by (rule filter_preserves_multiset)
507 lemma count_filter_mset [simp]:
508   "count (filter_mset P M) a = (if P a then count M a else 0)"
509   by (simp add: filter_mset.rep_eq)
511 lemma filter_empty_mset [simp]:
512   "filter_mset P {#} = {#}"
513   by (rule multiset_eqI) simp
515 lemma filter_single_mset [simp]:
516   "filter_mset P {#x#} = (if P x then {#x#} else {#})"
517   by (rule multiset_eqI) simp
519 lemma filter_union_mset [simp]:
520   "filter_mset P (M + N) = filter_mset P M + filter_mset P N"
521   by (rule multiset_eqI) simp
523 lemma filter_diff_mset [simp]:
524   "filter_mset P (M - N) = filter_mset P M - filter_mset P N"
525   by (rule multiset_eqI) simp
527 lemma filter_inter_mset [simp]:
528   "filter_mset P (M #\<inter> N) = filter_mset P M #\<inter> filter_mset P N"
529   by (rule multiset_eqI) simp
531 lemma multiset_filter_subset[simp]: "filter_mset f M \<le># M"
532   by (simp add: mset_less_eqI)
534 lemma multiset_filter_mono: assumes "A \<le># B"
535   shows "filter_mset f A \<le># filter_mset f B"
536 proof -
537   from assms[unfolded mset_le_exists_conv]
538   obtain C where B: "B = A + C" by auto
539   show ?thesis unfolding B by auto
540 qed
542 syntax
543   "_MCollect" :: "pttrn \<Rightarrow> 'a multiset \<Rightarrow> bool \<Rightarrow> 'a multiset"    ("(1{# _ :# _./ _#})")
544 syntax (xsymbol)
545   "_MCollect" :: "pttrn \<Rightarrow> 'a multiset \<Rightarrow> bool \<Rightarrow> 'a multiset"    ("(1{# _ \<in># _./ _#})")
546 translations
547   "{#x \<in># M. P#}" == "CONST filter_mset (\<lambda>x. P) M"
550 subsubsection \<open>Set of elements\<close>
552 definition set_mset :: "'a multiset => 'a set" where
553   "set_mset M = {x. x :# M}"
555 lemma set_mset_empty [simp]: "set_mset {#} = {}"
556 by (simp add: set_mset_def)
558 lemma set_mset_single [simp]: "set_mset {#b#} = {b}"
559 by (simp add: set_mset_def)
561 lemma set_mset_union [simp]: "set_mset (M + N) = set_mset M \<union> set_mset N"
562 by (auto simp add: set_mset_def)
564 lemma set_mset_eq_empty_iff [simp]: "(set_mset M = {}) = (M = {#})"
565 by (auto simp add: set_mset_def multiset_eq_iff)
567 lemma mem_set_mset_iff [simp]: "(x \<in> set_mset M) = (x :# M)"
568 by (auto simp add: set_mset_def)
570 lemma set_mset_filter [simp]: "set_mset {# x:#M. P x #} = set_mset M \<inter> {x. P x}"
571 by (auto simp add: set_mset_def)
573 lemma finite_set_mset [iff]: "finite (set_mset M)"
574   using count [of M] by (simp add: multiset_def set_mset_def)
576 lemma finite_Collect_mem [iff]: "finite {x. x :# M}"
577   unfolding set_mset_def[symmetric] by simp
579 lemma set_mset_mono: "A \<le># B \<Longrightarrow> set_mset A \<subseteq> set_mset B"
580   by (metis mset_leD subsetI mem_set_mset_iff)
582 lemma ball_set_mset_iff: "(\<forall>x \<in> set_mset M. P x) \<longleftrightarrow> (\<forall>x. x \<in># M \<longrightarrow> P x)"
583   by auto
586 subsubsection \<open>Size\<close>
588 definition wcount where "wcount f M = (\<lambda>x. count M x * Suc (f x))"
590 lemma wcount_union: "wcount f (M + N) a = wcount f M a + wcount f N a"
591   by (auto simp: wcount_def add_mult_distrib)
593 definition size_multiset :: "('a \<Rightarrow> nat) \<Rightarrow> 'a multiset \<Rightarrow> nat" where
594   "size_multiset f M = setsum (wcount f M) (set_mset M)"
596 lemmas size_multiset_eq = size_multiset_def[unfolded wcount_def]
598 instantiation multiset :: (type) size begin
599 definition size_multiset where
600   size_multiset_overloaded_def: "size_multiset = Multiset.size_multiset (\<lambda>_. 0)"
601 instance ..
602 end
604 lemmas size_multiset_overloaded_eq =
605   size_multiset_overloaded_def[THEN fun_cong, unfolded size_multiset_eq, simplified]
607 lemma size_multiset_empty [simp]: "size_multiset f {#} = 0"
608 by (simp add: size_multiset_def)
610 lemma size_empty [simp]: "size {#} = 0"
613 lemma size_multiset_single [simp]: "size_multiset f {#b#} = Suc (f b)"
614 by (simp add: size_multiset_eq)
616 lemma size_single [simp]: "size {#b#} = 1"
619 lemma setsum_wcount_Int:
620   "finite A \<Longrightarrow> setsum (wcount f N) (A \<inter> set_mset N) = setsum (wcount f N) A"
621 apply (induct rule: finite_induct)
622  apply simp
623 apply (simp add: Int_insert_left set_mset_def wcount_def)
624 done
626 lemma size_multiset_union [simp]:
627   "size_multiset f (M + N::'a multiset) = size_multiset f M + size_multiset f N"
628 apply (simp add: size_multiset_def setsum_Un_nat setsum.distrib setsum_wcount_Int wcount_union)
629 apply (subst Int_commute)
630 apply (simp add: setsum_wcount_Int)
631 done
633 lemma size_union [simp]: "size (M + N::'a multiset) = size M + size N"
636 lemma size_multiset_eq_0_iff_empty [iff]: "(size_multiset f M = 0) = (M = {#})"
637 by (auto simp add: size_multiset_eq multiset_eq_iff)
639 lemma size_eq_0_iff_empty [iff]: "(size M = 0) = (M = {#})"
642 lemma nonempty_has_size: "(S \<noteq> {#}) = (0 < size S)"
643 by (metis gr0I gr_implies_not0 size_empty size_eq_0_iff_empty)
645 lemma size_eq_Suc_imp_elem: "size M = Suc n ==> \<exists>a. a :# M"
646 apply (unfold size_multiset_overloaded_eq)
647 apply (drule setsum_SucD)
648 apply auto
649 done
651 lemma size_eq_Suc_imp_eq_union:
652   assumes "size M = Suc n"
653   shows "\<exists>a N. M = N + {#a#}"
654 proof -
655   from assms obtain a where "a \<in># M"
656     by (erule size_eq_Suc_imp_elem [THEN exE])
657   then have "M = M - {#a#} + {#a#}" by simp
658   then show ?thesis by blast
659 qed
661 lemma size_mset_mono: assumes "A \<le># B"
662   shows "size A \<le> size(B::_ multiset)"
663 proof -
664   from assms[unfolded mset_le_exists_conv]
665   obtain C where B: "B = A + C" by auto
666   show ?thesis unfolding B by (induct C, auto)
667 qed
669 lemma size_filter_mset_lesseq[simp]: "size (filter_mset f M) \<le> size M"
670 by (rule size_mset_mono[OF multiset_filter_subset])
672 lemma size_Diff_submset:
673   "M \<le># M' \<Longrightarrow> size (M' - M) = size M' - size(M::'a multiset)"
674 by (metis add_diff_cancel_left' size_union mset_le_exists_conv)
676 subsection \<open>Induction and case splits\<close>
678 theorem multiset_induct [case_names empty add, induct type: multiset]:
679   assumes empty: "P {#}"
680   assumes add: "\<And>M x. P M \<Longrightarrow> P (M + {#x#})"
681   shows "P M"
682 proof (induct n \<equiv> "size M" arbitrary: M)
683   case 0 thus "P M" by (simp add: empty)
684 next
685   case (Suc k)
686   obtain N x where "M = N + {#x#}"
687     using \<open>Suc k = size M\<close> [symmetric]
688     using size_eq_Suc_imp_eq_union by fast
689   with Suc add show "P M" by simp
690 qed
692 lemma multi_nonempty_split: "M \<noteq> {#} \<Longrightarrow> \<exists>A a. M = A + {#a#}"
693 by (induct M) auto
695 lemma multiset_cases [cases type]:
696   obtains (empty) "M = {#}"
697     | (add) N x where "M = N + {#x#}"
698   using assms by (induct M) simp_all
700 lemma multi_drop_mem_not_eq: "c \<in># B \<Longrightarrow> B - {#c#} \<noteq> B"
701 by (cases "B = {#}") (auto dest: multi_member_split)
703 lemma multiset_partition: "M = {# x:#M. P x #} + {# x:#M. \<not> P x #}"
704 apply (subst multiset_eq_iff)
705 apply auto
706 done
708 lemma mset_less_size: "(A::'a multiset) <# B \<Longrightarrow> size A < size B"
709 proof (induct A arbitrary: B)
710   case (empty M)
711   then have "M \<noteq> {#}" by (simp add: mset_less_empty_nonempty)
712   then obtain M' x where "M = M' + {#x#}"
713     by (blast dest: multi_nonempty_split)
714   then show ?case by simp
715 next
716   case (add S x T)
717   have IH: "\<And>B. S <# B \<Longrightarrow> size S < size B" by fact
718   have SxsubT: "S + {#x#} <# T" by fact
719   then have "x \<in># T" and "S <# T" by (auto dest: mset_less_insertD)
720   then obtain T' where T: "T = T' + {#x#}"
721     by (blast dest: multi_member_split)
722   then have "S <# T'" using SxsubT
723     by (blast intro: mset_less_add_bothsides)
724   then have "size S < size T'" using IH by simp
725   then show ?case using T by simp
726 qed
729 lemma size_1_singleton_mset: "size M = 1 \<Longrightarrow> \<exists>a. M = {#a#}"
730 by (cases M) auto
732 subsubsection \<open>Strong induction and subset induction for multisets\<close>
734 text \<open>Well-foundedness of strict subset relation\<close>
736 lemma wf_less_mset_rel: "wf {(M, N :: 'a multiset). M <# N}"
737 apply (rule wf_measure [THEN wf_subset, where f1=size])
738 apply (clarsimp simp: measure_def inv_image_def mset_less_size)
739 done
741 lemma full_multiset_induct [case_names less]:
742 assumes ih: "\<And>B. \<forall>(A::'a multiset). A <# B \<longrightarrow> P A \<Longrightarrow> P B"
743 shows "P B"
744 apply (rule wf_less_mset_rel [THEN wf_induct])
745 apply (rule ih, auto)
746 done
748 lemma multi_subset_induct [consumes 2, case_names empty add]:
749 assumes "F \<le># A"
750   and empty: "P {#}"
751   and insert: "\<And>a F. a \<in># A \<Longrightarrow> P F \<Longrightarrow> P (F + {#a#})"
752 shows "P F"
753 proof -
754   from \<open>F \<le># A\<close>
755   show ?thesis
756   proof (induct F)
757     show "P {#}" by fact
758   next
759     fix x F
760     assume P: "F \<le># A \<Longrightarrow> P F" and i: "F + {#x#} \<le># A"
761     show "P (F + {#x#})"
762     proof (rule insert)
763       from i show "x \<in># A" by (auto dest: mset_le_insertD)
764       from i have "F \<le># A" by (auto dest: mset_le_insertD)
765       with P show "P F" .
766     qed
767   qed
768 qed
771 subsection \<open>The fold combinator\<close>
773 definition fold_mset :: "('a \<Rightarrow> 'b \<Rightarrow> 'b) \<Rightarrow> 'b \<Rightarrow> 'a multiset \<Rightarrow> 'b"
774 where
775   "fold_mset f s M = Finite_Set.fold (\<lambda>x. f x ^^ count M x) s (set_mset M)"
777 lemma fold_mset_empty [simp]:
778   "fold_mset f s {#} = s"
779   by (simp add: fold_mset_def)
781 context comp_fun_commute
782 begin
784 lemma fold_mset_insert:
785   "fold_mset f s (M + {#x#}) = f x (fold_mset f s M)"
786 proof -
787   interpret mset: comp_fun_commute "\<lambda>y. f y ^^ count M y"
788     by (fact comp_fun_commute_funpow)
789   interpret mset_union: comp_fun_commute "\<lambda>y. f y ^^ count (M + {#x#}) y"
790     by (fact comp_fun_commute_funpow)
791   show ?thesis
792   proof (cases "x \<in> set_mset M")
793     case False
794     then have *: "count (M + {#x#}) x = 1" by simp
795     from False have "Finite_Set.fold (\<lambda>y. f y ^^ count (M + {#x#}) y) s (set_mset M) =
796       Finite_Set.fold (\<lambda>y. f y ^^ count M y) s (set_mset M)"
797       by (auto intro!: Finite_Set.fold_cong comp_fun_commute_funpow)
798     with False * show ?thesis
799       by (simp add: fold_mset_def del: count_union)
800   next
801     case True
802     def N \<equiv> "set_mset M - {x}"
803     from N_def True have *: "set_mset M = insert x N" "x \<notin> N" "finite N" by auto
804     then have "Finite_Set.fold (\<lambda>y. f y ^^ count (M + {#x#}) y) s N =
805       Finite_Set.fold (\<lambda>y. f y ^^ count M y) s N"
806       by (auto intro!: Finite_Set.fold_cong comp_fun_commute_funpow)
807     with * show ?thesis by (simp add: fold_mset_def del: count_union) simp
808   qed
809 qed
811 corollary fold_mset_single [simp]:
812   "fold_mset f s {#x#} = f x s"
813 proof -
814   have "fold_mset f s ({#} + {#x#}) = f x s" by (simp only: fold_mset_insert) simp
815   then show ?thesis by simp
816 qed
818 lemma fold_mset_fun_left_comm:
819   "f x (fold_mset f s M) = fold_mset f (f x s) M"
820   by (induct M) (simp_all add: fold_mset_insert fun_left_comm)
822 lemma fold_mset_union [simp]:
823   "fold_mset f s (M + N) = fold_mset f (fold_mset f s M) N"
824 proof (induct M)
825   case empty then show ?case by simp
826 next
827   case (add M x)
828   have "M + {#x#} + N = (M + N) + {#x#}"
829     by (simp add: ac_simps)
830   with add show ?case by (simp add: fold_mset_insert fold_mset_fun_left_comm)
831 qed
833 lemma fold_mset_fusion:
834   assumes "comp_fun_commute g"
835   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")
836 proof -
837   interpret comp_fun_commute g by (fact assms)
838   show "PROP ?P" by (induct A) auto
839 qed
841 end
843 text \<open>
844   A note on code generation: When defining some function containing a
845   subterm @{term "fold_mset F"}, code generation is not automatic. When
846   interpreting locale @{text left_commutative} with @{text F}, the
847   would be code thms for @{const fold_mset} become thms like
848   @{term "fold_mset F z {#} = z"} where @{text F} is not a pattern but
849   contains defined symbols, i.e.\ is not a code thm. Hence a separate
850   constant with its own code thms needs to be introduced for @{text
851   F}. See the image operator below.
852 \<close>
855 subsection \<open>Image\<close>
857 definition image_mset :: "('a \<Rightarrow> 'b) \<Rightarrow> 'a multiset \<Rightarrow> 'b multiset" where
858   "image_mset f = fold_mset (plus o single o f) {#}"
860 lemma comp_fun_commute_mset_image:
861   "comp_fun_commute (plus o single o f)"
862 proof
863 qed (simp add: ac_simps fun_eq_iff)
865 lemma image_mset_empty [simp]: "image_mset f {#} = {#}"
866   by (simp add: image_mset_def)
868 lemma image_mset_single [simp]: "image_mset f {#x#} = {#f x#}"
869 proof -
870   interpret comp_fun_commute "plus o single o f"
871     by (fact comp_fun_commute_mset_image)
872   show ?thesis by (simp add: image_mset_def)
873 qed
875 lemma image_mset_union [simp]:
876   "image_mset f (M + N) = image_mset f M + image_mset f N"
877 proof -
878   interpret comp_fun_commute "plus o single o f"
879     by (fact comp_fun_commute_mset_image)
880   show ?thesis by (induct N) (simp_all add: image_mset_def ac_simps)
881 qed
883 corollary image_mset_insert:
884   "image_mset f (M + {#a#}) = image_mset f M + {#f a#}"
885   by simp
887 lemma set_image_mset [simp]:
888   "set_mset (image_mset f M) = image f (set_mset M)"
889   by (induct M) simp_all
891 lemma size_image_mset [simp]:
892   "size (image_mset f M) = size M"
893   by (induct M) simp_all
895 lemma image_mset_is_empty_iff [simp]:
896   "image_mset f M = {#} \<longleftrightarrow> M = {#}"
897   by (cases M) auto
899 syntax
900   "_comprehension1_mset" :: "'a \<Rightarrow> 'b \<Rightarrow> 'b multiset \<Rightarrow> 'a multiset"
901       ("({#_/. _ :# _#})")
902 translations
903   "{#e. x:#M#}" == "CONST image_mset (%x. e) M"
905 syntax (xsymbols)
906   "_comprehension2_mset" :: "'a \<Rightarrow> 'b \<Rightarrow> 'b multiset \<Rightarrow> 'a multiset"
907       ("({#_/. _ \<in># _#})")
908 translations
909   "{#e. x \<in># M#}" == "CONST image_mset (\<lambda>x. e) M"
911 syntax
912   "_comprehension3_mset" :: "'a \<Rightarrow> 'b \<Rightarrow> 'b multiset \<Rightarrow> bool \<Rightarrow> 'a multiset"
913       ("({#_/ | _ :# _./ _#})")
914 translations
915   "{#e | x:#M. P#}" => "{#e. x :# {# x:#M. P#}#}"
917 syntax
918   "_comprehension4_mset" :: "'a \<Rightarrow> 'b \<Rightarrow> 'b multiset \<Rightarrow> bool \<Rightarrow> 'a multiset"
919       ("({#_/ | _ \<in># _./ _#})")
920 translations
921   "{#e | x\<in>#M. P#}" => "{#e. x \<in># {# x\<in>#M. P#}#}"
923 text \<open>
924   This allows to write not just filters like @{term "{#x:#M. x<c#}"}
925   but also images like @{term "{#x+x. x:#M #}"} and @{term [source]
926   "{#x+x|x:#M. x<c#}"}, where the latter is currently displayed as
927   @{term "{#x+x|x:#M. x<c#}"}.
928 \<close>
930 lemma in_image_mset: "y \<in># {#f x. x \<in># M#} \<longleftrightarrow> y \<in> f ` set_mset M"
931 by (metis mem_set_mset_iff set_image_mset)
933 functor image_mset: image_mset
934 proof -
935   fix f g show "image_mset f \<circ> image_mset g = image_mset (f \<circ> g)"
936   proof
937     fix A
938     show "(image_mset f \<circ> image_mset g) A = image_mset (f \<circ> g) A"
939       by (induct A) simp_all
940   qed
941   show "image_mset id = id"
942   proof
943     fix A
944     show "image_mset id A = id A"
945       by (induct A) simp_all
946   qed
947 qed
949 declare
950   image_mset.id [simp]
951   image_mset.identity [simp]
953 lemma image_mset_id[simp]: "image_mset id x = x"
954   unfolding id_def by auto
956 lemma image_mset_cong: "(\<And>x. x \<in># M \<Longrightarrow> f x = g x) \<Longrightarrow> {#f x. x \<in># M#} = {#g x. x \<in># M#}"
957   by (induct M) auto
959 lemma image_mset_cong_pair:
960   "(\<forall>x y. (x, y) \<in># M \<longrightarrow> f x y = g x y) \<Longrightarrow> {#f x y. (x, y) \<in># M#} = {#g x y. (x, y) \<in># M#}"
961   by (metis image_mset_cong split_cong)
964 subsection \<open>Further conversions\<close>
966 primrec multiset_of :: "'a list \<Rightarrow> 'a multiset" where
967   "multiset_of [] = {#}" |
968   "multiset_of (a # x) = multiset_of x + {# a #}"
970 lemma in_multiset_in_set:
971   "x \<in># multiset_of xs \<longleftrightarrow> x \<in> set xs"
972   by (induct xs) simp_all
974 lemma count_multiset_of:
975   "count (multiset_of xs) x = length (filter (\<lambda>y. x = y) xs)"
976   by (induct xs) simp_all
978 lemma multiset_of_zero_iff[simp]: "(multiset_of x = {#}) = (x = [])"
979   by (induct x) auto
981 lemma multiset_of_zero_iff_right[simp]: "({#} = multiset_of x) = (x = [])"
982 by (induct x) auto
984 lemma set_mset_multiset_of[simp]: "set_mset (multiset_of x) = set x"
985 by (induct x) auto
987 lemma mem_set_multiset_eq: "x \<in> set xs = (x :# multiset_of xs)"
988 by (induct xs) auto
990 lemma size_multiset_of [simp]: "size (multiset_of xs) = length xs"
991   by (induct xs) simp_all
993 lemma multiset_of_append [simp]:
994   "multiset_of (xs @ ys) = multiset_of xs + multiset_of ys"
995   by (induct xs arbitrary: ys) (auto simp: ac_simps)
997 lemma multiset_of_filter:
998   "multiset_of (filter P xs) = {#x :# multiset_of xs. P x #}"
999   by (induct xs) simp_all
1001 lemma multiset_of_rev [simp]:
1002   "multiset_of (rev xs) = multiset_of xs"
1003   by (induct xs) simp_all
1005 lemma surj_multiset_of: "surj multiset_of"
1006 apply (unfold surj_def)
1007 apply (rule allI)
1008 apply (rule_tac M = y in multiset_induct)
1009  apply auto
1010 apply (rule_tac x = "x # xa" in exI)
1011 apply auto
1012 done
1014 lemma set_count_greater_0: "set x = {a. count (multiset_of x) a > 0}"
1015 by (induct x) auto
1017 lemma distinct_count_atmost_1:
1018   "distinct x = (! a. count (multiset_of x) a = (if a \<in> set x then 1 else 0))"
1019 apply (induct x, simp, rule iffI, simp_all)
1020 apply (rename_tac a b)
1021 apply (rule conjI)
1022 apply (simp_all add: set_mset_multiset_of [THEN sym] del: set_mset_multiset_of)
1023 apply (erule_tac x = a in allE, simp, clarify)
1024 apply (erule_tac x = aa in allE, simp)
1025 done
1027 lemma multiset_of_eq_setD:
1028   "multiset_of xs = multiset_of ys \<Longrightarrow> set xs = set ys"
1029 by (rule) (auto simp add:multiset_eq_iff set_count_greater_0)
1031 lemma set_eq_iff_multiset_of_eq_distinct:
1032   "distinct x \<Longrightarrow> distinct y \<Longrightarrow>
1033     (set x = set y) = (multiset_of x = multiset_of y)"
1034 by (auto simp: multiset_eq_iff distinct_count_atmost_1)
1036 lemma set_eq_iff_multiset_of_remdups_eq:
1037    "(set x = set y) = (multiset_of (remdups x) = multiset_of (remdups y))"
1038 apply (rule iffI)
1039 apply (simp add: set_eq_iff_multiset_of_eq_distinct[THEN iffD1])
1040 apply (drule distinct_remdups [THEN distinct_remdups
1041       [THEN set_eq_iff_multiset_of_eq_distinct [THEN iffD2]]])
1042 apply simp
1043 done
1045 lemma multiset_of_compl_union [simp]:
1046   "multiset_of [x\<leftarrow>xs. P x] + multiset_of [x\<leftarrow>xs. \<not>P x] = multiset_of xs"
1047   by (induct xs) (auto simp: ac_simps)
1049 lemma nth_mem_multiset_of: "i < length ls \<Longrightarrow> (ls ! i) :# multiset_of ls"
1050 apply (induct ls arbitrary: i)
1051  apply simp
1052 apply (case_tac i)
1053  apply auto
1054 done
1056 lemma multiset_of_remove1[simp]:
1057   "multiset_of (remove1 a xs) = multiset_of xs - {#a#}"
1058 by (induct xs) (auto simp add: multiset_eq_iff)
1060 lemma multiset_of_eq_length:
1061   assumes "multiset_of xs = multiset_of ys"
1062   shows "length xs = length ys"
1063   using assms by (metis size_multiset_of)
1065 lemma multiset_of_eq_length_filter:
1066   assumes "multiset_of xs = multiset_of ys"
1067   shows "length (filter (\<lambda>x. z = x) xs) = length (filter (\<lambda>y. z = y) ys)"
1068   using assms by (metis count_multiset_of)
1070 lemma fold_multiset_equiv:
1071   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"
1072     and equiv: "multiset_of xs = multiset_of ys"
1073   shows "List.fold f xs = List.fold f ys"
1074 using f equiv [symmetric]
1075 proof (induct xs arbitrary: ys)
1076   case Nil then show ?case by simp
1077 next
1078   case (Cons x xs)
1079   then have *: "set ys = set (x # xs)" by (blast dest: multiset_of_eq_setD)
1080   have "\<And>x y. x \<in> set ys \<Longrightarrow> y \<in> set ys \<Longrightarrow> f x \<circ> f y = f y \<circ> f x"
1081     by (rule Cons.prems(1)) (simp_all add: *)
1082   moreover from * have "x \<in> set ys" by simp
1083   ultimately have "List.fold f ys = List.fold f (remove1 x ys) \<circ> f x" by (fact fold_remove1_split)
1084   moreover from Cons.prems have "List.fold f xs = List.fold f (remove1 x ys)" by (auto intro: Cons.hyps)
1085   ultimately show ?case by simp
1086 qed
1088 lemma multiset_of_insort [simp]:
1089   "multiset_of (insort x xs) = multiset_of xs + {#x#}"
1090   by (induct xs) (simp_all add: ac_simps)
1092 lemma multiset_of_map:
1093   "multiset_of (map f xs) = image_mset f (multiset_of xs)"
1094   by (induct xs) simp_all
1096 definition multiset_of_set :: "'a set \<Rightarrow> 'a multiset"
1097 where
1098   "multiset_of_set = folding.F (\<lambda>x M. {#x#} + M) {#}"
1100 interpretation multiset_of_set!: folding "\<lambda>x M. {#x#} + M" "{#}"
1101 where
1102   "folding.F (\<lambda>x M. {#x#} + M) {#} = multiset_of_set"
1103 proof -
1104   interpret comp_fun_commute "\<lambda>x M. {#x#} + M" by default (simp add: fun_eq_iff ac_simps)
1105   show "folding (\<lambda>x M. {#x#} + M)" by default (fact comp_fun_commute)
1106   from multiset_of_set_def show "folding.F (\<lambda>x M. {#x#} + M) {#} = multiset_of_set" ..
1107 qed
1109 lemma count_multiset_of_set [simp]:
1110   "finite A \<Longrightarrow> x \<in> A \<Longrightarrow> count (multiset_of_set A) x = 1" (is "PROP ?P")
1111   "\<not> finite A \<Longrightarrow> count (multiset_of_set A) x = 0" (is "PROP ?Q")
1112   "x \<notin> A \<Longrightarrow> count (multiset_of_set A) x = 0" (is "PROP ?R")
1113 proof -
1114   { fix A
1115     assume "x \<notin> A"
1116     have "count (multiset_of_set A) x = 0"
1117     proof (cases "finite A")
1118       case False then show ?thesis by simp
1119     next
1120       case True from True \<open>x \<notin> A\<close> show ?thesis by (induct A) auto
1121     qed
1122   } note * = this
1123   then show "PROP ?P" "PROP ?Q" "PROP ?R"
1124   by (auto elim!: Set.set_insert)
1125 qed -- \<open>TODO: maybe define @{const multiset_of_set} also in terms of @{const Abs_multiset}\<close>
1127 lemma elem_multiset_of_set[simp, intro]: "finite A \<Longrightarrow> x \<in># multiset_of_set A \<longleftrightarrow> x \<in> A"
1128   by (induct A rule: finite_induct) simp_all
1130 context linorder
1131 begin
1133 definition sorted_list_of_multiset :: "'a multiset \<Rightarrow> 'a list"
1134 where
1135   "sorted_list_of_multiset M = fold_mset insort [] M"
1137 lemma sorted_list_of_multiset_empty [simp]:
1138   "sorted_list_of_multiset {#} = []"
1139   by (simp add: sorted_list_of_multiset_def)
1141 lemma sorted_list_of_multiset_singleton [simp]:
1142   "sorted_list_of_multiset {#x#} = [x]"
1143 proof -
1144   interpret comp_fun_commute insort by (fact comp_fun_commute_insort)
1145   show ?thesis by (simp add: sorted_list_of_multiset_def)
1146 qed
1148 lemma sorted_list_of_multiset_insert [simp]:
1149   "sorted_list_of_multiset (M + {#x#}) = List.insort x (sorted_list_of_multiset M)"
1150 proof -
1151   interpret comp_fun_commute insort by (fact comp_fun_commute_insort)
1152   show ?thesis by (simp add: sorted_list_of_multiset_def)
1153 qed
1155 end
1157 lemma multiset_of_sorted_list_of_multiset [simp]:
1158   "multiset_of (sorted_list_of_multiset M) = M"
1159   by (induct M) simp_all
1161 lemma sorted_list_of_multiset_multiset_of [simp]:
1162   "sorted_list_of_multiset (multiset_of xs) = sort xs"
1163   by (induct xs) simp_all
1165 lemma finite_set_mset_multiset_of_set:
1166   assumes "finite A"
1167   shows "set_mset (multiset_of_set A) = A"
1168   using assms by (induct A) simp_all
1170 lemma infinite_set_mset_multiset_of_set:
1171   assumes "\<not> finite A"
1172   shows "set_mset (multiset_of_set A) = {}"
1173   using assms by simp
1175 lemma set_sorted_list_of_multiset [simp]:
1176   "set (sorted_list_of_multiset M) = set_mset M"
1177   by (induct M) (simp_all add: set_insort)
1179 lemma sorted_list_of_multiset_of_set [simp]:
1180   "sorted_list_of_multiset (multiset_of_set A) = sorted_list_of_set A"
1181   by (cases "finite A") (induct A rule: finite_induct, simp_all add: ac_simps)
1184 subsection \<open>Big operators\<close>
1186 no_notation times (infixl "*" 70)
1187 no_notation Groups.one ("1")
1189 locale comm_monoid_mset = comm_monoid
1190 begin
1192 definition F :: "'a multiset \<Rightarrow> 'a"
1193 where
1194   eq_fold: "F M = fold_mset f 1 M"
1196 lemma empty [simp]:
1197   "F {#} = 1"
1198   by (simp add: eq_fold)
1200 lemma singleton [simp]:
1201   "F {#x#} = x"
1202 proof -
1203   interpret comp_fun_commute
1204     by default (simp add: fun_eq_iff left_commute)
1205   show ?thesis by (simp add: eq_fold)
1206 qed
1208 lemma union [simp]:
1209   "F (M + N) = F M * F N"
1210 proof -
1211   interpret comp_fun_commute f
1212     by default (simp add: fun_eq_iff left_commute)
1213   show ?thesis by (induct N) (simp_all add: left_commute eq_fold)
1214 qed
1216 end
1218 lemma comp_fun_commute_plus_mset[simp]: "comp_fun_commute (op + \<Colon> 'a multiset \<Rightarrow> _ \<Rightarrow> _)"
1219   by default (simp add: add_ac comp_def)
1221 declare comp_fun_commute.fold_mset_insert[OF comp_fun_commute_plus_mset, simp]
1223 lemma in_mset_fold_plus_iff[iff]: "x \<in># fold_mset (op +) M NN \<longleftrightarrow> x \<in># M \<or> (\<exists>N. N \<in># NN \<and> x \<in># N)"
1224   by (induct NN) auto
1226 notation times (infixl "*" 70)
1227 notation Groups.one ("1")
1230 begin
1232 definition msetsum :: "'a multiset \<Rightarrow> 'a"
1233 where
1234   "msetsum = comm_monoid_mset.F plus 0"
1236 sublocale msetsum!: comm_monoid_mset plus 0
1237 where
1238   "comm_monoid_mset.F plus 0 = msetsum"
1239 proof -
1240   show "comm_monoid_mset plus 0" ..
1241   from msetsum_def show "comm_monoid_mset.F plus 0 = msetsum" ..
1242 qed
1244 lemma setsum_unfold_msetsum:
1245   "setsum f A = msetsum (image_mset f (multiset_of_set A))"
1246   by (cases "finite A") (induct A rule: finite_induct, simp_all)
1248 end
1250 lemma msetsum_diff:
1251   fixes M N :: "('a \<Colon> ordered_cancel_comm_monoid_diff) multiset"
1252   shows "N \<le># M \<Longrightarrow> msetsum (M - N) = msetsum M - msetsum N"
1255 lemma size_eq_msetsum: "size M = msetsum (image_mset (\<lambda>_. 1) M)"
1256 proof (induct M)
1257   case empty then show ?case by simp
1258 next
1259   case (add M x) then show ?case
1260     by (cases "x \<in> set_mset M")
1261       (simp_all del: mem_set_mset_iff add: size_multiset_overloaded_eq setsum.distrib setsum.delta' insert_absorb, simp)
1262 qed
1265 abbreviation Union_mset :: "'a multiset multiset \<Rightarrow> 'a multiset" where
1266   "Union_mset MM \<equiv> msetsum MM"
1268 notation (xsymbols) Union_mset ("\<Union>#_"  900)
1270 lemma set_mset_Union_mset[simp]: "set_mset (\<Union># MM) = (\<Union>M \<in> set_mset MM. set_mset M)"
1271   by (induct MM) auto
1273 lemma in_Union_mset_iff[iff]: "x \<in># \<Union># MM \<longleftrightarrow> (\<exists>M. M \<in># MM \<and> x \<in># M)"
1274   by (induct MM) auto
1276 syntax
1277   "_msetsum_image" :: "pttrn \<Rightarrow> 'b set \<Rightarrow> 'a \<Rightarrow> 'a::comm_monoid_add"
1278       ("(3SUM _:#_. _)" [0, 51, 10] 10)
1280 syntax (xsymbols)
1281   "_msetsum_image" :: "pttrn \<Rightarrow> 'b set \<Rightarrow> 'a \<Rightarrow> 'a::comm_monoid_add"
1282       ("(3\<Sum>_\<in>#_. _)" [0, 51, 10] 10)
1284 syntax (HTML output)
1285   "_msetsum_image" :: "pttrn \<Rightarrow> 'b set \<Rightarrow> 'a \<Rightarrow> 'a::comm_monoid_add"
1286       ("(3\<Sum>_\<in>#_. _)" [0, 51, 10] 10)
1288 translations
1289   "SUM i :# A. b" == "CONST msetsum (CONST image_mset (\<lambda>i. b) A)"
1291 context comm_monoid_mult
1292 begin
1294 definition msetprod :: "'a multiset \<Rightarrow> 'a"
1295 where
1296   "msetprod = comm_monoid_mset.F times 1"
1298 sublocale msetprod!: comm_monoid_mset times 1
1299 where
1300   "comm_monoid_mset.F times 1 = msetprod"
1301 proof -
1302   show "comm_monoid_mset times 1" ..
1303   from msetprod_def show "comm_monoid_mset.F times 1 = msetprod" ..
1304 qed
1306 lemma msetprod_empty:
1307   "msetprod {#} = 1"
1308   by (fact msetprod.empty)
1310 lemma msetprod_singleton:
1311   "msetprod {#x#} = x"
1312   by (fact msetprod.singleton)
1314 lemma msetprod_Un:
1315   "msetprod (A + B) = msetprod A * msetprod B"
1316   by (fact msetprod.union)
1318 lemma setprod_unfold_msetprod:
1319   "setprod f A = msetprod (image_mset f (multiset_of_set A))"
1320   by (cases "finite A") (induct A rule: finite_induct, simp_all)
1322 lemma msetprod_multiplicity:
1323   "msetprod M = setprod (\<lambda>x. x ^ count M x) (set_mset M)"
1324   by (simp add: fold_mset_def setprod.eq_fold msetprod.eq_fold funpow_times_power comp_def)
1326 end
1328 syntax
1329   "_msetprod_image" :: "pttrn \<Rightarrow> 'b set \<Rightarrow> 'a \<Rightarrow> 'a::comm_monoid_mult"
1330       ("(3PROD _:#_. _)" [0, 51, 10] 10)
1332 syntax (xsymbols)
1333   "_msetprod_image" :: "pttrn \<Rightarrow> 'b set \<Rightarrow> 'a \<Rightarrow> 'a::comm_monoid_mult"
1334       ("(3\<Prod>_\<in>#_. _)" [0, 51, 10] 10)
1336 syntax (HTML output)
1337   "_msetprod_image" :: "pttrn \<Rightarrow> 'b set \<Rightarrow> 'a \<Rightarrow> 'a::comm_monoid_mult"
1338       ("(3\<Prod>_\<in>#_. _)" [0, 51, 10] 10)
1340 translations
1341   "PROD i :# A. b" == "CONST msetprod (CONST image_mset (\<lambda>i. b) A)"
1343 lemma (in comm_semiring_1) dvd_msetprod:
1344   assumes "x \<in># A"
1345   shows "x dvd msetprod A"
1346 proof -
1347   from assms have "A = (A - {#x#}) + {#x#}" by simp
1348   then obtain B where "A = B + {#x#}" ..
1349   then show ?thesis by simp
1350 qed
1353 subsection \<open>Replicate operation\<close>
1355 definition replicate_mset :: "nat \<Rightarrow> 'a \<Rightarrow> 'a multiset" where
1356   "replicate_mset n x = ((op + {#x#}) ^^ n) {#}"
1358 lemma replicate_mset_0[simp]: "replicate_mset 0 x = {#}"
1359   unfolding replicate_mset_def by simp
1361 lemma replicate_mset_Suc[simp]: "replicate_mset (Suc n) x = replicate_mset n x + {#x#}"
1362   unfolding replicate_mset_def by (induct n) (auto intro: add.commute)
1364 lemma in_replicate_mset[simp]: "x \<in># replicate_mset n y \<longleftrightarrow> n > 0 \<and> x = y"
1365   unfolding replicate_mset_def by (induct n) simp_all
1367 lemma count_replicate_mset[simp]: "count (replicate_mset n x) y = (if y = x then n else 0)"
1368   unfolding replicate_mset_def by (induct n) simp_all
1370 lemma set_mset_replicate_mset_subset[simp]: "set_mset (replicate_mset n x) = (if n = 0 then {} else {x})"
1371   by (auto split: if_splits)
1373 lemma size_replicate_mset[simp]: "size (replicate_mset n M) = n"
1374   by (induct n, simp_all)
1376 lemma count_le_replicate_mset_le: "n \<le> count M x \<longleftrightarrow> replicate_mset n x \<le># M"
1377   by (auto simp add: assms mset_less_eqI) (metis count_replicate_mset subseteq_mset_def)
1380 lemma filter_eq_replicate_mset: "{#y \<in># D. y = x#} = replicate_mset (count D x) x"
1381   by (induct D) simp_all
1384 subsection \<open>Alternative representations\<close>
1386 subsubsection \<open>Lists\<close>
1388 context linorder
1389 begin
1391 lemma multiset_of_insort [simp]:
1392   "multiset_of (insort_key k x xs) = {#x#} + multiset_of xs"
1393   by (induct xs) (simp_all add: ac_simps)
1395 lemma multiset_of_sort [simp]:
1396   "multiset_of (sort_key k xs) = multiset_of xs"
1397   by (induct xs) (simp_all add: ac_simps)
1399 text \<open>
1400   This lemma shows which properties suffice to show that a function
1401   @{text "f"} with @{text "f xs = ys"} behaves like sort.
1402 \<close>
1404 lemma properties_for_sort_key:
1405   assumes "multiset_of ys = multiset_of xs"
1406   and "\<And>k. k \<in> set ys \<Longrightarrow> filter (\<lambda>x. f k = f x) ys = filter (\<lambda>x. f k = f x) xs"
1407   and "sorted (map f ys)"
1408   shows "sort_key f xs = ys"
1409 using assms
1410 proof (induct xs arbitrary: ys)
1411   case Nil then show ?case by simp
1412 next
1413   case (Cons x xs)
1414   from Cons.prems(2) have
1415     "\<forall>k \<in> set ys. filter (\<lambda>x. f k = f x) (remove1 x ys) = filter (\<lambda>x. f k = f x) xs"
1416     by (simp add: filter_remove1)
1417   with Cons.prems have "sort_key f xs = remove1 x ys"
1418     by (auto intro!: Cons.hyps simp add: sorted_map_remove1)
1419   moreover from Cons.prems have "x \<in> set ys"
1420     by (auto simp add: mem_set_multiset_eq intro!: ccontr)
1421   ultimately show ?case using Cons.prems by (simp add: insort_key_remove1)
1422 qed
1424 lemma properties_for_sort:
1425   assumes multiset: "multiset_of ys = multiset_of xs"
1426   and "sorted ys"
1427   shows "sort xs = ys"
1428 proof (rule properties_for_sort_key)
1429   from multiset show "multiset_of ys = multiset_of xs" .
1430   from \<open>sorted ys\<close> show "sorted (map (\<lambda>x. x) ys)" by simp
1431   from multiset have "\<And>k. length (filter (\<lambda>y. k = y) ys) = length (filter (\<lambda>x. k = x) xs)"
1432     by (rule multiset_of_eq_length_filter)
1433   then have "\<And>k. replicate (length (filter (\<lambda>y. k = y) ys)) k = replicate (length (filter (\<lambda>x. k = x) xs)) k"
1434     by simp
1435   then show "\<And>k. k \<in> set ys \<Longrightarrow> filter (\<lambda>y. k = y) ys = filter (\<lambda>x. k = x) xs"
1436     by (simp add: replicate_length_filter)
1437 qed
1439 lemma sort_key_by_quicksort:
1440   "sort_key f xs = sort_key f [x\<leftarrow>xs. f x < f (xs ! (length xs div 2))]
1441     @ [x\<leftarrow>xs. f x = f (xs ! (length xs div 2))]
1442     @ sort_key f [x\<leftarrow>xs. f x > f (xs ! (length xs div 2))]" (is "sort_key f ?lhs = ?rhs")
1443 proof (rule properties_for_sort_key)
1444   show "multiset_of ?rhs = multiset_of ?lhs"
1445     by (rule multiset_eqI) (auto simp add: multiset_of_filter)
1446 next
1447   show "sorted (map f ?rhs)"
1448     by (auto simp add: sorted_append intro: sorted_map_same)
1449 next
1450   fix l
1451   assume "l \<in> set ?rhs"
1452   let ?pivot = "f (xs ! (length xs div 2))"
1453   have *: "\<And>x. f l = f x \<longleftrightarrow> f x = f l" by auto
1454   have "[x \<leftarrow> sort_key f xs . f x = f l] = [x \<leftarrow> xs. f x = f l]"
1455     unfolding filter_sort by (rule properties_for_sort_key) (auto intro: sorted_map_same)
1456   with * have **: "[x \<leftarrow> sort_key f xs . f l = f x] = [x \<leftarrow> xs. f l = f x]" by simp
1457   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
1458   then have "\<And>P. [x \<leftarrow> sort_key f xs . P (f x) ?pivot \<and> f l = f x] =
1459     [x \<leftarrow> sort_key f xs. P (f l) ?pivot \<and> f l = f x]" by simp
1460   note *** = this [of "op <"] this [of "op >"] this [of "op ="]
1461   show "[x \<leftarrow> ?rhs. f l = f x] = [x \<leftarrow> ?lhs. f l = f x]"
1462   proof (cases "f l" ?pivot rule: linorder_cases)
1463     case less
1464     then have "f l \<noteq> ?pivot" and "\<not> f l > ?pivot" by auto
1465     with less show ?thesis
1466       by (simp add: filter_sort [symmetric] ** ***)
1467   next
1468     case equal then show ?thesis
1469       by (simp add: * less_le)
1470   next
1471     case greater
1472     then have "f l \<noteq> ?pivot" and "\<not> f l < ?pivot" by auto
1473     with greater show ?thesis
1474       by (simp add: filter_sort [symmetric] ** ***)
1475   qed
1476 qed
1478 lemma sort_by_quicksort:
1479   "sort xs = sort [x\<leftarrow>xs. x < xs ! (length xs div 2)]
1480     @ [x\<leftarrow>xs. x = xs ! (length xs div 2)]
1481     @ sort [x\<leftarrow>xs. x > xs ! (length xs div 2)]" (is "sort ?lhs = ?rhs")
1482   using sort_key_by_quicksort [of "\<lambda>x. x", symmetric] by simp
1484 text \<open>A stable parametrized quicksort\<close>
1486 definition part :: "('b \<Rightarrow> 'a) \<Rightarrow> 'a \<Rightarrow> 'b list \<Rightarrow> 'b list \<times> 'b list \<times> 'b list" where
1487   "part f pivot xs = ([x \<leftarrow> xs. f x < pivot], [x \<leftarrow> xs. f x = pivot], [x \<leftarrow> xs. pivot < f x])"
1489 lemma part_code [code]:
1490   "part f pivot [] = ([], [], [])"
1491   "part f pivot (x # xs) = (let (lts, eqs, gts) = part f pivot xs; x' = f x in
1492      if x' < pivot then (x # lts, eqs, gts)
1493      else if x' > pivot then (lts, eqs, x # gts)
1494      else (lts, x # eqs, gts))"
1495   by (auto simp add: part_def Let_def split_def)
1497 lemma sort_key_by_quicksort_code [code]:
1498   "sort_key f xs = (case xs of [] \<Rightarrow> []
1499     | [x] \<Rightarrow> xs
1500     | [x, y] \<Rightarrow> (if f x \<le> f y then xs else [y, x])
1501     | _ \<Rightarrow> (let (lts, eqs, gts) = part f (f (xs ! (length xs div 2))) xs
1502        in sort_key f lts @ eqs @ sort_key f gts))"
1503 proof (cases xs)
1504   case Nil then show ?thesis by simp
1505 next
1506   case (Cons _ ys) note hyps = Cons show ?thesis
1507   proof (cases ys)
1508     case Nil with hyps show ?thesis by simp
1509   next
1510     case (Cons _ zs) note hyps = hyps Cons show ?thesis
1511     proof (cases zs)
1512       case Nil with hyps show ?thesis by auto
1513     next
1514       case Cons
1515       from sort_key_by_quicksort [of f xs]
1516       have "sort_key f xs = (let (lts, eqs, gts) = part f (f (xs ! (length xs div 2))) xs
1517         in sort_key f lts @ eqs @ sort_key f gts)"
1518       by (simp only: split_def Let_def part_def fst_conv snd_conv)
1519       with hyps Cons show ?thesis by (simp only: list.cases)
1520     qed
1521   qed
1522 qed
1524 end
1526 hide_const (open) part
1528 lemma multiset_of_remdups_le: "multiset_of (remdups xs) \<le># multiset_of xs"
1529   by (induct xs) (auto intro: subset_mset.order_trans)
1531 lemma multiset_of_update:
1532   "i < length ls \<Longrightarrow> multiset_of (ls[i := v]) = multiset_of ls - {#ls ! i#} + {#v#}"
1533 proof (induct ls arbitrary: i)
1534   case Nil then show ?case by simp
1535 next
1536   case (Cons x xs)
1537   show ?case
1538   proof (cases i)
1539     case 0 then show ?thesis by simp
1540   next
1541     case (Suc i')
1542     with Cons show ?thesis
1543       apply simp
1544       apply (subst add.assoc)
1545       apply (subst add.commute [of "{#v#}" "{#x#}"])
1546       apply (subst add.assoc [symmetric])
1547       apply simp
1548       apply (rule mset_le_multiset_union_diff_commute)
1549       apply (simp add: mset_le_single nth_mem_multiset_of)
1550       done
1551   qed
1552 qed
1554 lemma multiset_of_swap:
1555   "i < length ls \<Longrightarrow> j < length ls \<Longrightarrow>
1556     multiset_of (ls[j := ls ! i, i := ls ! j]) = multiset_of ls"
1557   by (cases "i = j") (simp_all add: multiset_of_update nth_mem_multiset_of)
1560 subsection \<open>The multiset order\<close>
1562 subsubsection \<open>Well-foundedness\<close>
1564 definition mult1 :: "('a \<times> 'a) set => ('a multiset \<times> 'a multiset) set" where
1565   "mult1 r = {(N, M). \<exists>a M0 K. M = M0 + {#a#} \<and> N = M0 + K \<and>
1566       (\<forall>b. b :# K --> (b, a) \<in> r)}"
1568 definition mult :: "('a \<times> 'a) set => ('a multiset \<times> 'a multiset) set" where
1569   "mult r = (mult1 r)\<^sup>+"
1571 lemma not_less_empty [iff]: "(M, {#}) \<notin> mult1 r"
1572 by (simp add: mult1_def)
1574 lemma less_add: "(N, M0 + {#a#}) \<in> mult1 r ==>
1575     (\<exists>M. (M, M0) \<in> mult1 r \<and> N = M + {#a#}) \<or>
1576     (\<exists>K. (\<forall>b. b :# K --> (b, a) \<in> r) \<and> N = M0 + K)"
1577   (is "_ \<Longrightarrow> ?case1 (mult1 r) \<or> ?case2")
1578 proof (unfold mult1_def)
1579   let ?r = "\<lambda>K a. \<forall>b. b :# K --> (b, a) \<in> r"
1580   let ?R = "\<lambda>N M. \<exists>a M0 K. M = M0 + {#a#} \<and> N = M0 + K \<and> ?r K a"
1581   let ?case1 = "?case1 {(N, M). ?R N M}"
1583   assume "(N, M0 + {#a#}) \<in> {(N, M). ?R N M}"
1584   then have "\<exists>a' M0' K.
1585       M0 + {#a#} = M0' + {#a'#} \<and> N = M0' + K \<and> ?r K a'" by simp
1586   then show "?case1 \<or> ?case2"
1587   proof (elim exE conjE)
1588     fix a' M0' K
1589     assume N: "N = M0' + K" and r: "?r K a'"
1590     assume "M0 + {#a#} = M0' + {#a'#}"
1591     then have "M0 = M0' \<and> a = a' \<or>
1592         (\<exists>K'. M0 = K' + {#a'#} \<and> M0' = K' + {#a#})"
1593       by (simp only: add_eq_conv_ex)
1594     then show ?thesis
1595     proof (elim disjE conjE exE)
1596       assume "M0 = M0'" "a = a'"
1597       with N r have "?r K a \<and> N = M0 + K" by simp
1598       then have ?case2 .. then show ?thesis ..
1599     next
1600       fix K'
1601       assume "M0' = K' + {#a#}"
1602       with N have n: "N = K' + K + {#a#}" by (simp add: ac_simps)
1604       assume "M0 = K' + {#a'#}"
1605       with r have "?R (K' + K) M0" by blast
1606       with n have ?case1 by simp then show ?thesis ..
1607     qed
1608   qed
1609 qed
1611 lemma all_accessible: "wf r ==> \<forall>M. M \<in> Wellfounded.acc (mult1 r)"
1612 proof
1613   let ?R = "mult1 r"
1614   let ?W = "Wellfounded.acc ?R"
1615   {
1616     fix M M0 a
1617     assume M0: "M0 \<in> ?W"
1618       and wf_hyp: "!!b. (b, a) \<in> r ==> (\<forall>M \<in> ?W. M + {#b#} \<in> ?W)"
1619       and acc_hyp: "\<forall>M. (M, M0) \<in> ?R --> M + {#a#} \<in> ?W"
1620     have "M0 + {#a#} \<in> ?W"
1621     proof (rule accI [of "M0 + {#a#}"])
1622       fix N
1623       assume "(N, M0 + {#a#}) \<in> ?R"
1624       then have "((\<exists>M. (M, M0) \<in> ?R \<and> N = M + {#a#}) \<or>
1625           (\<exists>K. (\<forall>b. b :# K --> (b, a) \<in> r) \<and> N = M0 + K))"
1626         by (rule less_add)
1627       then show "N \<in> ?W"
1628       proof (elim exE disjE conjE)
1629         fix M assume "(M, M0) \<in> ?R" and N: "N = M + {#a#}"
1630         from acc_hyp have "(M, M0) \<in> ?R --> M + {#a#} \<in> ?W" ..
1631         from this and \<open>(M, M0) \<in> ?R\<close> have "M + {#a#} \<in> ?W" ..
1632         then show "N \<in> ?W" by (simp only: N)
1633       next
1634         fix K
1635         assume N: "N = M0 + K"
1636         assume "\<forall>b. b :# K --> (b, a) \<in> r"
1637         then have "M0 + K \<in> ?W"
1638         proof (induct K)
1639           case empty
1640           from M0 show "M0 + {#} \<in> ?W" by simp
1641         next
1642           case (add K x)
1643           from add.prems have "(x, a) \<in> r" by simp
1644           with wf_hyp have "\<forall>M \<in> ?W. M + {#x#} \<in> ?W" by blast
1645           moreover from add have "M0 + K \<in> ?W" by simp
1646           ultimately have "(M0 + K) + {#x#} \<in> ?W" ..
1647           then show "M0 + (K + {#x#}) \<in> ?W" by (simp only: add.assoc)
1648         qed
1649         then show "N \<in> ?W" by (simp only: N)
1650       qed
1651     qed
1652   } note tedious_reasoning = this
1654   assume wf: "wf r"
1655   fix M
1656   show "M \<in> ?W"
1657   proof (induct M)
1658     show "{#} \<in> ?W"
1659     proof (rule accI)
1660       fix b assume "(b, {#}) \<in> ?R"
1661       with not_less_empty show "b \<in> ?W" by contradiction
1662     qed
1664     fix M a assume "M \<in> ?W"
1665     from wf have "\<forall>M \<in> ?W. M + {#a#} \<in> ?W"
1666     proof induct
1667       fix a
1668       assume r: "!!b. (b, a) \<in> r ==> (\<forall>M \<in> ?W. M + {#b#} \<in> ?W)"
1669       show "\<forall>M \<in> ?W. M + {#a#} \<in> ?W"
1670       proof
1671         fix M assume "M \<in> ?W"
1672         then show "M + {#a#} \<in> ?W"
1673           by (rule acc_induct) (rule tedious_reasoning [OF _ r])
1674       qed
1675     qed
1676     from this and \<open>M \<in> ?W\<close> show "M + {#a#} \<in> ?W" ..
1677   qed
1678 qed
1680 theorem wf_mult1: "wf r ==> wf (mult1 r)"
1681 by (rule acc_wfI) (rule all_accessible)
1683 theorem wf_mult: "wf r ==> wf (mult r)"
1684 unfolding mult_def by (rule wf_trancl) (rule wf_mult1)
1687 subsubsection \<open>Closure-free presentation\<close>
1689 text \<open>One direction.\<close>
1691 lemma mult_implies_one_step:
1692   "trans r ==> (M, N) \<in> mult r ==>
1693     \<exists>I J K. N = I + J \<and> M = I + K \<and> J \<noteq> {#} \<and>
1694     (\<forall>k \<in> set_mset K. \<exists>j \<in> set_mset J. (k, j) \<in> r)"
1695 apply (unfold mult_def mult1_def set_mset_def)
1696 apply (erule converse_trancl_induct, clarify)
1697  apply (rule_tac x = M0 in exI, simp, clarify)
1698 apply (case_tac "a :# K")
1699  apply (rule_tac x = I in exI)
1700  apply (simp (no_asm))
1701  apply (rule_tac x = "(K - {#a#}) + Ka" in exI)
1702  apply (simp (no_asm_simp) add: add.assoc [symmetric])
1703  apply (drule_tac f = "\<lambda>M. M - {#a#}" and x="S + T" for S T in arg_cong)
1704  apply (simp add: diff_union_single_conv)
1705  apply (simp (no_asm_use) add: trans_def)
1706  apply blast
1707 apply (subgoal_tac "a :# I")
1708  apply (rule_tac x = "I - {#a#}" in exI)
1709  apply (rule_tac x = "J + {#a#}" in exI)
1710  apply (rule_tac x = "K + Ka" in exI)
1711  apply (rule conjI)
1712   apply (simp add: multiset_eq_iff split: nat_diff_split)
1713  apply (rule conjI)
1714   apply (drule_tac f = "\<lambda>M. M - {#a#}" and x="S + T" for S T in arg_cong, simp)
1715   apply (simp add: multiset_eq_iff split: nat_diff_split)
1716  apply (simp (no_asm_use) add: trans_def)
1717  apply blast
1718 apply (subgoal_tac "a :# (M0 + {#a#})")
1719  apply simp
1720 apply (simp (no_asm))
1721 done
1723 lemma one_step_implies_mult_aux:
1724   "trans r ==>
1725     \<forall>I J K. (size J = n \<and> J \<noteq> {#} \<and> (\<forall>k \<in> set_mset K. \<exists>j \<in> set_mset J. (k, j) \<in> r))
1726       --> (I + K, I + J) \<in> mult r"
1727 apply (induct_tac n, auto)
1728 apply (frule size_eq_Suc_imp_eq_union, clarify)
1729 apply (rename_tac "J'", simp)
1730 apply (erule notE, auto)
1731 apply (case_tac "J' = {#}")
1732  apply (simp add: mult_def)
1733  apply (rule r_into_trancl)
1734  apply (simp add: mult1_def set_mset_def, blast)
1735 txt \<open>Now we know @{term "J' \<noteq> {#}"}.\<close>
1736 apply (cut_tac M = K and P = "\<lambda>x. (x, a) \<in> r" in multiset_partition)
1737 apply (erule_tac P = "\<forall>k \<in> set_mset K. P k" for P in rev_mp)
1738 apply (erule ssubst)
1739 apply (simp add: Ball_def, auto)
1740 apply (subgoal_tac
1741   "((I + {# x :# K. (x, a) \<in> r #}) + {# x :# K. (x, a) \<notin> r #},
1742     (I + {# x :# K. (x, a) \<in> r #}) + J') \<in> mult r")
1743  prefer 2
1744  apply force
1745 apply (simp (no_asm_use) add: add.assoc [symmetric] mult_def)
1746 apply (erule trancl_trans)
1747 apply (rule r_into_trancl)
1748 apply (simp add: mult1_def set_mset_def)
1749 apply (rule_tac x = a in exI)
1750 apply (rule_tac x = "I + J'" in exI)
1751 apply (simp add: ac_simps)
1752 done
1754 lemma one_step_implies_mult:
1755   "trans r ==> J \<noteq> {#} ==> \<forall>k \<in> set_mset K. \<exists>j \<in> set_mset J. (k, j) \<in> r
1756     ==> (I + K, I + J) \<in> mult r"
1757 using one_step_implies_mult_aux by blast
1760 subsubsection \<open>Partial-order properties\<close>
1762 definition less_multiset :: "'a\<Colon>order multiset \<Rightarrow> 'a multiset \<Rightarrow> bool" (infix "#<#" 50) where
1763   "M' #<# M \<longleftrightarrow> (M', M) \<in> mult {(x', x). x' < x}"
1765 definition le_multiset :: "'a\<Colon>order multiset \<Rightarrow> 'a multiset \<Rightarrow> bool" (infix "#<=#" 50) where
1766   "M' #<=# M \<longleftrightarrow> M' #<# M \<or> M' = M"
1768 notation (xsymbols) less_multiset (infix "#\<subset>#" 50)
1769 notation (xsymbols) le_multiset (infix "#\<subseteq>#" 50)
1771 interpretation multiset_order: order le_multiset less_multiset
1772 proof -
1773   have irrefl: "\<And>M :: 'a multiset. \<not> M #\<subset># M"
1774   proof
1775     fix M :: "'a multiset"
1776     assume "M #\<subset># M"
1777     then have MM: "(M, M) \<in> mult {(x, y). x < y}" by (simp add: less_multiset_def)
1778     have "trans {(x'::'a, x). x' < x}"
1779       by (rule transI) simp
1780     moreover note MM
1781     ultimately have "\<exists>I J K. M = I + J \<and> M = I + K
1782       \<and> J \<noteq> {#} \<and> (\<forall>k\<in>set_mset K. \<exists>j\<in>set_mset J. (k, j) \<in> {(x, y). x < y})"
1783       by (rule mult_implies_one_step)
1784     then obtain I J K where "M = I + J" and "M = I + K"
1785       and "J \<noteq> {#}" and "(\<forall>k\<in>set_mset K. \<exists>j\<in>set_mset J. (k, j) \<in> {(x, y). x < y})" by blast
1786     then have aux1: "K \<noteq> {#}" and aux2: "\<forall>k\<in>set_mset K. \<exists>j\<in>set_mset K. k < j" by auto
1787     have "finite (set_mset K)" by simp
1788     moreover note aux2
1789     ultimately have "set_mset K = {}"
1790       by (induct rule: finite_induct) (auto intro: order_less_trans)
1791     with aux1 show False by simp
1792   qed
1793   have trans: "\<And>K M N :: 'a multiset. K #\<subset># M \<Longrightarrow> M #\<subset># N \<Longrightarrow> K #\<subset># N"
1794     unfolding less_multiset_def mult_def by (blast intro: trancl_trans)
1795   show "class.order (le_multiset :: 'a multiset \<Rightarrow> _) less_multiset"
1796     by default (auto simp add: le_multiset_def irrefl dest: trans)
1797 qed
1799 lemma mult_less_irrefl [elim!]: "M #\<subset># (M::'a::order multiset) ==> R"
1800   by simp
1803 subsubsection \<open>Monotonicity of multiset union\<close>
1805 lemma mult1_union: "(B, D) \<in> mult1 r ==> (C + B, C + D) \<in> mult1 r"
1806 apply (unfold mult1_def)
1807 apply auto
1808 apply (rule_tac x = a in exI)
1809 apply (rule_tac x = "C + M0" in exI)
1811 done
1813 lemma union_less_mono2: "B #\<subset># D ==> C + B #\<subset># C + (D::'a::order multiset)"
1814 apply (unfold less_multiset_def mult_def)
1815 apply (erule trancl_induct)
1816  apply (blast intro: mult1_union)
1817 apply (blast intro: mult1_union trancl_trans)
1818 done
1820 lemma union_less_mono1: "B #\<subset># D ==> B + C #\<subset># D + (C::'a::order multiset)"
1821 apply (subst add.commute [of B C])
1822 apply (subst add.commute [of D C])
1823 apply (erule union_less_mono2)
1824 done
1826 lemma union_less_mono:
1827   "A #\<subset># C ==> B #\<subset># D ==> A + B #\<subset># C + (D::'a::order multiset)"
1828   by (blast intro!: union_less_mono1 union_less_mono2 multiset_order.less_trans)
1830 interpretation multiset_order: ordered_ab_semigroup_add plus le_multiset less_multiset
1831 proof
1832 qed (auto simp add: le_multiset_def intro: union_less_mono2)
1835 subsubsection \<open>Termination proofs with multiset orders\<close>
1837 lemma multi_member_skip: "x \<in># XS \<Longrightarrow> x \<in># {# y #} + XS"
1838   and multi_member_this: "x \<in># {# x #} + XS"
1839   and multi_member_last: "x \<in># {# x #}"
1840   by auto
1842 definition "ms_strict = mult pair_less"
1843 definition "ms_weak = ms_strict \<union> Id"
1845 lemma ms_reduction_pair: "reduction_pair (ms_strict, ms_weak)"
1846 unfolding reduction_pair_def ms_strict_def ms_weak_def pair_less_def
1847 by (auto intro: wf_mult1 wf_trancl simp: mult_def)
1849 lemma smsI:
1850   "(set_mset A, set_mset B) \<in> max_strict \<Longrightarrow> (Z + A, Z + B) \<in> ms_strict"
1851   unfolding ms_strict_def
1852 by (rule one_step_implies_mult) (auto simp add: max_strict_def pair_less_def elim!:max_ext.cases)
1854 lemma wmsI:
1855   "(set_mset A, set_mset B) \<in> max_strict \<or> A = {#} \<and> B = {#}
1856   \<Longrightarrow> (Z + A, Z + B) \<in> ms_weak"
1857 unfolding ms_weak_def ms_strict_def
1858 by (auto simp add: pair_less_def max_strict_def elim!:max_ext.cases intro: one_step_implies_mult)
1860 inductive pw_leq
1861 where
1862   pw_leq_empty: "pw_leq {#} {#}"
1863 | pw_leq_step:  "\<lbrakk>(x,y) \<in> pair_leq; pw_leq X Y \<rbrakk> \<Longrightarrow> pw_leq ({#x#} + X) ({#y#} + Y)"
1865 lemma pw_leq_lstep:
1866   "(x, y) \<in> pair_leq \<Longrightarrow> pw_leq {#x#} {#y#}"
1867 by (drule pw_leq_step) (rule pw_leq_empty, simp)
1869 lemma pw_leq_split:
1870   assumes "pw_leq X Y"
1871   shows "\<exists>A B Z. X = A + Z \<and> Y = B + Z \<and> ((set_mset A, set_mset B) \<in> max_strict \<or> (B = {#} \<and> A = {#}))"
1872   using assms
1873 proof (induct)
1874   case pw_leq_empty thus ?case by auto
1875 next
1876   case (pw_leq_step x y X Y)
1877   then obtain A B Z where
1878     [simp]: "X = A + Z" "Y = B + Z"
1879       and 1[simp]: "(set_mset A, set_mset B) \<in> max_strict \<or> (B = {#} \<and> A = {#})"
1880     by auto
1881   from pw_leq_step have "x = y \<or> (x, y) \<in> pair_less"
1882     unfolding pair_leq_def by auto
1883   thus ?case
1884   proof
1885     assume [simp]: "x = y"
1886     have
1887       "{#x#} + X = A + ({#y#}+Z)
1888       \<and> {#y#} + Y = B + ({#y#}+Z)
1889       \<and> ((set_mset A, set_mset B) \<in> max_strict \<or> (B = {#} \<and> A = {#}))"
1890       by (auto simp: ac_simps)
1891     thus ?case by (intro exI)
1892   next
1893     assume A: "(x, y) \<in> pair_less"
1894     let ?A' = "{#x#} + A" and ?B' = "{#y#} + B"
1895     have "{#x#} + X = ?A' + Z"
1896       "{#y#} + Y = ?B' + Z"
1897       by (auto simp add: ac_simps)
1898     moreover have
1899       "(set_mset ?A', set_mset ?B') \<in> max_strict"
1900       using 1 A unfolding max_strict_def
1901       by (auto elim!: max_ext.cases)
1902     ultimately show ?thesis by blast
1903   qed
1904 qed
1906 lemma
1907   assumes pwleq: "pw_leq Z Z'"
1908   shows ms_strictI: "(set_mset A, set_mset B) \<in> max_strict \<Longrightarrow> (Z + A, Z' + B) \<in> ms_strict"
1909   and   ms_weakI1:  "(set_mset A, set_mset B) \<in> max_strict \<Longrightarrow> (Z + A, Z' + B) \<in> ms_weak"
1910   and   ms_weakI2:  "(Z + {#}, Z' + {#}) \<in> ms_weak"
1911 proof -
1912   from pw_leq_split[OF pwleq]
1913   obtain A' B' Z''
1914     where [simp]: "Z = A' + Z''" "Z' = B' + Z''"
1915     and mx_or_empty: "(set_mset A', set_mset B') \<in> max_strict \<or> (A' = {#} \<and> B' = {#})"
1916     by blast
1917   {
1918     assume max: "(set_mset A, set_mset B) \<in> max_strict"
1919     from mx_or_empty
1920     have "(Z'' + (A + A'), Z'' + (B + B')) \<in> ms_strict"
1921     proof
1922       assume max': "(set_mset A', set_mset B') \<in> max_strict"
1923       with max have "(set_mset (A + A'), set_mset (B + B')) \<in> max_strict"
1924         by (auto simp: max_strict_def intro: max_ext_additive)
1925       thus ?thesis by (rule smsI)
1926     next
1927       assume [simp]: "A' = {#} \<and> B' = {#}"
1928       show ?thesis by (rule smsI) (auto intro: max)
1929     qed
1930     thus "(Z + A, Z' + B) \<in> ms_strict" by (simp add:ac_simps)
1931     thus "(Z + A, Z' + B) \<in> ms_weak" by (simp add: ms_weak_def)
1932   }
1933   from mx_or_empty
1934   have "(Z'' + A', Z'' + B') \<in> ms_weak" by (rule wmsI)
1935   thus "(Z + {#}, Z' + {#}) \<in> ms_weak" by (simp add:ac_simps)
1936 qed
1938 lemma empty_neutral: "{#} + x = x" "x + {#} = x"
1939 and nonempty_plus: "{# x #} + rs \<noteq> {#}"
1940 and nonempty_single: "{# x #} \<noteq> {#}"
1941 by auto
1943 setup \<open>
1944 let
1945   fun msetT T = Type (@{type_name multiset}, [T]);
1947   fun mk_mset T [] = Const (@{const_abbrev Mempty}, msetT T)
1948     | mk_mset T [x] = Const (@{const_name single}, T --> msetT T) \$ x
1949     | mk_mset T (x :: xs) =
1950           Const (@{const_name plus}, msetT T --> msetT T --> msetT T) \$
1951                 mk_mset T [x] \$ mk_mset T xs
1953   fun mset_member_tac m i =
1954       (if m <= 0 then
1955            rtac @{thm multi_member_this} i ORELSE rtac @{thm multi_member_last} i
1956        else
1957            rtac @{thm multi_member_skip} i THEN mset_member_tac (m - 1) i)
1959   val mset_nonempty_tac =
1960       rtac @{thm nonempty_plus} ORELSE' rtac @{thm nonempty_single}
1962   fun regroup_munion_conv ctxt =
1963     Function_Lib.regroup_conv ctxt @{const_abbrev Mempty} @{const_name plus}
1964       (map (fn t => t RS eq_reflection) (@{thms ac_simps} @ @{thms empty_neutral}))
1966   fun unfold_pwleq_tac i =
1967     (rtac @{thm pw_leq_step} i THEN (fn st => unfold_pwleq_tac (i + 1) st))
1968       ORELSE (rtac @{thm pw_leq_lstep} i)
1969       ORELSE (rtac @{thm pw_leq_empty} i)
1971   val set_mset_simps = [@{thm set_mset_empty}, @{thm set_mset_single}, @{thm set_mset_union},
1972                       @{thm Un_insert_left}, @{thm Un_empty_left}]
1973 in
1974   ScnpReconstruct.multiset_setup (ScnpReconstruct.Multiset
1975   {
1976     msetT=msetT, mk_mset=mk_mset, mset_regroup_conv=regroup_munion_conv,
1977     mset_member_tac=mset_member_tac, mset_nonempty_tac=mset_nonempty_tac,
1978     mset_pwleq_tac=unfold_pwleq_tac, set_of_simps=set_mset_simps,
1979     smsI'= @{thm ms_strictI}, wmsI2''= @{thm ms_weakI2}, wmsI1= @{thm ms_weakI1},
1980     reduction_pair= @{thm ms_reduction_pair}
1981   })
1982 end
1983 \<close>
1986 subsection \<open>Legacy theorem bindings\<close>
1988 lemmas multi_count_eq = multiset_eq_iff [symmetric]
1990 lemma union_commute: "M + N = N + (M::'a multiset)"
1991   by (fact add.commute)
1993 lemma union_assoc: "(M + N) + K = M + (N + (K::'a multiset))"
1994   by (fact add.assoc)
1996 lemma union_lcomm: "M + (N + K) = N + (M + (K::'a multiset))"
1997   by (fact add.left_commute)
1999 lemmas union_ac = union_assoc union_commute union_lcomm
2001 lemma union_right_cancel: "M + K = N + K \<longleftrightarrow> M = (N::'a multiset)"
2002   by (fact add_right_cancel)
2004 lemma union_left_cancel: "K + M = K + N \<longleftrightarrow> M = (N::'a multiset)"
2005   by (fact add_left_cancel)
2007 lemma multi_union_self_other_eq: "(A::'a multiset) + X = A + Y \<Longrightarrow> X = Y"
2008   by (fact add_left_imp_eq)
2010 lemma mset_less_trans: "(M::'a multiset) <# K \<Longrightarrow> K <# N \<Longrightarrow> M <# N"
2011   by (fact subset_mset.less_trans)
2013 lemma multiset_inter_commute: "A #\<inter> B = B #\<inter> A"
2014   by (fact subset_mset.inf.commute)
2016 lemma multiset_inter_assoc: "A #\<inter> (B #\<inter> C) = A #\<inter> B #\<inter> C"
2017   by (fact subset_mset.inf.assoc [symmetric])
2019 lemma multiset_inter_left_commute: "A #\<inter> (B #\<inter> C) = B #\<inter> (A #\<inter> C)"
2020   by (fact subset_mset.inf.left_commute)
2022 lemmas multiset_inter_ac =
2023   multiset_inter_commute
2024   multiset_inter_assoc
2025   multiset_inter_left_commute
2027 lemma mult_less_not_refl:
2028   "\<not> M #\<subset># (M::'a::order multiset)"
2029   by (fact multiset_order.less_irrefl)
2031 lemma mult_less_trans:
2032   "K #\<subset># M ==> M #\<subset># N ==> K #\<subset># (N::'a::order multiset)"
2033   by (fact multiset_order.less_trans)
2035 lemma mult_less_not_sym:
2036   "M #\<subset># N ==> \<not> N #\<subset># (M::'a::order multiset)"
2037   by (fact multiset_order.less_not_sym)
2039 lemma mult_less_asym:
2040   "M #\<subset># N ==> (\<not> P ==> N #\<subset># (M::'a::order multiset)) ==> P"
2041   by (fact multiset_order.less_asym)
2043 ML \<open>
2044 fun multiset_postproc _ maybe_name all_values (T as Type (_, [elem_T]))
2045                       (Const _ \$ t') =
2046     let
2047       val (maybe_opt, ps) =
2048         Nitpick_Model.dest_plain_fun t' ||> op ~~
2049         ||> map (apsnd (snd o HOLogic.dest_number))
2050       fun elems_for t =
2051         case AList.lookup (op =) ps t of
2052           SOME n => replicate n t
2053         | NONE => [Const (maybe_name, elem_T --> elem_T) \$ t]
2054     in
2055       case maps elems_for (all_values elem_T) @
2056            (if maybe_opt then [Const (Nitpick_Model.unrep (), elem_T)]
2057             else []) of
2058         [] => Const (@{const_name zero_class.zero}, T)
2059       | ts => foldl1 (fn (t1, t2) =>
2060                          Const (@{const_name plus_class.plus}, T --> T --> T)
2061                          \$ t1 \$ t2)
2062                      (map (curry (op \$) (Const (@{const_name single},
2063                                                 elem_T --> T))) ts)
2064     end
2065   | multiset_postproc _ _ _ _ t = t
2066 \<close>
2068 declaration \<open>
2069 Nitpick_Model.register_term_postprocessor @{typ "'a multiset"}
2070     multiset_postproc
2071 \<close>
2074 subsection \<open>Naive implementation using lists\<close>
2076 code_datatype multiset_of
2078 lemma [code]:
2079   "{#} = multiset_of []"
2080   by simp
2082 lemma [code]:
2083   "{#x#} = multiset_of [x]"
2084   by simp
2086 lemma union_code [code]:
2087   "multiset_of xs + multiset_of ys = multiset_of (xs @ ys)"
2088   by simp
2090 lemma [code]:
2091   "image_mset f (multiset_of xs) = multiset_of (map f xs)"
2092   by (simp add: multiset_of_map)
2094 lemma [code]:
2095   "filter_mset f (multiset_of xs) = multiset_of (filter f xs)"
2096   by (simp add: multiset_of_filter)
2098 lemma [code]:
2099   "multiset_of xs - multiset_of ys = multiset_of (fold remove1 ys xs)"
2100   by (rule sym, induct ys arbitrary: xs) (simp_all add: diff_add diff_right_commute)
2102 lemma [code]:
2103   "multiset_of xs #\<inter> multiset_of ys =
2104     multiset_of (snd (fold (\<lambda>x (ys, zs).
2105       if x \<in> set ys then (remove1 x ys, x # zs) else (ys, zs)) xs (ys, [])))"
2106 proof -
2107   have "\<And>zs. multiset_of (snd (fold (\<lambda>x (ys, zs).
2108     if x \<in> set ys then (remove1 x ys, x # zs) else (ys, zs)) xs (ys, zs))) =
2109       (multiset_of xs #\<inter> multiset_of ys) + multiset_of zs"
2110     by (induct xs arbitrary: ys)
2112   then show ?thesis by simp
2113 qed
2115 lemma [code]:
2116   "multiset_of xs #\<union> multiset_of ys =
2117     multiset_of (split append (fold (\<lambda>x (ys, zs). (remove1 x ys, x # zs)) xs (ys, [])))"
2118 proof -
2119   have "\<And>zs. multiset_of (split append (fold (\<lambda>x (ys, zs). (remove1 x ys, x # zs)) xs (ys, zs))) =
2120       (multiset_of xs #\<union> multiset_of ys) + multiset_of zs"
2121     by (induct xs arbitrary: ys) (simp_all add: multiset_eq_iff)
2122   then show ?thesis by simp
2123 qed
2125 declare in_multiset_in_set [code_unfold]
2127 lemma [code]:
2128   "count (multiset_of xs) x = fold (\<lambda>y. if x = y then Suc else id) xs 0"
2129 proof -
2130   have "\<And>n. fold (\<lambda>y. if x = y then Suc else id) xs n = count (multiset_of xs) x + n"
2131     by (induct xs) simp_all
2132   then show ?thesis by simp
2133 qed
2135 declare set_mset_multiset_of [code]
2137 declare sorted_list_of_multiset_multiset_of [code]
2139 lemma [code]: -- \<open>not very efficient, but representation-ignorant!\<close>
2140   "multiset_of_set A = multiset_of (sorted_list_of_set A)"
2141   apply (cases "finite A")
2142   apply simp_all
2143   apply (induct A rule: finite_induct)
2145   done
2147 declare size_multiset_of [code]
2149 fun ms_lesseq_impl :: "'a list \<Rightarrow> 'a list \<Rightarrow> bool option" where
2150   "ms_lesseq_impl [] ys = Some (ys \<noteq> [])"
2151 | "ms_lesseq_impl (Cons x xs) ys = (case List.extract (op = x) ys of
2152      None \<Rightarrow> None
2153    | Some (ys1,_,ys2) \<Rightarrow> ms_lesseq_impl xs (ys1 @ ys2))"
2155 lemma ms_lesseq_impl: "(ms_lesseq_impl xs ys = None \<longleftrightarrow> \<not> multiset_of xs \<le># multiset_of ys) \<and>
2156   (ms_lesseq_impl xs ys = Some True \<longleftrightarrow> multiset_of xs <# multiset_of ys) \<and>
2157   (ms_lesseq_impl xs ys = Some False \<longrightarrow> multiset_of xs = multiset_of ys)"
2158 proof (induct xs arbitrary: ys)
2159   case (Nil ys)
2160   show ?case by (auto simp: mset_less_empty_nonempty)
2161 next
2162   case (Cons x xs ys)
2163   show ?case
2164   proof (cases "List.extract (op = x) ys")
2165     case None
2166     hence x: "x \<notin> set ys" by (simp add: extract_None_iff)
2167     {
2168       assume "multiset_of (x # xs) \<le># multiset_of ys"
2169       from set_mset_mono[OF this] x have False by simp
2170     } note nle = this
2171     moreover
2172     {
2173       assume "multiset_of (x # xs) <# multiset_of ys"
2174       hence "multiset_of (x # xs) \<le># multiset_of ys" by auto
2175       from nle[OF this] have False .
2176     }
2177     ultimately show ?thesis using None by auto
2178   next
2179     case (Some res)
2180     obtain ys1 y ys2 where res: "res = (ys1,y,ys2)" by (cases res, auto)
2181     note Some = Some[unfolded res]
2182     from extract_SomeE[OF Some] have "ys = ys1 @ x # ys2" by simp
2183     hence id: "multiset_of ys = multiset_of (ys1 @ ys2) + {#x#}"
2184       by (auto simp: ac_simps)
2185     show ?thesis unfolding ms_lesseq_impl.simps
2186       unfolding Some option.simps split
2187       unfolding id
2188       using Cons[of "ys1 @ ys2"]
2189       unfolding subset_mset_def subseteq_mset_def by auto
2190   qed
2191 qed
2193 lemma [code]: "multiset_of xs \<le># multiset_of ys \<longleftrightarrow> ms_lesseq_impl xs ys \<noteq> None"
2194   using ms_lesseq_impl[of xs ys] by (cases "ms_lesseq_impl xs ys", auto)
2196 lemma [code]: "multiset_of xs <# multiset_of ys \<longleftrightarrow> ms_lesseq_impl xs ys = Some True"
2197   using ms_lesseq_impl[of xs ys] by (cases "ms_lesseq_impl xs ys", auto)
2199 instantiation multiset :: (equal) equal
2200 begin
2202 definition
2203   [code del]: "HOL.equal A (B :: 'a multiset) \<longleftrightarrow> A = B"
2204 lemma [code]: "HOL.equal (multiset_of xs) (multiset_of ys) \<longleftrightarrow> ms_lesseq_impl xs ys = Some False"
2205   unfolding equal_multiset_def
2206   using ms_lesseq_impl[of xs ys] by (cases "ms_lesseq_impl xs ys", auto)
2208 instance
2209   by default (simp add: equal_multiset_def)
2210 end
2212 lemma [code]:
2213   "msetsum (multiset_of xs) = listsum xs"
2214   by (induct xs) (simp_all add: add.commute)
2216 lemma [code]:
2217   "msetprod (multiset_of xs) = fold times xs 1"
2218 proof -
2219   have "\<And>x. fold times xs x = msetprod (multiset_of xs) * x"
2220     by (induct xs) (simp_all add: mult.assoc)
2221   then show ?thesis by simp
2222 qed
2224 text \<open>
2225   Exercise for the casual reader: add implementations for @{const le_multiset}
2226   and @{const less_multiset} (multiset order).
2227 \<close>
2229 text \<open>Quickcheck generators\<close>
2231 definition (in term_syntax)
2232   msetify :: "'a\<Colon>typerep list \<times> (unit \<Rightarrow> Code_Evaluation.term)
2233     \<Rightarrow> 'a multiset \<times> (unit \<Rightarrow> Code_Evaluation.term)" where
2234   [code_unfold]: "msetify xs = Code_Evaluation.valtermify multiset_of {\<cdot>} xs"
2236 notation fcomp (infixl "\<circ>>" 60)
2237 notation scomp (infixl "\<circ>\<rightarrow>" 60)
2239 instantiation multiset :: (random) random
2240 begin
2242 definition
2243   "Quickcheck_Random.random i = Quickcheck_Random.random i \<circ>\<rightarrow> (\<lambda>xs. Pair (msetify xs))"
2245 instance ..
2247 end
2249 no_notation fcomp (infixl "\<circ>>" 60)
2250 no_notation scomp (infixl "\<circ>\<rightarrow>" 60)
2252 instantiation multiset :: (full_exhaustive) full_exhaustive
2253 begin
2255 definition full_exhaustive_multiset :: "('a multiset \<times> (unit \<Rightarrow> term) \<Rightarrow> (bool \<times> term list) option) \<Rightarrow> natural \<Rightarrow> (bool \<times> term list) option"
2256 where
2257   "full_exhaustive_multiset f i = Quickcheck_Exhaustive.full_exhaustive (\<lambda>xs. f (msetify xs)) i"
2259 instance ..
2261 end
2263 hide_const (open) msetify
2266 subsection \<open>BNF setup\<close>
2268 definition rel_mset where
2269   "rel_mset R X Y \<longleftrightarrow> (\<exists>xs ys. multiset_of xs = X \<and> multiset_of ys = Y \<and> list_all2 R xs ys)"
2271 lemma multiset_of_zip_take_Cons_drop_twice:
2272   assumes "length xs = length ys" "j \<le> length xs"
2273   shows "multiset_of (zip (take j xs @ x # drop j xs) (take j ys @ y # drop j ys)) =
2274     multiset_of (zip xs ys) + {#(x, y)#}"
2275 using assms
2276 proof (induct xs ys arbitrary: x y j rule: list_induct2)
2277   case Nil
2278   thus ?case
2279     by simp
2280 next
2281   case (Cons x xs y ys)
2282   thus ?case
2283   proof (cases "j = 0")
2284     case True
2285     thus ?thesis
2286       by simp
2287   next
2288     case False
2289     then obtain k where k: "j = Suc k"
2290       by (case_tac j) simp
2291     hence "k \<le> length xs"
2292       using Cons.prems by auto
2293     hence "multiset_of (zip (take k xs @ x # drop k xs) (take k ys @ y # drop k ys)) =
2294       multiset_of (zip xs ys) + {#(x, y)#}"
2295       by (rule Cons.hyps(2))
2296     thus ?thesis
2297       unfolding k by (auto simp: add.commute union_lcomm)
2298   qed
2299 qed
2301 lemma ex_multiset_of_zip_left:
2302   assumes "length xs = length ys" "multiset_of xs' = multiset_of xs"
2303   shows "\<exists>ys'. length ys' = length xs' \<and> multiset_of (zip xs' ys') = multiset_of (zip xs ys)"
2304 using assms
2305 proof (induct xs ys arbitrary: xs' rule: list_induct2)
2306   case Nil
2307   thus ?case
2308     by auto
2309 next
2310   case (Cons x xs y ys xs')
2311   obtain j where j_len: "j < length xs'" and nth_j: "xs' ! j = x"
2312     by (metis Cons.prems in_set_conv_nth list.set_intros(1) multiset_of_eq_setD)
2314   def xsa \<equiv> "take j xs' @ drop (Suc j) xs'"
2315   have "multiset_of xs' = {#x#} + multiset_of xsa"
2316     unfolding xsa_def using j_len nth_j
2317     by (metis (no_types) ab_semigroup_add_class.add_ac(1) append_take_drop_id Cons_nth_drop_Suc
2318       multiset_of.simps(2) union_code add.commute)
2319   hence ms_x: "multiset_of xsa = multiset_of xs"
2320     by (metis Cons.prems add.commute add_right_imp_eq multiset_of.simps(2))
2321   then obtain ysa where
2322     len_a: "length ysa = length xsa" and ms_a: "multiset_of (zip xsa ysa) = multiset_of (zip xs ys)"
2323     using Cons.hyps(2) by blast
2325   def ys' \<equiv> "take j ysa @ y # drop j ysa"
2326   have xs': "xs' = take j xsa @ x # drop j xsa"
2327     using ms_x j_len nth_j Cons.prems xsa_def
2328     by (metis append_eq_append_conv append_take_drop_id diff_Suc_Suc Cons_nth_drop_Suc length_Cons
2329       length_drop size_multiset_of)
2330   have j_len': "j \<le> length xsa"
2331     using j_len xs' xsa_def
2332     by (metis add_Suc_right append_take_drop_id length_Cons length_append less_eq_Suc_le not_less)
2333   have "length ys' = length xs'"
2334     unfolding ys'_def using Cons.prems len_a ms_x
2335     by (metis add_Suc_right append_take_drop_id length_Cons length_append multiset_of_eq_length)
2336   moreover have "multiset_of (zip xs' ys') = multiset_of (zip (x # xs) (y # ys))"
2337     unfolding xs' ys'_def
2338     by (rule trans[OF multiset_of_zip_take_Cons_drop_twice])
2339       (auto simp: len_a ms_a j_len' add.commute)
2340   ultimately show ?case
2341     by blast
2342 qed
2344 lemma list_all2_reorder_left_invariance:
2345   assumes rel: "list_all2 R xs ys" and ms_x: "multiset_of xs' = multiset_of xs"
2346   shows "\<exists>ys'. list_all2 R xs' ys' \<and> multiset_of ys' = multiset_of ys"
2347 proof -
2348   have len: "length xs = length ys"
2349     using rel list_all2_conv_all_nth by auto
2350   obtain ys' where
2351     len': "length xs' = length ys'" and ms_xy: "multiset_of (zip xs' ys') = multiset_of (zip xs ys)"
2352     using len ms_x by (metis ex_multiset_of_zip_left)
2353   have "list_all2 R xs' ys'"
2354     using assms(1) len' ms_xy unfolding list_all2_iff by (blast dest: multiset_of_eq_setD)
2355   moreover have "multiset_of ys' = multiset_of ys"
2356     using len len' ms_xy map_snd_zip multiset_of_map by metis
2357   ultimately show ?thesis
2358     by blast
2359 qed
2361 lemma ex_multiset_of: "\<exists>xs. multiset_of xs = X"
2362   by (induct X) (simp, metis multiset_of.simps(2))
2364 bnf "'a multiset"
2365   map: image_mset
2366   sets: set_mset
2367   bd: natLeq
2368   wits: "{#}"
2369   rel: rel_mset
2370 proof -
2371   show "image_mset id = id"
2372     by (rule image_mset.id)
2373 next
2374   show "\<And>f g. image_mset (g \<circ> f) = image_mset g \<circ> image_mset f"
2375     unfolding comp_def by (rule ext) (simp add: comp_def image_mset.compositionality)
2376 next
2377   fix X :: "'a multiset"
2378   show "\<And>f g. (\<And>z. z \<in> set_mset X \<Longrightarrow> f z = g z) \<Longrightarrow> image_mset f X = image_mset g X"
2379     by (induct X, (simp (no_asm))+,
2380       metis One_nat_def Un_iff count_single mem_set_mset_iff set_mset_union zero_less_Suc)
2381 next
2382   show "\<And>f. set_mset \<circ> image_mset f = op ` f \<circ> set_mset"
2383     by auto
2384 next
2385   show "card_order natLeq"
2386     by (rule natLeq_card_order)
2387 next
2388   show "BNF_Cardinal_Arithmetic.cinfinite natLeq"
2389     by (rule natLeq_cinfinite)
2390 next
2391   show "\<And>X. ordLeq3 (card_of (set_mset X)) natLeq"
2392     by transfer
2393       (auto intro!: ordLess_imp_ordLeq simp: finite_iff_ordLess_natLeq[symmetric] multiset_def)
2394 next
2395   show "\<And>R S. rel_mset R OO rel_mset S \<le> rel_mset (R OO S)"
2396     unfolding rel_mset_def[abs_def] OO_def
2397     apply clarify
2398     apply (rename_tac X Z Y xs ys' ys zs)
2399     apply (drule_tac xs = ys' and ys = zs and xs' = ys in list_all2_reorder_left_invariance)
2400     by (auto intro: list_all2_trans)
2401 next
2402   show "\<And>R. rel_mset R =
2403     (BNF_Def.Grp {x. set_mset x \<subseteq> {(x, y). R x y}} (image_mset fst))\<inverse>\<inverse> OO
2404     BNF_Def.Grp {x. set_mset x \<subseteq> {(x, y). R x y}} (image_mset snd)"
2405     unfolding rel_mset_def[abs_def] BNF_Def.Grp_def OO_def
2406     apply (rule ext)+
2407     apply auto
2408      apply (rule_tac x = "multiset_of (zip xs ys)" in exI; auto)
2409         apply (metis list_all2_lengthD map_fst_zip multiset_of_map)
2410        apply (auto simp: list_all2_iff)
2411       apply (metis list_all2_lengthD map_snd_zip multiset_of_map)
2412      apply (auto simp: list_all2_iff)
2413     apply (rename_tac XY)
2414     apply (cut_tac X = XY in ex_multiset_of)
2415     apply (erule exE)
2416     apply (rename_tac xys)
2417     apply (rule_tac x = "map fst xys" in exI)
2418     apply (auto simp: multiset_of_map)
2419     apply (rule_tac x = "map snd xys" in exI)
2420     apply (auto simp: multiset_of_map list_all2I subset_eq zip_map_fst_snd)
2421     done
2422 next
2423   show "\<And>z. z \<in> set_mset {#} \<Longrightarrow> False"
2424     by auto
2425 qed
2427 inductive rel_mset' where
2428   Zero[intro]: "rel_mset' R {#} {#}"
2429 | Plus[intro]: "\<lbrakk>R a b; rel_mset' R M N\<rbrakk> \<Longrightarrow> rel_mset' R (M + {#a#}) (N + {#b#})"
2431 lemma rel_mset_Zero: "rel_mset R {#} {#}"
2432 unfolding rel_mset_def Grp_def by auto
2434 declare multiset.count[simp]
2435 declare Abs_multiset_inverse[simp]
2436 declare multiset.count_inverse[simp]
2437 declare union_preserves_multiset[simp]
2439 lemma rel_mset_Plus:
2440 assumes ab: "R a b" and MN: "rel_mset R M N"
2441 shows "rel_mset R (M + {#a#}) (N + {#b#})"
2442 proof-
2443   {fix y assume "R a b" and "set_mset y \<subseteq> {(x, y). R x y}"
2444    hence "\<exists>ya. image_mset fst y + {#a#} = image_mset fst ya \<and>
2445                image_mset snd y + {#b#} = image_mset snd ya \<and>
2446                set_mset ya \<subseteq> {(x, y). R x y}"
2447    apply(intro exI[of _ "y + {#(a,b)#}"]) by auto
2448   }
2449   thus ?thesis
2450   using assms
2451   unfolding multiset.rel_compp_Grp Grp_def by blast
2452 qed
2454 lemma rel_mset'_imp_rel_mset:
2455   "rel_mset' R M N \<Longrightarrow> rel_mset R M N"
2456 apply(induct rule: rel_mset'.induct)
2457 using rel_mset_Zero rel_mset_Plus by auto
2459 lemma rel_mset_size:
2460   "rel_mset R M N \<Longrightarrow> size M = size N"
2461 unfolding multiset.rel_compp_Grp Grp_def by auto
2464 assumes empty: "P {#} {#}"
2465 and addL: "\<And>M N a. P M N \<Longrightarrow> P (M + {#a#}) N"
2466 and addR: "\<And>M N a. P M N \<Longrightarrow> P M (N + {#a#})"
2467 shows "P M N"
2468 apply(induct N rule: multiset_induct)
2469   apply(induct M rule: multiset_induct, rule empty, erule addL)
2470   apply(induct M rule: multiset_induct, erule addR, erule addR)
2471 done
2473 lemma multiset_induct2_size[consumes 1, case_names empty add]:
2474 assumes c: "size M = size N"
2475 and empty: "P {#} {#}"
2476 and add: "\<And>M N a b. P M N \<Longrightarrow> P (M + {#a#}) (N + {#b#})"
2477 shows "P M N"
2478 using c proof(induct M arbitrary: N rule: measure_induct_rule[of size])
2479   case (less M)  show ?case
2480   proof(cases "M = {#}")
2481     case True hence "N = {#}" using less.prems by auto
2482     thus ?thesis using True empty by auto
2483   next
2484     case False then obtain M1 a where M: "M = M1 + {#a#}" by (metis multi_nonempty_split)
2485     have "N \<noteq> {#}" using False less.prems by auto
2486     then obtain N1 b where N: "N = N1 + {#b#}" by (metis multi_nonempty_split)
2487     have "size M1 = size N1" using less.prems unfolding M N by auto
2488     thus ?thesis using M N less.hyps add by auto
2489   qed
2490 qed
2492 lemma msed_map_invL:
2493 assumes "image_mset f (M + {#a#}) = N"
2494 shows "\<exists>N1. N = N1 + {#f a#} \<and> image_mset f M = N1"
2495 proof-
2496   have "f a \<in># N"
2497   using assms multiset.set_map[of f "M + {#a#}"] by auto
2498   then obtain N1 where N: "N = N1 + {#f a#}" using multi_member_split by metis
2499   have "image_mset f M = N1" using assms unfolding N by simp
2500   thus ?thesis using N by blast
2501 qed
2503 lemma msed_map_invR:
2504 assumes "image_mset f M = N + {#b#}"
2505 shows "\<exists>M1 a. M = M1 + {#a#} \<and> f a = b \<and> image_mset f M1 = N"
2506 proof-
2507   obtain a where a: "a \<in># M" and fa: "f a = b"
2508   using multiset.set_map[of f M] unfolding assms
2509   by (metis image_iff mem_set_mset_iff union_single_eq_member)
2510   then obtain M1 where M: "M = M1 + {#a#}" using multi_member_split by metis
2511   have "image_mset f M1 = N" using assms unfolding M fa[symmetric] by simp
2512   thus ?thesis using M fa by blast
2513 qed
2515 lemma msed_rel_invL:
2516 assumes "rel_mset R (M + {#a#}) N"
2517 shows "\<exists>N1 b. N = N1 + {#b#} \<and> R a b \<and> rel_mset R M N1"
2518 proof-
2519   obtain K where KM: "image_mset fst K = M + {#a#}"
2520   and KN: "image_mset snd K = N" and sK: "set_mset K \<subseteq> {(a, b). R a b}"
2521   using assms
2522   unfolding multiset.rel_compp_Grp Grp_def by auto
2523   obtain K1 ab where K: "K = K1 + {#ab#}" and a: "fst ab = a"
2524   and K1M: "image_mset fst K1 = M" using msed_map_invR[OF KM] by auto
2525   obtain N1 where N: "N = N1 + {#snd ab#}" and K1N1: "image_mset snd K1 = N1"
2526   using msed_map_invL[OF KN[unfolded K]] by auto
2527   have Rab: "R a (snd ab)" using sK a unfolding K by auto
2528   have "rel_mset R M N1" using sK K1M K1N1
2529   unfolding K multiset.rel_compp_Grp Grp_def by auto
2530   thus ?thesis using N Rab by auto
2531 qed
2533 lemma msed_rel_invR:
2534 assumes "rel_mset R M (N + {#b#})"
2535 shows "\<exists>M1 a. M = M1 + {#a#} \<and> R a b \<and> rel_mset R M1 N"
2536 proof-
2537   obtain K where KN: "image_mset snd K = N + {#b#}"
2538   and KM: "image_mset fst K = M" and sK: "set_mset K \<subseteq> {(a, b). R a b}"
2539   using assms
2540   unfolding multiset.rel_compp_Grp Grp_def by auto
2541   obtain K1 ab where K: "K = K1 + {#ab#}" and b: "snd ab = b"
2542   and K1N: "image_mset snd K1 = N" using msed_map_invR[OF KN] by auto
2543   obtain M1 where M: "M = M1 + {#fst ab#}" and K1M1: "image_mset fst K1 = M1"
2544   using msed_map_invL[OF KM[unfolded K]] by auto
2545   have Rab: "R (fst ab) b" using sK b unfolding K by auto
2546   have "rel_mset R M1 N" using sK K1N K1M1
2547   unfolding K multiset.rel_compp_Grp Grp_def by auto
2548   thus ?thesis using M Rab by auto
2549 qed
2551 lemma rel_mset_imp_rel_mset':
2552 assumes "rel_mset R M N"
2553 shows "rel_mset' R M N"
2554 using assms proof(induct M arbitrary: N rule: measure_induct_rule[of size])
2555   case (less M)
2556   have c: "size M = size N" using rel_mset_size[OF less.prems] .
2557   show ?case
2558   proof(cases "M = {#}")
2559     case True hence "N = {#}" using c by simp
2560     thus ?thesis using True rel_mset'.Zero by auto
2561   next
2562     case False then obtain M1 a where M: "M = M1 + {#a#}" by (metis multi_nonempty_split)
2563     obtain N1 b where N: "N = N1 + {#b#}" and R: "R a b" and ms: "rel_mset R M1 N1"
2564     using msed_rel_invL[OF less.prems[unfolded M]] by auto
2565     have "rel_mset' R M1 N1" using less.hyps[of M1 N1] ms unfolding M by simp
2566     thus ?thesis using rel_mset'.Plus[of R a b, OF R] unfolding M N by simp
2567   qed
2568 qed
2570 lemma rel_mset_rel_mset':
2571 "rel_mset R M N = rel_mset' R M N"
2572 using rel_mset_imp_rel_mset' rel_mset'_imp_rel_mset by auto
2574 (* The main end product for rel_mset: inductive characterization *)
2575 theorems rel_mset_induct[case_names empty add, induct pred: rel_mset] =
2576          rel_mset'.induct[unfolded rel_mset_rel_mset'[symmetric]]
2579 subsection \<open>Size setup\<close>
2581 lemma multiset_size_o_map: "size_multiset g \<circ> image_mset f = size_multiset (g \<circ> f)"
2582   unfolding o_apply by (rule ext) (induct_tac, auto)
2584 setup \<open>
2585 BNF_LFP_Size.register_size_global @{type_name multiset} @{const_name size_multiset}
2586   @{thms size_multiset_empty size_multiset_single size_multiset_union size_empty size_single
2587     size_union}
2588   @{thms multiset_size_o_map}
2589 \<close>
2591 hide_const (open) wcount
2593 end