src/HOL/Library/Multiset.thy
 author haftmann Mon Mar 23 19:05:14 2015 +0100 (2015-03-23) changeset 59815 cce82e360c2f parent 59813 6320064f22bb child 59949 fc4c896c8e74 permissions -rw-r--r--
explicit commutative additive inverse operation;
more explicit focal point for commutative monoids with an inverse operation
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 {* (Finite) multisets *}
11 theory Multiset
12 imports Main
13 begin
15 subsection {* The type of multisets *}
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 {*
43  \medskip Preservation of the representing set @{term multiset}.
44 *}
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 {* Representing multisets *}
84 text {* Multiset enumeration *}
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 {* Basic operations *}
124 subsubsection {* Union *}
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 {* Difference *}
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 {* Equality of multisets *}
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 `?lhs` show ?thesis by simp
238   next
239     case False
240     from `?lhs` have "a \<in># N + {#b#}" by (rule union_single_eq_member)
241     with False have "a \<in># N" by auto
242     moreover from `?lhs` 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 `c \<in># B` 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 {* Pointwise ordering induced by count *}
283 instantiation multiset :: (type) ordered_ab_semigroup_add_imp_le
284 begin
286 lift_definition less_eq_multiset :: "'a multiset \<Rightarrow> 'a multiset \<Rightarrow> bool" is "\<lambda> A B. (\<forall>a. A a \<le> B a)" .
288 lemmas mset_le_def = less_eq_multiset_def
290 definition less_multiset :: "'a multiset \<Rightarrow> 'a multiset \<Rightarrow> bool" where
291   mset_less_def: "(A::'a multiset) < B \<longleftrightarrow> A \<le> B \<and> A \<noteq> B"
293 instance
294   by default (auto simp add: mset_le_def mset_less_def multiset_eq_iff intro: order_trans antisym)
296 end
298 lemma mset_less_eqI:
299   "(\<And>x. count A x \<le> count B x) \<Longrightarrow> A \<le> B"
300   by (simp add: mset_le_def)
302 lemma mset_le_exists_conv:
303   "(A::'a multiset) \<le> B \<longleftrightarrow> (\<exists>C. B = A + C)"
304 apply (unfold mset_le_def, rule iffI, rule_tac x = "B - A" in exI)
305 apply (auto intro: multiset_eq_iff [THEN iffD2])
306 done
308 instance multiset :: (type) ordered_cancel_comm_monoid_diff
309   by default (simp, fact mset_le_exists_conv)
311 lemma mset_le_mono_add_right_cancel [simp]:
312   "(A::'a multiset) + C \<le> B + C \<longleftrightarrow> A \<le> B"
313   by (fact add_le_cancel_right)
315 lemma mset_le_mono_add_left_cancel [simp]:
316   "C + (A::'a multiset) \<le> C + B \<longleftrightarrow> A \<le> B"
317   by (fact add_le_cancel_left)
320   "(A::'a multiset) \<le> B \<Longrightarrow> C \<le> D \<Longrightarrow> A + C \<le> B + D"
321   by (fact add_mono)
323 lemma mset_le_add_left [simp]:
324   "(A::'a multiset) \<le> A + B"
325   unfolding mset_le_def by auto
327 lemma mset_le_add_right [simp]:
328   "B \<le> (A::'a multiset) + B"
329   unfolding mset_le_def by auto
331 lemma mset_le_single:
332   "a :# B \<Longrightarrow> {#a#} \<le> B"
333   by (simp add: mset_le_def)
335 lemma multiset_diff_union_assoc:
336   "C \<le> B \<Longrightarrow> (A::'a multiset) + B - C = A + (B - C)"
337   by (simp add: multiset_eq_iff mset_le_def)
339 lemma mset_le_multiset_union_diff_commute:
340   "B \<le> A \<Longrightarrow> (A::'a multiset) - B + C = A + C - B"
341 by (simp add: multiset_eq_iff mset_le_def)
343 lemma diff_le_self[simp]: "(M::'a multiset) - N \<le> M"
344 by(simp add: mset_le_def)
346 lemma mset_lessD: "A < B \<Longrightarrow> x \<in># A \<Longrightarrow> x \<in># B"
347 apply (clarsimp simp: mset_le_def mset_less_def)
348 apply (erule_tac x=x in allE)
349 apply auto
350 done
352 lemma mset_leD: "A \<le> B \<Longrightarrow> x \<in># A \<Longrightarrow> x \<in># B"
353 apply (clarsimp simp: mset_le_def mset_less_def)
354 apply (erule_tac x = x in allE)
355 apply auto
356 done
358 lemma mset_less_insertD: "(A + {#x#} < B) \<Longrightarrow> (x \<in># B \<and> A < B)"
359 apply (rule conjI)
360  apply (simp add: mset_lessD)
361 apply (clarsimp simp: mset_le_def mset_less_def)
362 apply safe
363  apply (erule_tac x = a in allE)
364  apply (auto split: split_if_asm)
365 done
367 lemma mset_le_insertD: "(A + {#x#} \<le> B) \<Longrightarrow> (x \<in># B \<and> A \<le> B)"
368 apply (rule conjI)
369  apply (simp add: mset_leD)
370 apply (force simp: mset_le_def mset_less_def split: split_if_asm)
371 done
373 lemma mset_less_of_empty[simp]: "A < {#} \<longleftrightarrow> False"
374   by (auto simp add: mset_less_def mset_le_def multiset_eq_iff)
376 lemma empty_le[simp]: "{#} \<le> A"
377   unfolding mset_le_exists_conv by auto
379 lemma le_empty[simp]: "(M \<le> {#}) = (M = {#})"
380   unfolding mset_le_exists_conv by auto
382 lemma multi_psub_of_add_self[simp]: "A < A + {#x#}"
383   by (auto simp: mset_le_def mset_less_def)
385 lemma multi_psub_self[simp]: "(A::'a multiset) < A = False"
386   by simp
388 lemma mset_less_add_bothsides: "N + {#x#} < M + {#x#} \<Longrightarrow> N < M"
389   by (fact add_less_imp_less_right)
391 lemma mset_less_empty_nonempty:
392   "{#} < S \<longleftrightarrow> S \<noteq> {#}"
393   by (auto simp: mset_le_def mset_less_def)
395 lemma mset_less_diff_self:
396   "c \<in># B \<Longrightarrow> B - {#c#} < B"
397   by (auto simp: mset_le_def mset_less_def multiset_eq_iff)
400 subsubsection {* Intersection *}
402 instantiation multiset :: (type) semilattice_inf
403 begin
405 definition inf_multiset :: "'a multiset \<Rightarrow> 'a multiset \<Rightarrow> 'a multiset" where
406   multiset_inter_def: "inf_multiset A B = A - (A - B)"
408 instance
409 proof -
410   have aux: "\<And>m n q :: nat. m \<le> n \<Longrightarrow> m \<le> q \<Longrightarrow> m \<le> n - (n - q)" by arith
411   show "OFCLASS('a multiset, semilattice_inf_class)"
412     by default (auto simp add: multiset_inter_def mset_le_def aux)
413 qed
415 end
417 abbreviation multiset_inter :: "'a multiset \<Rightarrow> 'a multiset \<Rightarrow> 'a multiset" (infixl "#\<inter>" 70) where
418   "multiset_inter \<equiv> inf"
420 lemma multiset_inter_count [simp]:
421   "count (A #\<inter> B) x = min (count A x) (count B x)"
422   by (simp add: multiset_inter_def)
424 lemma multiset_inter_single: "a \<noteq> b \<Longrightarrow> {#a#} #\<inter> {#b#} = {#}"
425   by (rule multiset_eqI) auto
427 lemma multiset_union_diff_commute:
428   assumes "B #\<inter> C = {#}"
429   shows "A + B - C = A - C + B"
430 proof (rule multiset_eqI)
431   fix x
432   from assms have "min (count B x) (count C x) = 0"
433     by (auto simp add: multiset_eq_iff)
434   then have "count B x = 0 \<or> count C x = 0"
435     by auto
436   then show "count (A + B - C) x = count (A - C + B) x"
437     by auto
438 qed
440 lemma empty_inter [simp]:
441   "{#} #\<inter> M = {#}"
442   by (simp add: multiset_eq_iff)
444 lemma inter_empty [simp]:
445   "M #\<inter> {#} = {#}"
446   by (simp add: multiset_eq_iff)
449   "\<not> x \<in># N \<Longrightarrow> (M + {#x#}) #\<inter> N = M #\<inter> N"
450   by (simp add: multiset_eq_iff)
453   "x \<in># N \<Longrightarrow> (M + {#x#}) #\<inter> N = (M #\<inter> (N - {#x#})) + {#x#}"
454   by (simp add: multiset_eq_iff)
457   "\<not> x \<in># N \<Longrightarrow> N #\<inter> (M + {#x#}) = N #\<inter> M"
458   by (simp add: multiset_eq_iff)
461   "x \<in># N \<Longrightarrow> N #\<inter> (M + {#x#}) = ((N - {#x#}) #\<inter> M) + {#x#}"
462   by (simp add: multiset_eq_iff)
465 subsubsection {* Bounded union *}
467 instantiation multiset :: (type) semilattice_sup
468 begin
470 definition sup_multiset :: "'a multiset \<Rightarrow> 'a multiset \<Rightarrow> 'a multiset" where
471   "sup_multiset A B = A + (B - A)"
473 instance
474 proof -
475   have aux: "\<And>m n q :: nat. m \<le> n \<Longrightarrow> q \<le> n \<Longrightarrow> m + (q - m) \<le> n" by arith
476   show "OFCLASS('a multiset, semilattice_sup_class)"
477     by default (auto simp add: sup_multiset_def mset_le_def aux)
478 qed
480 end
482 abbreviation sup_multiset :: "'a multiset \<Rightarrow> 'a multiset \<Rightarrow> 'a multiset" (infixl "#\<union>" 70) where
483   "sup_multiset \<equiv> sup"
485 lemma sup_multiset_count [simp]:
486   "count (A #\<union> B) x = max (count A x) (count B x)"
487   by (simp add: sup_multiset_def)
489 lemma empty_sup [simp]:
490   "{#} #\<union> M = M"
491   by (simp add: multiset_eq_iff)
493 lemma sup_empty [simp]:
494   "M #\<union> {#} = M"
495   by (simp add: multiset_eq_iff)
498   "\<not> x \<in># N \<Longrightarrow> (M + {#x#}) #\<union> N = (M #\<union> N) + {#x#}"
499   by (simp add: multiset_eq_iff)
502   "x \<in># N \<Longrightarrow> (M + {#x#}) #\<union> N = (M #\<union> (N - {#x#})) + {#x#}"
503   by (simp add: multiset_eq_iff)
506   "\<not> x \<in># N \<Longrightarrow> N #\<union> (M + {#x#}) = (N #\<union> M) + {#x#}"
507   by (simp add: multiset_eq_iff)
510   "x \<in># N \<Longrightarrow> N #\<union> (M + {#x#}) = ((N - {#x#}) #\<union> M) + {#x#}"
511   by (simp add: multiset_eq_iff)
514 subsubsection {* Filter (with comprehension syntax) *}
516 text {* Multiset comprehension *}
518 lift_definition filter :: "('a \<Rightarrow> bool) \<Rightarrow> 'a multiset \<Rightarrow> 'a multiset" is "\<lambda>P M. \<lambda>x. if P x then M x else 0"
519 by (rule filter_preserves_multiset)
521 hide_const (open) filter
523 lemma count_filter [simp]:
524   "count (Multiset.filter P M) a = (if P a then count M a else 0)"
525   by (simp add: filter.rep_eq)
527 lemma filter_empty [simp]:
528   "Multiset.filter P {#} = {#}"
529   by (rule multiset_eqI) simp
531 lemma filter_single [simp]:
532   "Multiset.filter P {#x#} = (if P x then {#x#} else {#})"
533   by (rule multiset_eqI) simp
535 lemma filter_union [simp]:
536   "Multiset.filter P (M + N) = Multiset.filter P M + Multiset.filter P N"
537   by (rule multiset_eqI) simp
539 lemma filter_diff [simp]:
540   "Multiset.filter P (M - N) = Multiset.filter P M - Multiset.filter P N"
541   by (rule multiset_eqI) simp
543 lemma filter_inter [simp]:
544   "Multiset.filter P (M #\<inter> N) = Multiset.filter P M #\<inter> Multiset.filter P N"
545   by (rule multiset_eqI) simp
547 lemma multiset_filter_subset[simp]: "Multiset.filter f M \<le> M"
548   unfolding less_eq_multiset.rep_eq by auto
550 lemma multiset_filter_mono: assumes "A \<le> B"
551   shows "Multiset.filter f A \<le> Multiset.filter f B"
552 proof -
553   from assms[unfolded mset_le_exists_conv]
554   obtain C where B: "B = A + C" by auto
555   show ?thesis unfolding B by auto
556 qed
558 syntax
559   "_MCollect" :: "pttrn \<Rightarrow> 'a multiset \<Rightarrow> bool \<Rightarrow> 'a multiset"    ("(1{# _ :# _./ _#})")
560 syntax (xsymbol)
561   "_MCollect" :: "pttrn \<Rightarrow> 'a multiset \<Rightarrow> bool \<Rightarrow> 'a multiset"    ("(1{# _ \<in># _./ _#})")
562 translations
563   "{#x \<in># M. P#}" == "CONST Multiset.filter (\<lambda>x. P) M"
566 subsubsection {* Set of elements *}
568 definition set_of :: "'a multiset => 'a set" where
569   "set_of M = {x. x :# M}"
571 lemma set_of_empty [simp]: "set_of {#} = {}"
572 by (simp add: set_of_def)
574 lemma set_of_single [simp]: "set_of {#b#} = {b}"
575 by (simp add: set_of_def)
577 lemma set_of_union [simp]: "set_of (M + N) = set_of M \<union> set_of N"
578 by (auto simp add: set_of_def)
580 lemma set_of_eq_empty_iff [simp]: "(set_of M = {}) = (M = {#})"
581 by (auto simp add: set_of_def multiset_eq_iff)
583 lemma mem_set_of_iff [simp]: "(x \<in> set_of M) = (x :# M)"
584 by (auto simp add: set_of_def)
586 lemma set_of_filter [simp]: "set_of {# x:#M. P x #} = set_of M \<inter> {x. P x}"
587 by (auto simp add: set_of_def)
589 lemma finite_set_of [iff]: "finite (set_of M)"
590   using count [of M] by (simp add: multiset_def set_of_def)
592 lemma finite_Collect_mem [iff]: "finite {x. x :# M}"
593   unfolding set_of_def[symmetric] by simp
595 lemma set_of_mono: "A \<le> B \<Longrightarrow> set_of A \<subseteq> set_of B"
596   by (metis mset_leD subsetI mem_set_of_iff)
598 lemma ball_set_of_iff: "(\<forall>x \<in> set_of M. P x) \<longleftrightarrow> (\<forall>x. x \<in># M \<longrightarrow> P x)"
599   by auto
602 subsubsection {* Size *}
604 definition wcount where "wcount f M = (\<lambda>x. count M x * Suc (f x))"
606 lemma wcount_union: "wcount f (M + N) a = wcount f M a + wcount f N a"
607   by (auto simp: wcount_def add_mult_distrib)
609 definition size_multiset :: "('a \<Rightarrow> nat) \<Rightarrow> 'a multiset \<Rightarrow> nat" where
610   "size_multiset f M = setsum (wcount f M) (set_of M)"
612 lemmas size_multiset_eq = size_multiset_def[unfolded wcount_def]
614 instantiation multiset :: (type) size begin
615 definition size_multiset where
616   size_multiset_overloaded_def: "size_multiset = Multiset.size_multiset (\<lambda>_. 0)"
617 instance ..
618 end
620 lemmas size_multiset_overloaded_eq =
621   size_multiset_overloaded_def[THEN fun_cong, unfolded size_multiset_eq, simplified]
623 lemma size_multiset_empty [simp]: "size_multiset f {#} = 0"
624 by (simp add: size_multiset_def)
626 lemma size_empty [simp]: "size {#} = 0"
629 lemma size_multiset_single [simp]: "size_multiset f {#b#} = Suc (f b)"
630 by (simp add: size_multiset_eq)
632 lemma size_single [simp]: "size {#b#} = 1"
635 lemma setsum_wcount_Int:
636   "finite A \<Longrightarrow> setsum (wcount f N) (A \<inter> set_of N) = setsum (wcount f N) A"
637 apply (induct rule: finite_induct)
638  apply simp
639 apply (simp add: Int_insert_left set_of_def wcount_def)
640 done
642 lemma size_multiset_union [simp]:
643   "size_multiset f (M + N::'a multiset) = size_multiset f M + size_multiset f N"
644 apply (simp add: size_multiset_def setsum_Un_nat setsum.distrib setsum_wcount_Int wcount_union)
645 apply (subst Int_commute)
646 apply (simp add: setsum_wcount_Int)
647 done
649 lemma size_union [simp]: "size (M + N::'a multiset) = size M + size N"
652 lemma size_multiset_eq_0_iff_empty [iff]: "(size_multiset f M = 0) = (M = {#})"
653 by (auto simp add: size_multiset_eq multiset_eq_iff)
655 lemma size_eq_0_iff_empty [iff]: "(size M = 0) = (M = {#})"
658 lemma nonempty_has_size: "(S \<noteq> {#}) = (0 < size S)"
659 by (metis gr0I gr_implies_not0 size_empty size_eq_0_iff_empty)
661 lemma size_eq_Suc_imp_elem: "size M = Suc n ==> \<exists>a. a :# M"
662 apply (unfold size_multiset_overloaded_eq)
663 apply (drule setsum_SucD)
664 apply auto
665 done
667 lemma size_eq_Suc_imp_eq_union:
668   assumes "size M = Suc n"
669   shows "\<exists>a N. M = N + {#a#}"
670 proof -
671   from assms obtain a where "a \<in># M"
672     by (erule size_eq_Suc_imp_elem [THEN exE])
673   then have "M = M - {#a#} + {#a#}" by simp
674   then show ?thesis by blast
675 qed
678 subsection {* Induction and case splits *}
680 theorem multiset_induct [case_names empty add, induct type: multiset]:
681   assumes empty: "P {#}"
682   assumes add: "\<And>M x. P M \<Longrightarrow> P (M + {#x#})"
683   shows "P M"
684 proof (induct n \<equiv> "size M" arbitrary: M)
685   case 0 thus "P M" by (simp add: empty)
686 next
687   case (Suc k)
688   obtain N x where "M = N + {#x#}"
689     using `Suc k = size M` [symmetric]
690     using size_eq_Suc_imp_eq_union by fast
691   with Suc add show "P M" by simp
692 qed
694 lemma multi_nonempty_split: "M \<noteq> {#} \<Longrightarrow> \<exists>A a. M = A + {#a#}"
695 by (induct M) auto
697 lemma multiset_cases [cases type]:
698   obtains (empty) "M = {#}"
699     | (add) N x where "M = N + {#x#}"
700   using assms by (induct M) simp_all
702 lemma multi_drop_mem_not_eq: "c \<in># B \<Longrightarrow> B - {#c#} \<noteq> B"
703 by (cases "B = {#}") (auto dest: multi_member_split)
705 lemma multiset_partition: "M = {# x:#M. P x #} + {# x:#M. \<not> P x #}"
706 apply (subst multiset_eq_iff)
707 apply auto
708 done
710 lemma mset_less_size: "(A::'a multiset) < B \<Longrightarrow> size A < size B"
711 proof (induct A arbitrary: B)
712   case (empty M)
713   then have "M \<noteq> {#}" by (simp add: mset_less_empty_nonempty)
714   then obtain M' x where "M = M' + {#x#}"
715     by (blast dest: multi_nonempty_split)
716   then show ?case by simp
717 next
718   case (add S x T)
719   have IH: "\<And>B. S < B \<Longrightarrow> size S < size B" by fact
720   have SxsubT: "S + {#x#} < T" by fact
721   then have "x \<in># T" and "S < T" by (auto dest: mset_less_insertD)
722   then obtain T' where T: "T = T' + {#x#}"
723     by (blast dest: multi_member_split)
724   then have "S < T'" using SxsubT
725     by (blast intro: mset_less_add_bothsides)
726   then have "size S < size T'" using IH by simp
727   then show ?case using T by simp
728 qed
731 subsubsection {* Strong induction and subset induction for multisets *}
733 text {* Well-foundedness of strict subset relation *}
735 lemma wf_less_mset_rel: "wf {(M, N :: 'a multiset). M < N}"
736 apply (rule wf_measure [THEN wf_subset, where f1=size])
737 apply (clarsimp simp: measure_def inv_image_def mset_less_size)
738 done
740 lemma full_multiset_induct [case_names less]:
741 assumes ih: "\<And>B. \<forall>(A::'a multiset). A < B \<longrightarrow> P A \<Longrightarrow> P B"
742 shows "P B"
743 apply (rule wf_less_mset_rel [THEN wf_induct])
744 apply (rule ih, auto)
745 done
747 lemma multi_subset_induct [consumes 2, case_names empty add]:
748 assumes "F \<le> A"
749   and empty: "P {#}"
750   and insert: "\<And>a F. a \<in># A \<Longrightarrow> P F \<Longrightarrow> P (F + {#a#})"
751 shows "P F"
752 proof -
753   from `F \<le> A`
754   show ?thesis
755   proof (induct F)
756     show "P {#}" by fact
757   next
758     fix x F
759     assume P: "F \<le> A \<Longrightarrow> P F" and i: "F + {#x#} \<le> A"
760     show "P (F + {#x#})"
761     proof (rule insert)
762       from i show "x \<in># A" by (auto dest: mset_le_insertD)
763       from i have "F \<le> A" by (auto dest: mset_le_insertD)
764       with P show "P F" .
765     qed
766   qed
767 qed
770 subsection {* The fold combinator *}
772 definition fold :: "('a \<Rightarrow> 'b \<Rightarrow> 'b) \<Rightarrow> 'b \<Rightarrow> 'a multiset \<Rightarrow> 'b"
773 where
774   "fold f s M = Finite_Set.fold (\<lambda>x. f x ^^ count M x) s (set_of M)"
776 lemma fold_mset_empty [simp]:
777   "fold f s {#} = s"
778   by (simp add: fold_def)
780 context comp_fun_commute
781 begin
783 lemma fold_mset_insert:
784   "fold f s (M + {#x#}) = f x (fold f s M)"
785 proof -
786   interpret mset: comp_fun_commute "\<lambda>y. f y ^^ count M y"
787     by (fact comp_fun_commute_funpow)
788   interpret mset_union: comp_fun_commute "\<lambda>y. f y ^^ count (M + {#x#}) y"
789     by (fact comp_fun_commute_funpow)
790   show ?thesis
791   proof (cases "x \<in> set_of M")
792     case False
793     then have *: "count (M + {#x#}) x = 1" by simp
794     from False have "Finite_Set.fold (\<lambda>y. f y ^^ count (M + {#x#}) y) s (set_of M) =
795       Finite_Set.fold (\<lambda>y. f y ^^ count M y) s (set_of M)"
796       by (auto intro!: Finite_Set.fold_cong comp_fun_commute_funpow)
797     with False * show ?thesis
798       by (simp add: fold_def del: count_union)
799   next
800     case True
801     def N \<equiv> "set_of M - {x}"
802     from N_def True have *: "set_of M = insert x N" "x \<notin> N" "finite N" by auto
803     then have "Finite_Set.fold (\<lambda>y. f y ^^ count (M + {#x#}) y) s N =
804       Finite_Set.fold (\<lambda>y. f y ^^ count M y) s N"
805       by (auto intro!: Finite_Set.fold_cong comp_fun_commute_funpow)
806     with * show ?thesis by (simp add: fold_def del: count_union) simp
807   qed
808 qed
810 corollary fold_mset_single [simp]:
811   "fold f s {#x#} = f x s"
812 proof -
813   have "fold f s ({#} + {#x#}) = f x s" by (simp only: fold_mset_insert) simp
814   then show ?thesis by simp
815 qed
817 lemma fold_mset_fun_left_comm:
818   "f x (fold f s M) = fold f (f x s) M"
819   by (induct M) (simp_all add: fold_mset_insert fun_left_comm)
821 lemma fold_mset_union [simp]:
822   "fold f s (M + N) = fold f (fold f s M) N"
823 proof (induct M)
824   case empty then show ?case by simp
825 next
826   case (add M x)
827   have "M + {#x#} + N = (M + N) + {#x#}"
828     by (simp add: ac_simps)
829   with add show ?case by (simp add: fold_mset_insert fold_mset_fun_left_comm)
830 qed
832 lemma fold_mset_fusion:
833   assumes "comp_fun_commute g"
834   shows "(\<And>x y. h (g x y) = f x (h y)) \<Longrightarrow> h (fold g w A) = fold f (h w) A" (is "PROP ?P")
835 proof -
836   interpret comp_fun_commute g by (fact assms)
837   show "PROP ?P" by (induct A) auto
838 qed
840 end
842 text {*
843   A note on code generation: When defining some function containing a
844   subterm @{term "fold F"}, code generation is not automatic. When
845   interpreting locale @{text left_commutative} with @{text F}, the
846   would be code thms for @{const fold} become thms like
847   @{term "fold F z {#} = z"} where @{text F} is not a pattern but
848   contains defined symbols, i.e.\ is not a code thm. Hence a separate
849   constant with its own code thms needs to be introduced for @{text
850   F}. See the image operator below.
851 *}
854 subsection {* Image *}
856 definition image_mset :: "('a \<Rightarrow> 'b) \<Rightarrow> 'a multiset \<Rightarrow> 'b multiset" where
857   "image_mset f = fold (plus o single o f) {#}"
859 lemma comp_fun_commute_mset_image:
860   "comp_fun_commute (plus o single o f)"
861 proof
862 qed (simp add: ac_simps fun_eq_iff)
864 lemma image_mset_empty [simp]: "image_mset f {#} = {#}"
865   by (simp add: image_mset_def)
867 lemma image_mset_single [simp]: "image_mset f {#x#} = {#f x#}"
868 proof -
869   interpret comp_fun_commute "plus o single o f"
870     by (fact comp_fun_commute_mset_image)
871   show ?thesis by (simp add: image_mset_def)
872 qed
874 lemma image_mset_union [simp]:
875   "image_mset f (M + N) = image_mset f M + image_mset f N"
876 proof -
877   interpret comp_fun_commute "plus o single o f"
878     by (fact comp_fun_commute_mset_image)
879   show ?thesis by (induct N) (simp_all add: image_mset_def ac_simps)
880 qed
882 corollary image_mset_insert:
883   "image_mset f (M + {#a#}) = image_mset f M + {#f a#}"
884   by simp
886 lemma set_of_image_mset [simp]:
887   "set_of (image_mset f M) = image f (set_of M)"
888   by (induct M) simp_all
890 lemma size_image_mset [simp]:
891   "size (image_mset f M) = size M"
892   by (induct M) simp_all
894 lemma image_mset_is_empty_iff [simp]:
895   "image_mset f M = {#} \<longleftrightarrow> M = {#}"
896   by (cases M) auto
898 syntax
899   "_comprehension1_mset" :: "'a \<Rightarrow> 'b \<Rightarrow> 'b multiset \<Rightarrow> 'a multiset"
900       ("({#_/. _ :# _#})")
901 translations
902   "{#e. x:#M#}" == "CONST image_mset (%x. e) M"
904 syntax (xsymbols)
905   "_comprehension2_mset" :: "'a \<Rightarrow> 'b \<Rightarrow> 'b multiset \<Rightarrow> 'a multiset"
906       ("({#_/. _ \<in># _#})")
907 translations
908   "{#e. x \<in># M#}" == "CONST image_mset (\<lambda>x. e) M"
910 syntax
911   "_comprehension3_mset" :: "'a \<Rightarrow> 'b \<Rightarrow> 'b multiset \<Rightarrow> bool \<Rightarrow> 'a multiset"
912       ("({#_/ | _ :# _./ _#})")
913 translations
914   "{#e | x:#M. P#}" => "{#e. x :# {# x:#M. P#}#}"
916 syntax
917   "_comprehension4_mset" :: "'a \<Rightarrow> 'b \<Rightarrow> 'b multiset \<Rightarrow> bool \<Rightarrow> 'a multiset"
918       ("({#_/ | _ \<in># _./ _#})")
919 translations
920   "{#e | x\<in>#M. P#}" => "{#e. x \<in># {# x\<in>#M. P#}#}"
922 text {*
923   This allows to write not just filters like @{term "{#x:#M. x<c#}"}
924   but also images like @{term "{#x+x. x:#M #}"} and @{term [source]
925   "{#x+x|x:#M. x<c#}"}, where the latter is currently displayed as
926   @{term "{#x+x|x:#M. x<c#}"}.
927 *}
929 lemma in_image_mset: "y \<in># {#f x. x \<in># M#} \<longleftrightarrow> y \<in> f ` set_of M"
930   by (metis mem_set_of_iff set_of_image_mset)
932 functor image_mset: image_mset
933 proof -
934   fix f g show "image_mset f \<circ> image_mset g = image_mset (f \<circ> g)"
935   proof
936     fix A
937     show "(image_mset f \<circ> image_mset g) A = image_mset (f \<circ> g) A"
938       by (induct A) simp_all
939   qed
940   show "image_mset id = id"
941   proof
942     fix A
943     show "image_mset id A = id A"
944       by (induct A) simp_all
945   qed
946 qed
948 declare
949   image_mset.id [simp]
950   image_mset.identity [simp]
952 lemma image_mset_id[simp]: "image_mset id x = x"
953   unfolding id_def by auto
955 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#}"
956   by (induct M) auto
958 lemma image_mset_cong_pair:
959   "(\<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#}"
960   by (metis image_mset_cong split_cong)
963 subsection {* Further conversions *}
965 primrec multiset_of :: "'a list \<Rightarrow> 'a multiset" where
966   "multiset_of [] = {#}" |
967   "multiset_of (a # x) = multiset_of x + {# a #}"
969 lemma in_multiset_in_set:
970   "x \<in># multiset_of xs \<longleftrightarrow> x \<in> set xs"
971   by (induct xs) simp_all
973 lemma count_multiset_of:
974   "count (multiset_of xs) x = length (filter (\<lambda>y. x = y) xs)"
975   by (induct xs) simp_all
977 lemma multiset_of_zero_iff[simp]: "(multiset_of x = {#}) = (x = [])"
978   by (induct x) auto
980 lemma multiset_of_zero_iff_right[simp]: "({#} = multiset_of x) = (x = [])"
981 by (induct x) auto
983 lemma set_of_multiset_of[simp]: "set_of (multiset_of x) = set x"
984 by (induct x) auto
986 lemma mem_set_multiset_eq: "x \<in> set xs = (x :# multiset_of xs)"
987 by (induct xs) auto
989 lemma size_multiset_of [simp]: "size (multiset_of xs) = length xs"
990   by (induct xs) simp_all
992 lemma multiset_of_append [simp]:
993   "multiset_of (xs @ ys) = multiset_of xs + multiset_of ys"
994   by (induct xs arbitrary: ys) (auto simp: ac_simps)
996 lemma multiset_of_filter:
997   "multiset_of (filter P xs) = {#x :# multiset_of xs. P x #}"
998   by (induct xs) simp_all
1000 lemma multiset_of_rev [simp]:
1001   "multiset_of (rev xs) = multiset_of xs"
1002   by (induct xs) simp_all
1004 lemma surj_multiset_of: "surj multiset_of"
1005 apply (unfold surj_def)
1006 apply (rule allI)
1007 apply (rule_tac M = y in multiset_induct)
1008  apply auto
1009 apply (rule_tac x = "x # xa" in exI)
1010 apply auto
1011 done
1013 lemma set_count_greater_0: "set x = {a. count (multiset_of x) a > 0}"
1014 by (induct x) auto
1016 lemma distinct_count_atmost_1:
1017   "distinct x = (! a. count (multiset_of x) a = (if a \<in> set x then 1 else 0))"
1018 apply (induct x, simp, rule iffI, simp_all)
1019 apply (rename_tac a b)
1020 apply (rule conjI)
1021 apply (simp_all add: set_of_multiset_of [THEN sym] del: set_of_multiset_of)
1022 apply (erule_tac x = a in allE, simp, clarify)
1023 apply (erule_tac x = aa in allE, simp)
1024 done
1026 lemma multiset_of_eq_setD:
1027   "multiset_of xs = multiset_of ys \<Longrightarrow> set xs = set ys"
1028 by (rule) (auto simp add:multiset_eq_iff set_count_greater_0)
1030 lemma set_eq_iff_multiset_of_eq_distinct:
1031   "distinct x \<Longrightarrow> distinct y \<Longrightarrow>
1032     (set x = set y) = (multiset_of x = multiset_of y)"
1033 by (auto simp: multiset_eq_iff distinct_count_atmost_1)
1035 lemma set_eq_iff_multiset_of_remdups_eq:
1036    "(set x = set y) = (multiset_of (remdups x) = multiset_of (remdups y))"
1037 apply (rule iffI)
1038 apply (simp add: set_eq_iff_multiset_of_eq_distinct[THEN iffD1])
1039 apply (drule distinct_remdups [THEN distinct_remdups
1040       [THEN set_eq_iff_multiset_of_eq_distinct [THEN iffD2]]])
1041 apply simp
1042 done
1044 lemma multiset_of_compl_union [simp]:
1045   "multiset_of [x\<leftarrow>xs. P x] + multiset_of [x\<leftarrow>xs. \<not>P x] = multiset_of xs"
1046   by (induct xs) (auto simp: ac_simps)
1048 lemma count_multiset_of_length_filter:
1049   "count (multiset_of xs) x = length (filter (\<lambda>y. x = y) xs)"
1050   by (induct xs) auto
1052 lemma nth_mem_multiset_of: "i < length ls \<Longrightarrow> (ls ! i) :# multiset_of ls"
1053 apply (induct ls arbitrary: i)
1054  apply simp
1055 apply (case_tac i)
1056  apply auto
1057 done
1059 lemma multiset_of_remove1[simp]:
1060   "multiset_of (remove1 a xs) = multiset_of xs - {#a#}"
1061 by (induct xs) (auto simp add: multiset_eq_iff)
1063 lemma multiset_of_eq_length:
1064   assumes "multiset_of xs = multiset_of ys"
1065   shows "length xs = length ys"
1066   using assms by (metis size_multiset_of)
1068 lemma multiset_of_eq_length_filter:
1069   assumes "multiset_of xs = multiset_of ys"
1070   shows "length (filter (\<lambda>x. z = x) xs) = length (filter (\<lambda>y. z = y) ys)"
1071   using assms by (metis count_multiset_of)
1073 lemma fold_multiset_equiv:
1074   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"
1075     and equiv: "multiset_of xs = multiset_of ys"
1076   shows "List.fold f xs = List.fold f ys"
1077 using f equiv [symmetric]
1078 proof (induct xs arbitrary: ys)
1079   case Nil then show ?case by simp
1080 next
1081   case (Cons x xs)
1082   then have *: "set ys = set (x # xs)" by (blast dest: multiset_of_eq_setD)
1083   have "\<And>x y. x \<in> set ys \<Longrightarrow> y \<in> set ys \<Longrightarrow> f x \<circ> f y = f y \<circ> f x"
1084     by (rule Cons.prems(1)) (simp_all add: *)
1085   moreover from * have "x \<in> set ys" by simp
1086   ultimately have "List.fold f ys = List.fold f (remove1 x ys) \<circ> f x" by (fact fold_remove1_split)
1087   moreover from Cons.prems have "List.fold f xs = List.fold f (remove1 x ys)" by (auto intro: Cons.hyps)
1088   ultimately show ?case by simp
1089 qed
1091 lemma multiset_of_insort [simp]:
1092   "multiset_of (insort x xs) = multiset_of xs + {#x#}"
1093   by (induct xs) (simp_all add: ac_simps)
1095 lemma multiset_of_map:
1096   "multiset_of (map f xs) = image_mset f (multiset_of xs)"
1097   by (induct xs) simp_all
1099 definition multiset_of_set :: "'a set \<Rightarrow> 'a multiset"
1100 where
1101   "multiset_of_set = folding.F (\<lambda>x M. {#x#} + M) {#}"
1103 interpretation multiset_of_set!: folding "\<lambda>x M. {#x#} + M" "{#}"
1104 where
1105   "folding.F (\<lambda>x M. {#x#} + M) {#} = multiset_of_set"
1106 proof -
1107   interpret comp_fun_commute "\<lambda>x M. {#x#} + M" by default (simp add: fun_eq_iff ac_simps)
1108   show "folding (\<lambda>x M. {#x#} + M)" by default (fact comp_fun_commute)
1109   from multiset_of_set_def show "folding.F (\<lambda>x M. {#x#} + M) {#} = multiset_of_set" ..
1110 qed
1112 lemma count_multiset_of_set [simp]:
1113   "finite A \<Longrightarrow> x \<in> A \<Longrightarrow> count (multiset_of_set A) x = 1" (is "PROP ?P")
1114   "\<not> finite A \<Longrightarrow> count (multiset_of_set A) x = 0" (is "PROP ?Q")
1115   "x \<notin> A \<Longrightarrow> count (multiset_of_set A) x = 0" (is "PROP ?R")
1116 proof -
1117   { fix A
1118     assume "x \<notin> A"
1119     have "count (multiset_of_set A) x = 0"
1120     proof (cases "finite A")
1121       case False then show ?thesis by simp
1122     next
1123       case True from True `x \<notin> A` show ?thesis by (induct A) auto
1124     qed
1125   } note * = this
1126   then show "PROP ?P" "PROP ?Q" "PROP ?R"
1127   by (auto elim!: Set.set_insert)
1128 qed -- {* TODO: maybe define @{const multiset_of_set} also in terms of @{const Abs_multiset} *}
1130 lemma elem_multiset_of_set[simp, intro]: "finite A \<Longrightarrow> x \<in># multiset_of_set A \<longleftrightarrow> x \<in> A"
1131   by (induct A rule: finite_induct) simp_all
1133 context linorder
1134 begin
1136 definition sorted_list_of_multiset :: "'a multiset \<Rightarrow> 'a list"
1137 where
1138   "sorted_list_of_multiset M = fold insort [] M"
1140 lemma sorted_list_of_multiset_empty [simp]:
1141   "sorted_list_of_multiset {#} = []"
1142   by (simp add: sorted_list_of_multiset_def)
1144 lemma sorted_list_of_multiset_singleton [simp]:
1145   "sorted_list_of_multiset {#x#} = [x]"
1146 proof -
1147   interpret comp_fun_commute insort by (fact comp_fun_commute_insort)
1148   show ?thesis by (simp add: sorted_list_of_multiset_def)
1149 qed
1151 lemma sorted_list_of_multiset_insert [simp]:
1152   "sorted_list_of_multiset (M + {#x#}) = List.insort x (sorted_list_of_multiset M)"
1153 proof -
1154   interpret comp_fun_commute insort by (fact comp_fun_commute_insort)
1155   show ?thesis by (simp add: sorted_list_of_multiset_def)
1156 qed
1158 end
1160 lemma multiset_of_sorted_list_of_multiset [simp]:
1161   "multiset_of (sorted_list_of_multiset M) = M"
1162   by (induct M) simp_all
1164 lemma sorted_list_of_multiset_multiset_of [simp]:
1165   "sorted_list_of_multiset (multiset_of xs) = sort xs"
1166   by (induct xs) simp_all
1168 lemma finite_set_of_multiset_of_set:
1169   assumes "finite A"
1170   shows "set_of (multiset_of_set A) = A"
1171   using assms by (induct A) simp_all
1173 lemma infinite_set_of_multiset_of_set:
1174   assumes "\<not> finite A"
1175   shows "set_of (multiset_of_set A) = {}"
1176   using assms by simp
1178 lemma set_sorted_list_of_multiset [simp]:
1179   "set (sorted_list_of_multiset M) = set_of M"
1180   by (induct M) (simp_all add: set_insort)
1182 lemma sorted_list_of_multiset_of_set [simp]:
1183   "sorted_list_of_multiset (multiset_of_set A) = sorted_list_of_set A"
1184   by (cases "finite A") (induct A rule: finite_induct, simp_all add: ac_simps)
1187 subsection {* Big operators *}
1189 no_notation times (infixl "*" 70)
1190 no_notation Groups.one ("1")
1192 locale comm_monoid_mset = comm_monoid
1193 begin
1195 definition F :: "'a multiset \<Rightarrow> 'a"
1196 where
1197   eq_fold: "F M = Multiset.fold f 1 M"
1199 lemma empty [simp]:
1200   "F {#} = 1"
1201   by (simp add: eq_fold)
1203 lemma singleton [simp]:
1204   "F {#x#} = x"
1205 proof -
1206   interpret comp_fun_commute
1207     by default (simp add: fun_eq_iff left_commute)
1208   show ?thesis by (simp add: eq_fold)
1209 qed
1211 lemma union [simp]:
1212   "F (M + N) = F M * F N"
1213 proof -
1214   interpret comp_fun_commute f
1215     by default (simp add: fun_eq_iff left_commute)
1216   show ?thesis by (induct N) (simp_all add: left_commute eq_fold)
1217 qed
1219 end
1221 lemma comp_fun_commute_plus_mset[simp]: "comp_fun_commute (op + \<Colon> 'a multiset \<Rightarrow> _ \<Rightarrow> _)"
1222   by default (simp add: add_ac comp_def)
1224 declare comp_fun_commute.fold_mset_insert[OF comp_fun_commute_plus_mset, simp]
1226 lemma in_mset_fold_plus_iff[iff]: "x \<in># Multiset.fold (op +) M NN \<longleftrightarrow> x \<in># M \<or> (\<exists>N. N \<in># NN \<and> x \<in># N)"
1227   by (induct NN) auto
1229 notation times (infixl "*" 70)
1230 notation Groups.one ("1")
1233 begin
1235 definition msetsum :: "'a multiset \<Rightarrow> 'a"
1236 where
1237   "msetsum = comm_monoid_mset.F plus 0"
1239 sublocale msetsum!: comm_monoid_mset plus 0
1240 where
1241   "comm_monoid_mset.F plus 0 = msetsum"
1242 proof -
1243   show "comm_monoid_mset plus 0" ..
1244   from msetsum_def show "comm_monoid_mset.F plus 0 = msetsum" ..
1245 qed
1247 lemma setsum_unfold_msetsum:
1248   "setsum f A = msetsum (image_mset f (multiset_of_set A))"
1249   by (cases "finite A") (induct A rule: finite_induct, simp_all)
1251 end
1253 lemma msetsum_diff:
1254   fixes M N :: "('a \<Colon> ordered_cancel_comm_monoid_diff) multiset"
1255   shows "N \<le> M \<Longrightarrow> msetsum (M - N) = msetsum M - msetsum N"
1258 abbreviation Union_mset :: "'a multiset multiset \<Rightarrow> 'a multiset" where
1259   "Union_mset MM \<equiv> msetsum MM"
1261 notation (xsymbols) Union_mset ("\<Union>#_"  900)
1263 lemma set_of_Union_mset[simp]: "set_of (\<Union># MM) = (\<Union>M \<in> set_of MM. set_of M)"
1264   by (induct MM) auto
1266 lemma in_Union_mset_iff[iff]: "x \<in># \<Union># MM \<longleftrightarrow> (\<exists>M. M \<in># MM \<and> x \<in># M)"
1267   by (induct MM) auto
1269 syntax
1270   "_msetsum_image" :: "pttrn \<Rightarrow> 'b set \<Rightarrow> 'a \<Rightarrow> 'a::comm_monoid_add"
1271       ("(3SUM _:#_. _)" [0, 51, 10] 10)
1273 syntax (xsymbols)
1274   "_msetsum_image" :: "pttrn \<Rightarrow> 'b set \<Rightarrow> 'a \<Rightarrow> 'a::comm_monoid_add"
1275       ("(3\<Sum>_\<in>#_. _)" [0, 51, 10] 10)
1277 syntax (HTML output)
1278   "_msetsum_image" :: "pttrn \<Rightarrow> 'b set \<Rightarrow> 'a \<Rightarrow> 'a::comm_monoid_add"
1279       ("(3\<Sum>_\<in>#_. _)" [0, 51, 10] 10)
1281 translations
1282   "SUM i :# A. b" == "CONST msetsum (CONST image_mset (\<lambda>i. b) A)"
1284 context comm_monoid_mult
1285 begin
1287 definition msetprod :: "'a multiset \<Rightarrow> 'a"
1288 where
1289   "msetprod = comm_monoid_mset.F times 1"
1291 sublocale msetprod!: comm_monoid_mset times 1
1292 where
1293   "comm_monoid_mset.F times 1 = msetprod"
1294 proof -
1295   show "comm_monoid_mset times 1" ..
1296   from msetprod_def show "comm_monoid_mset.F times 1 = msetprod" ..
1297 qed
1299 lemma msetprod_empty:
1300   "msetprod {#} = 1"
1301   by (fact msetprod.empty)
1303 lemma msetprod_singleton:
1304   "msetprod {#x#} = x"
1305   by (fact msetprod.singleton)
1307 lemma msetprod_Un:
1308   "msetprod (A + B) = msetprod A * msetprod B"
1309   by (fact msetprod.union)
1311 lemma setprod_unfold_msetprod:
1312   "setprod f A = msetprod (image_mset f (multiset_of_set A))"
1313   by (cases "finite A") (induct A rule: finite_induct, simp_all)
1315 lemma msetprod_multiplicity:
1316   "msetprod M = setprod (\<lambda>x. x ^ count M x) (set_of M)"
1317   by (simp add: Multiset.fold_def setprod.eq_fold msetprod.eq_fold funpow_times_power comp_def)
1319 end
1321 syntax
1322   "_msetprod_image" :: "pttrn \<Rightarrow> 'b set \<Rightarrow> 'a \<Rightarrow> 'a::comm_monoid_mult"
1323       ("(3PROD _:#_. _)" [0, 51, 10] 10)
1325 syntax (xsymbols)
1326   "_msetprod_image" :: "pttrn \<Rightarrow> 'b set \<Rightarrow> 'a \<Rightarrow> 'a::comm_monoid_mult"
1327       ("(3\<Prod>_\<in>#_. _)" [0, 51, 10] 10)
1329 syntax (HTML output)
1330   "_msetprod_image" :: "pttrn \<Rightarrow> 'b set \<Rightarrow> 'a \<Rightarrow> 'a::comm_monoid_mult"
1331       ("(3\<Prod>_\<in>#_. _)" [0, 51, 10] 10)
1333 translations
1334   "PROD i :# A. b" == "CONST msetprod (CONST image_mset (\<lambda>i. b) A)"
1336 lemma (in comm_semiring_1) dvd_msetprod:
1337   assumes "x \<in># A"
1338   shows "x dvd msetprod A"
1339 proof -
1340   from assms have "A = (A - {#x#}) + {#x#}" by simp
1341   then obtain B where "A = B + {#x#}" ..
1342   then show ?thesis by simp
1343 qed
1346 subsection {* Cardinality *}
1348 definition mcard :: "'a multiset \<Rightarrow> nat"
1349 where
1350   "mcard = msetsum \<circ> image_mset (\<lambda>_. 1)"
1352 lemma mcard_empty [simp]:
1353   "mcard {#} = 0"
1354   by (simp add: mcard_def)
1356 lemma mcard_singleton [simp]:
1357   "mcard {#a#} = Suc 0"
1358   by (simp add: mcard_def)
1360 lemma mcard_plus [simp]:
1361   "mcard (M + N) = mcard M + mcard N"
1362   by (simp add: mcard_def)
1364 lemma mcard_empty_iff [simp]:
1365   "mcard M = 0 \<longleftrightarrow> M = {#}"
1366   by (induct M) simp_all
1368 lemma mcard_unfold_setsum:
1369   "mcard M = setsum (count M) (set_of M)"
1370 proof (induct M)
1371   case empty then show ?case by simp
1372 next
1373   case (add M x) then show ?case
1374     by (cases "x \<in> set_of M")
1375       (simp_all del: mem_set_of_iff add: setsum.distrib setsum.delta' insert_absorb, simp)
1376 qed
1378 lemma size_eq_mcard:
1379   "size = mcard"
1380   by (simp add: fun_eq_iff size_multiset_overloaded_eq mcard_unfold_setsum)
1382 lemma mcard_multiset_of:
1383   "mcard (multiset_of xs) = length xs"
1384   by (induct xs) simp_all
1386 lemma mcard_mono: assumes "A \<le> B"
1387   shows "mcard A \<le> mcard B"
1388 proof -
1389   from assms[unfolded mset_le_exists_conv]
1390   obtain C where B: "B = A + C" by auto
1391   show ?thesis unfolding B by (induct C, auto)
1392 qed
1394 lemma mcard_filter_lesseq[simp]: "mcard (Multiset.filter f M) \<le> mcard M"
1395   by (rule mcard_mono[OF multiset_filter_subset])
1397 lemma mcard_1_singleton:
1398   assumes card: "mcard AA = 1"
1399   shows "\<exists>A. AA = {#A#}"
1400   using card by (cases AA) auto
1402 lemma mcard_Diff_subset:
1403   assumes "M \<le> M'"
1404   shows "mcard (M' - M) = mcard M' - mcard M"
1405   by (metis add_diff_cancel_left' assms mcard_plus mset_le_exists_conv)
1408 subsection {* Replicate operation *}
1410 definition replicate_mset :: "nat \<Rightarrow> 'a \<Rightarrow> 'a multiset" where
1411   "replicate_mset n x = ((op + {#x#}) ^^ n) {#}"
1413 lemma replicate_mset_0[simp]: "replicate_mset 0 x = {#}"
1414   unfolding replicate_mset_def by simp
1416 lemma replicate_mset_Suc[simp]: "replicate_mset (Suc n) x = replicate_mset n x + {#x#}"
1417   unfolding replicate_mset_def by (induct n) (auto intro: add.commute)
1419 lemma in_replicate_mset[simp]: "x \<in># replicate_mset n y \<longleftrightarrow> n > 0 \<and> x = y"
1420   unfolding replicate_mset_def by (induct n) simp_all
1422 lemma count_replicate_mset[simp]: "count (replicate_mset n x) y = (if y = x then n else 0)"
1423   unfolding replicate_mset_def by (induct n) simp_all
1425 lemma set_of_replicate_mset_subset[simp]: "set_of (replicate_mset n x) = (if n = 0 then {} else {x})"
1426   by (auto split: if_splits)
1428 lemma mcard_replicate_mset[simp]: "mcard (replicate_mset n M) = n"
1429   by (induct n, simp_all)
1431 lemma count_le_replicate_mset_le: "n \<le> count M x \<longleftrightarrow> replicate_mset n x \<le> M"
1432   by (auto simp add: assms mset_less_eqI) (metis count_replicate_mset less_eq_multiset.rep_eq)
1434 lemma filter_eq_replicate_mset: "{#y \<in># D. y = x#} = replicate_mset (count D x) x"
1435   by (induct D) simp_all
1438 subsection {* Alternative representations *}
1440 subsubsection {* Lists *}
1442 context linorder
1443 begin
1445 lemma multiset_of_insort [simp]:
1446   "multiset_of (insort_key k x xs) = {#x#} + multiset_of xs"
1447   by (induct xs) (simp_all add: ac_simps)
1449 lemma multiset_of_sort [simp]:
1450   "multiset_of (sort_key k xs) = multiset_of xs"
1451   by (induct xs) (simp_all add: ac_simps)
1453 text {*
1454   This lemma shows which properties suffice to show that a function
1455   @{text "f"} with @{text "f xs = ys"} behaves like sort.
1456 *}
1458 lemma properties_for_sort_key:
1459   assumes "multiset_of ys = multiset_of xs"
1460   and "\<And>k. k \<in> set ys \<Longrightarrow> filter (\<lambda>x. f k = f x) ys = filter (\<lambda>x. f k = f x) xs"
1461   and "sorted (map f ys)"
1462   shows "sort_key f xs = ys"
1463 using assms
1464 proof (induct xs arbitrary: ys)
1465   case Nil then show ?case by simp
1466 next
1467   case (Cons x xs)
1468   from Cons.prems(2) have
1469     "\<forall>k \<in> set ys. filter (\<lambda>x. f k = f x) (remove1 x ys) = filter (\<lambda>x. f k = f x) xs"
1470     by (simp add: filter_remove1)
1471   with Cons.prems have "sort_key f xs = remove1 x ys"
1472     by (auto intro!: Cons.hyps simp add: sorted_map_remove1)
1473   moreover from Cons.prems have "x \<in> set ys"
1474     by (auto simp add: mem_set_multiset_eq intro!: ccontr)
1475   ultimately show ?case using Cons.prems by (simp add: insort_key_remove1)
1476 qed
1478 lemma properties_for_sort:
1479   assumes multiset: "multiset_of ys = multiset_of xs"
1480   and "sorted ys"
1481   shows "sort xs = ys"
1482 proof (rule properties_for_sort_key)
1483   from multiset show "multiset_of ys = multiset_of xs" .
1484   from `sorted ys` show "sorted (map (\<lambda>x. x) ys)" by simp
1485   from multiset have "\<And>k. length (filter (\<lambda>y. k = y) ys) = length (filter (\<lambda>x. k = x) xs)"
1486     by (rule multiset_of_eq_length_filter)
1487   then have "\<And>k. replicate (length (filter (\<lambda>y. k = y) ys)) k = replicate (length (filter (\<lambda>x. k = x) xs)) k"
1488     by simp
1489   then show "\<And>k. k \<in> set ys \<Longrightarrow> filter (\<lambda>y. k = y) ys = filter (\<lambda>x. k = x) xs"
1490     by (simp add: replicate_length_filter)
1491 qed
1493 lemma sort_key_by_quicksort:
1494   "sort_key f xs = sort_key f [x\<leftarrow>xs. f x < f (xs ! (length xs div 2))]
1495     @ [x\<leftarrow>xs. f x = f (xs ! (length xs div 2))]
1496     @ sort_key f [x\<leftarrow>xs. f x > f (xs ! (length xs div 2))]" (is "sort_key f ?lhs = ?rhs")
1497 proof (rule properties_for_sort_key)
1498   show "multiset_of ?rhs = multiset_of ?lhs"
1499     by (rule multiset_eqI) (auto simp add: multiset_of_filter)
1500 next
1501   show "sorted (map f ?rhs)"
1502     by (auto simp add: sorted_append intro: sorted_map_same)
1503 next
1504   fix l
1505   assume "l \<in> set ?rhs"
1506   let ?pivot = "f (xs ! (length xs div 2))"
1507   have *: "\<And>x. f l = f x \<longleftrightarrow> f x = f l" by auto
1508   have "[x \<leftarrow> sort_key f xs . f x = f l] = [x \<leftarrow> xs. f x = f l]"
1509     unfolding filter_sort by (rule properties_for_sort_key) (auto intro: sorted_map_same)
1510   with * have **: "[x \<leftarrow> sort_key f xs . f l = f x] = [x \<leftarrow> xs. f l = f x]" by simp
1511   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
1512   then have "\<And>P. [x \<leftarrow> sort_key f xs . P (f x) ?pivot \<and> f l = f x] =
1513     [x \<leftarrow> sort_key f xs. P (f l) ?pivot \<and> f l = f x]" by simp
1514   note *** = this [of "op <"] this [of "op >"] this [of "op ="]
1515   show "[x \<leftarrow> ?rhs. f l = f x] = [x \<leftarrow> ?lhs. f l = f x]"
1516   proof (cases "f l" ?pivot rule: linorder_cases)
1517     case less
1518     then have "f l \<noteq> ?pivot" and "\<not> f l > ?pivot" by auto
1519     with less show ?thesis
1520       by (simp add: filter_sort [symmetric] ** ***)
1521   next
1522     case equal then show ?thesis
1523       by (simp add: * less_le)
1524   next
1525     case greater
1526     then have "f l \<noteq> ?pivot" and "\<not> f l < ?pivot" by auto
1527     with greater show ?thesis
1528       by (simp add: filter_sort [symmetric] ** ***)
1529   qed
1530 qed
1532 lemma sort_by_quicksort:
1533   "sort xs = sort [x\<leftarrow>xs. x < xs ! (length xs div 2)]
1534     @ [x\<leftarrow>xs. x = xs ! (length xs div 2)]
1535     @ sort [x\<leftarrow>xs. x > xs ! (length xs div 2)]" (is "sort ?lhs = ?rhs")
1536   using sort_key_by_quicksort [of "\<lambda>x. x", symmetric] by simp
1538 text {* A stable parametrized quicksort *}
1540 definition part :: "('b \<Rightarrow> 'a) \<Rightarrow> 'a \<Rightarrow> 'b list \<Rightarrow> 'b list \<times> 'b list \<times> 'b list" where
1541   "part f pivot xs = ([x \<leftarrow> xs. f x < pivot], [x \<leftarrow> xs. f x = pivot], [x \<leftarrow> xs. pivot < f x])"
1543 lemma part_code [code]:
1544   "part f pivot [] = ([], [], [])"
1545   "part f pivot (x # xs) = (let (lts, eqs, gts) = part f pivot xs; x' = f x in
1546      if x' < pivot then (x # lts, eqs, gts)
1547      else if x' > pivot then (lts, eqs, x # gts)
1548      else (lts, x # eqs, gts))"
1549   by (auto simp add: part_def Let_def split_def)
1551 lemma sort_key_by_quicksort_code [code]:
1552   "sort_key f xs = (case xs of [] \<Rightarrow> []
1553     | [x] \<Rightarrow> xs
1554     | [x, y] \<Rightarrow> (if f x \<le> f y then xs else [y, x])
1555     | _ \<Rightarrow> (let (lts, eqs, gts) = part f (f (xs ! (length xs div 2))) xs
1556        in sort_key f lts @ eqs @ sort_key f gts))"
1557 proof (cases xs)
1558   case Nil then show ?thesis by simp
1559 next
1560   case (Cons _ ys) note hyps = Cons show ?thesis
1561   proof (cases ys)
1562     case Nil with hyps show ?thesis by simp
1563   next
1564     case (Cons _ zs) note hyps = hyps Cons show ?thesis
1565     proof (cases zs)
1566       case Nil with hyps show ?thesis by auto
1567     next
1568       case Cons
1569       from sort_key_by_quicksort [of f xs]
1570       have "sort_key f xs = (let (lts, eqs, gts) = part f (f (xs ! (length xs div 2))) xs
1571         in sort_key f lts @ eqs @ sort_key f gts)"
1572       by (simp only: split_def Let_def part_def fst_conv snd_conv)
1573       with hyps Cons show ?thesis by (simp only: list.cases)
1574     qed
1575   qed
1576 qed
1578 end
1580 hide_const (open) part
1582 lemma multiset_of_remdups_le: "multiset_of (remdups xs) \<le> multiset_of xs"
1583   by (induct xs) (auto intro: order_trans)
1585 lemma multiset_of_update:
1586   "i < length ls \<Longrightarrow> multiset_of (ls[i := v]) = multiset_of ls - {#ls ! i#} + {#v#}"
1587 proof (induct ls arbitrary: i)
1588   case Nil then show ?case by simp
1589 next
1590   case (Cons x xs)
1591   show ?case
1592   proof (cases i)
1593     case 0 then show ?thesis by simp
1594   next
1595     case (Suc i')
1596     with Cons show ?thesis
1597       apply simp
1598       apply (subst add.assoc)
1599       apply (subst add.commute [of "{#v#}" "{#x#}"])
1600       apply (subst add.assoc [symmetric])
1601       apply simp
1602       apply (rule mset_le_multiset_union_diff_commute)
1603       apply (simp add: mset_le_single nth_mem_multiset_of)
1604       done
1605   qed
1606 qed
1608 lemma multiset_of_swap:
1609   "i < length ls \<Longrightarrow> j < length ls \<Longrightarrow>
1610     multiset_of (ls[j := ls ! i, i := ls ! j]) = multiset_of ls"
1611   by (cases "i = j") (simp_all add: multiset_of_update nth_mem_multiset_of)
1614 subsection {* The multiset order *}
1616 subsubsection {* Well-foundedness *}
1618 definition mult1 :: "('a \<times> 'a) set => ('a multiset \<times> 'a multiset) set" where
1619   "mult1 r = {(N, M). \<exists>a M0 K. M = M0 + {#a#} \<and> N = M0 + K \<and>
1620       (\<forall>b. b :# K --> (b, a) \<in> r)}"
1622 definition mult :: "('a \<times> 'a) set => ('a multiset \<times> 'a multiset) set" where
1623   "mult r = (mult1 r)\<^sup>+"
1625 lemma not_less_empty [iff]: "(M, {#}) \<notin> mult1 r"
1626 by (simp add: mult1_def)
1628 lemma less_add: "(N, M0 + {#a#}) \<in> mult1 r ==>
1629     (\<exists>M. (M, M0) \<in> mult1 r \<and> N = M + {#a#}) \<or>
1630     (\<exists>K. (\<forall>b. b :# K --> (b, a) \<in> r) \<and> N = M0 + K)"
1631   (is "_ \<Longrightarrow> ?case1 (mult1 r) \<or> ?case2")
1632 proof (unfold mult1_def)
1633   let ?r = "\<lambda>K a. \<forall>b. b :# K --> (b, a) \<in> r"
1634   let ?R = "\<lambda>N M. \<exists>a M0 K. M = M0 + {#a#} \<and> N = M0 + K \<and> ?r K a"
1635   let ?case1 = "?case1 {(N, M). ?R N M}"
1637   assume "(N, M0 + {#a#}) \<in> {(N, M). ?R N M}"
1638   then have "\<exists>a' M0' K.
1639       M0 + {#a#} = M0' + {#a'#} \<and> N = M0' + K \<and> ?r K a'" by simp
1640   then show "?case1 \<or> ?case2"
1641   proof (elim exE conjE)
1642     fix a' M0' K
1643     assume N: "N = M0' + K" and r: "?r K a'"
1644     assume "M0 + {#a#} = M0' + {#a'#}"
1645     then have "M0 = M0' \<and> a = a' \<or>
1646         (\<exists>K'. M0 = K' + {#a'#} \<and> M0' = K' + {#a#})"
1647       by (simp only: add_eq_conv_ex)
1648     then show ?thesis
1649     proof (elim disjE conjE exE)
1650       assume "M0 = M0'" "a = a'"
1651       with N r have "?r K a \<and> N = M0 + K" by simp
1652       then have ?case2 .. then show ?thesis ..
1653     next
1654       fix K'
1655       assume "M0' = K' + {#a#}"
1656       with N have n: "N = K' + K + {#a#}" by (simp add: ac_simps)
1658       assume "M0 = K' + {#a'#}"
1659       with r have "?R (K' + K) M0" by blast
1660       with n have ?case1 by simp then show ?thesis ..
1661     qed
1662   qed
1663 qed
1665 lemma all_accessible: "wf r ==> \<forall>M. M \<in> Wellfounded.acc (mult1 r)"
1666 proof
1667   let ?R = "mult1 r"
1668   let ?W = "Wellfounded.acc ?R"
1669   {
1670     fix M M0 a
1671     assume M0: "M0 \<in> ?W"
1672       and wf_hyp: "!!b. (b, a) \<in> r ==> (\<forall>M \<in> ?W. M + {#b#} \<in> ?W)"
1673       and acc_hyp: "\<forall>M. (M, M0) \<in> ?R --> M + {#a#} \<in> ?W"
1674     have "M0 + {#a#} \<in> ?W"
1675     proof (rule accI [of "M0 + {#a#}"])
1676       fix N
1677       assume "(N, M0 + {#a#}) \<in> ?R"
1678       then have "((\<exists>M. (M, M0) \<in> ?R \<and> N = M + {#a#}) \<or>
1679           (\<exists>K. (\<forall>b. b :# K --> (b, a) \<in> r) \<and> N = M0 + K))"
1680         by (rule less_add)
1681       then show "N \<in> ?W"
1682       proof (elim exE disjE conjE)
1683         fix M assume "(M, M0) \<in> ?R" and N: "N = M + {#a#}"
1684         from acc_hyp have "(M, M0) \<in> ?R --> M + {#a#} \<in> ?W" ..
1685         from this and `(M, M0) \<in> ?R` have "M + {#a#} \<in> ?W" ..
1686         then show "N \<in> ?W" by (simp only: N)
1687       next
1688         fix K
1689         assume N: "N = M0 + K"
1690         assume "\<forall>b. b :# K --> (b, a) \<in> r"
1691         then have "M0 + K \<in> ?W"
1692         proof (induct K)
1693           case empty
1694           from M0 show "M0 + {#} \<in> ?W" by simp
1695         next
1696           case (add K x)
1697           from add.prems have "(x, a) \<in> r" by simp
1698           with wf_hyp have "\<forall>M \<in> ?W. M + {#x#} \<in> ?W" by blast
1699           moreover from add have "M0 + K \<in> ?W" by simp
1700           ultimately have "(M0 + K) + {#x#} \<in> ?W" ..
1701           then show "M0 + (K + {#x#}) \<in> ?W" by (simp only: add.assoc)
1702         qed
1703         then show "N \<in> ?W" by (simp only: N)
1704       qed
1705     qed
1706   } note tedious_reasoning = this
1708   assume wf: "wf r"
1709   fix M
1710   show "M \<in> ?W"
1711   proof (induct M)
1712     show "{#} \<in> ?W"
1713     proof (rule accI)
1714       fix b assume "(b, {#}) \<in> ?R"
1715       with not_less_empty show "b \<in> ?W" by contradiction
1716     qed
1718     fix M a assume "M \<in> ?W"
1719     from wf have "\<forall>M \<in> ?W. M + {#a#} \<in> ?W"
1720     proof induct
1721       fix a
1722       assume r: "!!b. (b, a) \<in> r ==> (\<forall>M \<in> ?W. M + {#b#} \<in> ?W)"
1723       show "\<forall>M \<in> ?W. M + {#a#} \<in> ?W"
1724       proof
1725         fix M assume "M \<in> ?W"
1726         then show "M + {#a#} \<in> ?W"
1727           by (rule acc_induct) (rule tedious_reasoning [OF _ r])
1728       qed
1729     qed
1730     from this and `M \<in> ?W` show "M + {#a#} \<in> ?W" ..
1731   qed
1732 qed
1734 theorem wf_mult1: "wf r ==> wf (mult1 r)"
1735 by (rule acc_wfI) (rule all_accessible)
1737 theorem wf_mult: "wf r ==> wf (mult r)"
1738 unfolding mult_def by (rule wf_trancl) (rule wf_mult1)
1741 subsubsection {* Closure-free presentation *}
1743 text {* One direction. *}
1745 lemma mult_implies_one_step:
1746   "trans r ==> (M, N) \<in> mult r ==>
1747     \<exists>I J K. N = I + J \<and> M = I + K \<and> J \<noteq> {#} \<and>
1748     (\<forall>k \<in> set_of K. \<exists>j \<in> set_of J. (k, j) \<in> r)"
1749 apply (unfold mult_def mult1_def set_of_def)
1750 apply (erule converse_trancl_induct, clarify)
1751  apply (rule_tac x = M0 in exI, simp, clarify)
1752 apply (case_tac "a :# K")
1753  apply (rule_tac x = I in exI)
1754  apply (simp (no_asm))
1755  apply (rule_tac x = "(K - {#a#}) + Ka" in exI)
1756  apply (simp (no_asm_simp) add: add.assoc [symmetric])
1757  apply (drule_tac f = "\<lambda>M. M - {#a#}" and x="S + T" for S T in arg_cong)
1758  apply (simp add: diff_union_single_conv)
1759  apply (simp (no_asm_use) add: trans_def)
1760  apply blast
1761 apply (subgoal_tac "a :# I")
1762  apply (rule_tac x = "I - {#a#}" in exI)
1763  apply (rule_tac x = "J + {#a#}" in exI)
1764  apply (rule_tac x = "K + Ka" in exI)
1765  apply (rule conjI)
1766   apply (simp add: multiset_eq_iff split: nat_diff_split)
1767  apply (rule conjI)
1768   apply (drule_tac f = "\<lambda>M. M - {#a#}" and x="S + T" for S T in arg_cong, simp)
1769   apply (simp add: multiset_eq_iff split: nat_diff_split)
1770  apply (simp (no_asm_use) add: trans_def)
1771  apply blast
1772 apply (subgoal_tac "a :# (M0 + {#a#})")
1773  apply simp
1774 apply (simp (no_asm))
1775 done
1777 lemma one_step_implies_mult_aux:
1778   "trans r ==>
1779     \<forall>I J K. (size J = n \<and> J \<noteq> {#} \<and> (\<forall>k \<in> set_of K. \<exists>j \<in> set_of J. (k, j) \<in> r))
1780       --> (I + K, I + J) \<in> mult r"
1781 apply (induct_tac n, auto)
1782 apply (frule size_eq_Suc_imp_eq_union, clarify)
1783 apply (rename_tac "J'", simp)
1784 apply (erule notE, auto)
1785 apply (case_tac "J' = {#}")
1786  apply (simp add: mult_def)
1787  apply (rule r_into_trancl)
1788  apply (simp add: mult1_def set_of_def, blast)
1789 txt {* Now we know @{term "J' \<noteq> {#}"}. *}
1790 apply (cut_tac M = K and P = "\<lambda>x. (x, a) \<in> r" in multiset_partition)
1791 apply (erule_tac P = "\<forall>k \<in> set_of K. P k" for P in rev_mp)
1792 apply (erule ssubst)
1793 apply (simp add: Ball_def, auto)
1794 apply (subgoal_tac
1795   "((I + {# x :# K. (x, a) \<in> r #}) + {# x :# K. (x, a) \<notin> r #},
1796     (I + {# x :# K. (x, a) \<in> r #}) + J') \<in> mult r")
1797  prefer 2
1798  apply force
1799 apply (simp (no_asm_use) add: add.assoc [symmetric] mult_def)
1800 apply (erule trancl_trans)
1801 apply (rule r_into_trancl)
1802 apply (simp add: mult1_def set_of_def)
1803 apply (rule_tac x = a in exI)
1804 apply (rule_tac x = "I + J'" in exI)
1805 apply (simp add: ac_simps)
1806 done
1808 lemma one_step_implies_mult:
1809   "trans r ==> J \<noteq> {#} ==> \<forall>k \<in> set_of K. \<exists>j \<in> set_of J. (k, j) \<in> r
1810     ==> (I + K, I + J) \<in> mult r"
1811 using one_step_implies_mult_aux by blast
1814 subsubsection {* Partial-order properties *}
1816 definition less_multiset :: "'a\<Colon>order multiset \<Rightarrow> 'a multiset \<Rightarrow> bool" (infix "<#" 50) where
1817   "M' <# M \<longleftrightarrow> (M', M) \<in> mult {(x', x). x' < x}"
1819 definition le_multiset :: "'a\<Colon>order multiset \<Rightarrow> 'a multiset \<Rightarrow> bool" (infix "<=#" 50) where
1820   "M' <=# M \<longleftrightarrow> M' <# M \<or> M' = M"
1822 notation (xsymbols) less_multiset (infix "\<subset>#" 50)
1823 notation (xsymbols) le_multiset (infix "\<subseteq>#" 50)
1825 interpretation multiset_order: order le_multiset less_multiset
1826 proof -
1827   have irrefl: "\<And>M :: 'a multiset. \<not> M \<subset># M"
1828   proof
1829     fix M :: "'a multiset"
1830     assume "M \<subset># M"
1831     then have MM: "(M, M) \<in> mult {(x, y). x < y}" by (simp add: less_multiset_def)
1832     have "trans {(x'::'a, x). x' < x}"
1833       by (rule transI) simp
1834     moreover note MM
1835     ultimately have "\<exists>I J K. M = I + J \<and> M = I + K
1836       \<and> J \<noteq> {#} \<and> (\<forall>k\<in>set_of K. \<exists>j\<in>set_of J. (k, j) \<in> {(x, y). x < y})"
1837       by (rule mult_implies_one_step)
1838     then obtain I J K where "M = I + J" and "M = I + K"
1839       and "J \<noteq> {#}" and "(\<forall>k\<in>set_of K. \<exists>j\<in>set_of J. (k, j) \<in> {(x, y). x < y})" by blast
1840     then have aux1: "K \<noteq> {#}" and aux2: "\<forall>k\<in>set_of K. \<exists>j\<in>set_of K. k < j" by auto
1841     have "finite (set_of K)" by simp
1842     moreover note aux2
1843     ultimately have "set_of K = {}"
1844       by (induct rule: finite_induct) (auto intro: order_less_trans)
1845     with aux1 show False by simp
1846   qed
1847   have trans: "\<And>K M N :: 'a multiset. K \<subset># M \<Longrightarrow> M \<subset># N \<Longrightarrow> K \<subset># N"
1848     unfolding less_multiset_def mult_def by (blast intro: trancl_trans)
1849   show "class.order (le_multiset :: 'a multiset \<Rightarrow> _) less_multiset"
1850     by default (auto simp add: le_multiset_def irrefl dest: trans)
1851 qed
1853 lemma mult_less_irrefl [elim!]: "M \<subset># (M::'a::order multiset) ==> R"
1854   by simp
1857 subsubsection {* Monotonicity of multiset union *}
1859 lemma mult1_union: "(B, D) \<in> mult1 r ==> (C + B, C + D) \<in> mult1 r"
1860 apply (unfold mult1_def)
1861 apply auto
1862 apply (rule_tac x = a in exI)
1863 apply (rule_tac x = "C + M0" in exI)
1865 done
1867 lemma union_less_mono2: "B \<subset># D ==> C + B \<subset># C + (D::'a::order multiset)"
1868 apply (unfold less_multiset_def mult_def)
1869 apply (erule trancl_induct)
1870  apply (blast intro: mult1_union)
1871 apply (blast intro: mult1_union trancl_trans)
1872 done
1874 lemma union_less_mono1: "B \<subset># D ==> B + C \<subset># D + (C::'a::order multiset)"
1875 apply (subst add.commute [of B C])
1876 apply (subst add.commute [of D C])
1877 apply (erule union_less_mono2)
1878 done
1880 lemma union_less_mono:
1881   "A \<subset># C ==> B \<subset># D ==> A + B \<subset># C + (D::'a::order multiset)"
1882   by (blast intro!: union_less_mono1 union_less_mono2 multiset_order.less_trans)
1884 interpretation multiset_order: ordered_ab_semigroup_add plus le_multiset less_multiset
1885 proof
1886 qed (auto simp add: le_multiset_def intro: union_less_mono2)
1889 subsubsection {* Termination proofs with multiset orders *}
1891 lemma multi_member_skip: "x \<in># XS \<Longrightarrow> x \<in># {# y #} + XS"
1892   and multi_member_this: "x \<in># {# x #} + XS"
1893   and multi_member_last: "x \<in># {# x #}"
1894   by auto
1896 definition "ms_strict = mult pair_less"
1897 definition "ms_weak = ms_strict \<union> Id"
1899 lemma ms_reduction_pair: "reduction_pair (ms_strict, ms_weak)"
1900 unfolding reduction_pair_def ms_strict_def ms_weak_def pair_less_def
1901 by (auto intro: wf_mult1 wf_trancl simp: mult_def)
1903 lemma smsI:
1904   "(set_of A, set_of B) \<in> max_strict \<Longrightarrow> (Z + A, Z + B) \<in> ms_strict"
1905   unfolding ms_strict_def
1906 by (rule one_step_implies_mult) (auto simp add: max_strict_def pair_less_def elim!:max_ext.cases)
1908 lemma wmsI:
1909   "(set_of A, set_of B) \<in> max_strict \<or> A = {#} \<and> B = {#}
1910   \<Longrightarrow> (Z + A, Z + B) \<in> ms_weak"
1911 unfolding ms_weak_def ms_strict_def
1912 by (auto simp add: pair_less_def max_strict_def elim!:max_ext.cases intro: one_step_implies_mult)
1914 inductive pw_leq
1915 where
1916   pw_leq_empty: "pw_leq {#} {#}"
1917 | pw_leq_step:  "\<lbrakk>(x,y) \<in> pair_leq; pw_leq X Y \<rbrakk> \<Longrightarrow> pw_leq ({#x#} + X) ({#y#} + Y)"
1919 lemma pw_leq_lstep:
1920   "(x, y) \<in> pair_leq \<Longrightarrow> pw_leq {#x#} {#y#}"
1921 by (drule pw_leq_step) (rule pw_leq_empty, simp)
1923 lemma pw_leq_split:
1924   assumes "pw_leq X Y"
1925   shows "\<exists>A B Z. X = A + Z \<and> Y = B + Z \<and> ((set_of A, set_of B) \<in> max_strict \<or> (B = {#} \<and> A = {#}))"
1926   using assms
1927 proof (induct)
1928   case pw_leq_empty thus ?case by auto
1929 next
1930   case (pw_leq_step x y X Y)
1931   then obtain A B Z where
1932     [simp]: "X = A + Z" "Y = B + Z"
1933       and 1[simp]: "(set_of A, set_of B) \<in> max_strict \<or> (B = {#} \<and> A = {#})"
1934     by auto
1935   from pw_leq_step have "x = y \<or> (x, y) \<in> pair_less"
1936     unfolding pair_leq_def by auto
1937   thus ?case
1938   proof
1939     assume [simp]: "x = y"
1940     have
1941       "{#x#} + X = A + ({#y#}+Z)
1942       \<and> {#y#} + Y = B + ({#y#}+Z)
1943       \<and> ((set_of A, set_of B) \<in> max_strict \<or> (B = {#} \<and> A = {#}))"
1944       by (auto simp: ac_simps)
1945     thus ?case by (intro exI)
1946   next
1947     assume A: "(x, y) \<in> pair_less"
1948     let ?A' = "{#x#} + A" and ?B' = "{#y#} + B"
1949     have "{#x#} + X = ?A' + Z"
1950       "{#y#} + Y = ?B' + Z"
1951       by (auto simp add: ac_simps)
1952     moreover have
1953       "(set_of ?A', set_of ?B') \<in> max_strict"
1954       using 1 A unfolding max_strict_def
1955       by (auto elim!: max_ext.cases)
1956     ultimately show ?thesis by blast
1957   qed
1958 qed
1960 lemma
1961   assumes pwleq: "pw_leq Z Z'"
1962   shows ms_strictI: "(set_of A, set_of B) \<in> max_strict \<Longrightarrow> (Z + A, Z' + B) \<in> ms_strict"
1963   and   ms_weakI1:  "(set_of A, set_of B) \<in> max_strict \<Longrightarrow> (Z + A, Z' + B) \<in> ms_weak"
1964   and   ms_weakI2:  "(Z + {#}, Z' + {#}) \<in> ms_weak"
1965 proof -
1966   from pw_leq_split[OF pwleq]
1967   obtain A' B' Z''
1968     where [simp]: "Z = A' + Z''" "Z' = B' + Z''"
1969     and mx_or_empty: "(set_of A', set_of B') \<in> max_strict \<or> (A' = {#} \<and> B' = {#})"
1970     by blast
1971   {
1972     assume max: "(set_of A, set_of B) \<in> max_strict"
1973     from mx_or_empty
1974     have "(Z'' + (A + A'), Z'' + (B + B')) \<in> ms_strict"
1975     proof
1976       assume max': "(set_of A', set_of B') \<in> max_strict"
1977       with max have "(set_of (A + A'), set_of (B + B')) \<in> max_strict"
1978         by (auto simp: max_strict_def intro: max_ext_additive)
1979       thus ?thesis by (rule smsI)
1980     next
1981       assume [simp]: "A' = {#} \<and> B' = {#}"
1982       show ?thesis by (rule smsI) (auto intro: max)
1983     qed
1984     thus "(Z + A, Z' + B) \<in> ms_strict" by (simp add:ac_simps)
1985     thus "(Z + A, Z' + B) \<in> ms_weak" by (simp add: ms_weak_def)
1986   }
1987   from mx_or_empty
1988   have "(Z'' + A', Z'' + B') \<in> ms_weak" by (rule wmsI)
1989   thus "(Z + {#}, Z' + {#}) \<in> ms_weak" by (simp add:ac_simps)
1990 qed
1992 lemma empty_neutral: "{#} + x = x" "x + {#} = x"
1993 and nonempty_plus: "{# x #} + rs \<noteq> {#}"
1994 and nonempty_single: "{# x #} \<noteq> {#}"
1995 by auto
1997 setup {*
1998 let
1999   fun msetT T = Type (@{type_name multiset}, [T]);
2001   fun mk_mset T [] = Const (@{const_abbrev Mempty}, msetT T)
2002     | mk_mset T [x] = Const (@{const_name single}, T --> msetT T) \$ x
2003     | mk_mset T (x :: xs) =
2004           Const (@{const_name plus}, msetT T --> msetT T --> msetT T) \$
2005                 mk_mset T [x] \$ mk_mset T xs
2007   fun mset_member_tac m i =
2008       (if m <= 0 then
2009            rtac @{thm multi_member_this} i ORELSE rtac @{thm multi_member_last} i
2010        else
2011            rtac @{thm multi_member_skip} i THEN mset_member_tac (m - 1) i)
2013   val mset_nonempty_tac =
2014       rtac @{thm nonempty_plus} ORELSE' rtac @{thm nonempty_single}
2016   fun regroup_munion_conv ctxt =
2017     Function_Lib.regroup_conv ctxt @{const_abbrev Mempty} @{const_name plus}
2018       (map (fn t => t RS eq_reflection) (@{thms ac_simps} @ @{thms empty_neutral}))
2020   fun unfold_pwleq_tac i =
2021     (rtac @{thm pw_leq_step} i THEN (fn st => unfold_pwleq_tac (i + 1) st))
2022       ORELSE (rtac @{thm pw_leq_lstep} i)
2023       ORELSE (rtac @{thm pw_leq_empty} i)
2025   val set_of_simps = [@{thm set_of_empty}, @{thm set_of_single}, @{thm set_of_union},
2026                       @{thm Un_insert_left}, @{thm Un_empty_left}]
2027 in
2028   ScnpReconstruct.multiset_setup (ScnpReconstruct.Multiset
2029   {
2030     msetT=msetT, mk_mset=mk_mset, mset_regroup_conv=regroup_munion_conv,
2031     mset_member_tac=mset_member_tac, mset_nonempty_tac=mset_nonempty_tac,
2032     mset_pwleq_tac=unfold_pwleq_tac, set_of_simps=set_of_simps,
2033     smsI'= @{thm ms_strictI}, wmsI2''= @{thm ms_weakI2}, wmsI1= @{thm ms_weakI1},
2034     reduction_pair= @{thm ms_reduction_pair}
2035   })
2036 end
2037 *}
2040 subsection {* Legacy theorem bindings *}
2042 lemmas multi_count_eq = multiset_eq_iff [symmetric]
2044 lemma union_commute: "M + N = N + (M::'a multiset)"
2045   by (fact add.commute)
2047 lemma union_assoc: "(M + N) + K = M + (N + (K::'a multiset))"
2048   by (fact add.assoc)
2050 lemma union_lcomm: "M + (N + K) = N + (M + (K::'a multiset))"
2051   by (fact add.left_commute)
2053 lemmas union_ac = union_assoc union_commute union_lcomm
2055 lemma union_right_cancel: "M + K = N + K \<longleftrightarrow> M = (N::'a multiset)"
2056   by (fact add_right_cancel)
2058 lemma union_left_cancel: "K + M = K + N \<longleftrightarrow> M = (N::'a multiset)"
2059   by (fact add_left_cancel)
2061 lemma multi_union_self_other_eq: "(A::'a multiset) + X = A + Y \<Longrightarrow> X = Y"
2062   by (fact add_left_imp_eq)
2064 lemma mset_less_trans: "(M::'a multiset) < K \<Longrightarrow> K < N \<Longrightarrow> M < N"
2065   by (fact order_less_trans)
2067 lemma multiset_inter_commute: "A #\<inter> B = B #\<inter> A"
2068   by (fact inf.commute)
2070 lemma multiset_inter_assoc: "A #\<inter> (B #\<inter> C) = A #\<inter> B #\<inter> C"
2071   by (fact inf.assoc [symmetric])
2073 lemma multiset_inter_left_commute: "A #\<inter> (B #\<inter> C) = B #\<inter> (A #\<inter> C)"
2074   by (fact inf.left_commute)
2076 lemmas multiset_inter_ac =
2077   multiset_inter_commute
2078   multiset_inter_assoc
2079   multiset_inter_left_commute
2081 lemma mult_less_not_refl:
2082   "\<not> M \<subset># (M::'a::order multiset)"
2083   by (fact multiset_order.less_irrefl)
2085 lemma mult_less_trans:
2086   "K \<subset># M ==> M \<subset># N ==> K \<subset># (N::'a::order multiset)"
2087   by (fact multiset_order.less_trans)
2089 lemma mult_less_not_sym:
2090   "M \<subset># N ==> \<not> N \<subset># (M::'a::order multiset)"
2091   by (fact multiset_order.less_not_sym)
2093 lemma mult_less_asym:
2094   "M \<subset># N ==> (\<not> P ==> N \<subset># (M::'a::order multiset)) ==> P"
2095   by (fact multiset_order.less_asym)
2097 ML {*
2098 fun multiset_postproc _ maybe_name all_values (T as Type (_, [elem_T]))
2099                       (Const _ \$ t') =
2100     let
2101       val (maybe_opt, ps) =
2102         Nitpick_Model.dest_plain_fun t' ||> op ~~
2103         ||> map (apsnd (snd o HOLogic.dest_number))
2104       fun elems_for t =
2105         case AList.lookup (op =) ps t of
2106           SOME n => replicate n t
2107         | NONE => [Const (maybe_name, elem_T --> elem_T) \$ t]
2108     in
2109       case maps elems_for (all_values elem_T) @
2110            (if maybe_opt then [Const (Nitpick_Model.unrep (), elem_T)]
2111             else []) of
2112         [] => Const (@{const_name zero_class.zero}, T)
2113       | ts => foldl1 (fn (t1, t2) =>
2114                          Const (@{const_name plus_class.plus}, T --> T --> T)
2115                          \$ t1 \$ t2)
2116                      (map (curry (op \$) (Const (@{const_name single},
2117                                                 elem_T --> T))) ts)
2118     end
2119   | multiset_postproc _ _ _ _ t = t
2120 *}
2122 declaration {*
2123 Nitpick_Model.register_term_postprocessor @{typ "'a multiset"}
2124     multiset_postproc
2125 *}
2127 hide_const (open) fold
2130 subsection {* Naive implementation using lists *}
2132 code_datatype multiset_of
2134 lemma [code]:
2135   "{#} = multiset_of []"
2136   by simp
2138 lemma [code]:
2139   "{#x#} = multiset_of [x]"
2140   by simp
2142 lemma union_code [code]:
2143   "multiset_of xs + multiset_of ys = multiset_of (xs @ ys)"
2144   by simp
2146 lemma [code]:
2147   "image_mset f (multiset_of xs) = multiset_of (map f xs)"
2148   by (simp add: multiset_of_map)
2150 lemma [code]:
2151   "Multiset.filter f (multiset_of xs) = multiset_of (filter f xs)"
2152   by (simp add: multiset_of_filter)
2154 lemma [code]:
2155   "multiset_of xs - multiset_of ys = multiset_of (fold remove1 ys xs)"
2156   by (rule sym, induct ys arbitrary: xs) (simp_all add: diff_add diff_right_commute)
2158 lemma [code]:
2159   "multiset_of xs #\<inter> multiset_of ys =
2160     multiset_of (snd (fold (\<lambda>x (ys, zs).
2161       if x \<in> set ys then (remove1 x ys, x # zs) else (ys, zs)) xs (ys, [])))"
2162 proof -
2163   have "\<And>zs. multiset_of (snd (fold (\<lambda>x (ys, zs).
2164     if x \<in> set ys then (remove1 x ys, x # zs) else (ys, zs)) xs (ys, zs))) =
2165       (multiset_of xs #\<inter> multiset_of ys) + multiset_of zs"
2166     by (induct xs arbitrary: ys)
2168   then show ?thesis by simp
2169 qed
2171 lemma [code]:
2172   "multiset_of xs #\<union> multiset_of ys =
2173     multiset_of (split append (fold (\<lambda>x (ys, zs). (remove1 x ys, x # zs)) xs (ys, [])))"
2174 proof -
2175   have "\<And>zs. multiset_of (split append (fold (\<lambda>x (ys, zs). (remove1 x ys, x # zs)) xs (ys, zs))) =
2176       (multiset_of xs #\<union> multiset_of ys) + multiset_of zs"
2177     by (induct xs arbitrary: ys) (simp_all add: multiset_eq_iff)
2178   then show ?thesis by simp
2179 qed
2181 declare in_multiset_in_set [code_unfold]
2183 lemma [code]:
2184   "count (multiset_of xs) x = fold (\<lambda>y. if x = y then Suc else id) xs 0"
2185 proof -
2186   have "\<And>n. fold (\<lambda>y. if x = y then Suc else id) xs n = count (multiset_of xs) x + n"
2187     by (induct xs) simp_all
2188   then show ?thesis by simp
2189 qed
2191 declare set_of_multiset_of [code]
2193 declare sorted_list_of_multiset_multiset_of [code]
2195 lemma [code]: -- {* not very efficient, but representation-ignorant! *}
2196   "multiset_of_set A = multiset_of (sorted_list_of_set A)"
2197   apply (cases "finite A")
2198   apply simp_all
2199   apply (induct A rule: finite_induct)
2201   done
2203 declare mcard_multiset_of [code]
2205 fun ms_lesseq_impl :: "'a list \<Rightarrow> 'a list \<Rightarrow> bool option" where
2206   "ms_lesseq_impl [] ys = Some (ys \<noteq> [])"
2207 | "ms_lesseq_impl (Cons x xs) ys = (case List.extract (op = x) ys of
2208      None \<Rightarrow> None
2209    | Some (ys1,_,ys2) \<Rightarrow> ms_lesseq_impl xs (ys1 @ ys2))"
2211 lemma ms_lesseq_impl: "(ms_lesseq_impl xs ys = None \<longleftrightarrow> \<not> multiset_of xs \<le> multiset_of ys) \<and>
2212   (ms_lesseq_impl xs ys = Some True \<longleftrightarrow> multiset_of xs < multiset_of ys) \<and>
2213   (ms_lesseq_impl xs ys = Some False \<longrightarrow> multiset_of xs = multiset_of ys)"
2214 proof (induct xs arbitrary: ys)
2215   case (Nil ys)
2216   show ?case by (auto simp: mset_less_empty_nonempty)
2217 next
2218   case (Cons x xs ys)
2219   show ?case
2220   proof (cases "List.extract (op = x) ys")
2221     case None
2222     hence x: "x \<notin> set ys" by (simp add: extract_None_iff)
2223     {
2224       assume "multiset_of (x # xs) \<le> multiset_of ys"
2225       from set_of_mono[OF this] x have False by simp
2226     } note nle = this
2227     moreover
2228     {
2229       assume "multiset_of (x # xs) < multiset_of ys"
2230       hence "multiset_of (x # xs) \<le> multiset_of ys" by auto
2231       from nle[OF this] have False .
2232     }
2233     ultimately show ?thesis using None by auto
2234   next
2235     case (Some res)
2236     obtain ys1 y ys2 where res: "res = (ys1,y,ys2)" by (cases res, auto)
2237     note Some = Some[unfolded res]
2238     from extract_SomeE[OF Some] have "ys = ys1 @ x # ys2" by simp
2239     hence id: "multiset_of ys = multiset_of (ys1 @ ys2) + {#x#}"
2240       by (auto simp: ac_simps)
2241     show ?thesis unfolding ms_lesseq_impl.simps
2242       unfolding Some option.simps split
2243       unfolding id
2244       using Cons[of "ys1 @ ys2"]
2245       unfolding mset_le_def mset_less_def by auto
2246   qed
2247 qed
2249 lemma [code]: "multiset_of xs \<le> multiset_of ys \<longleftrightarrow> ms_lesseq_impl xs ys \<noteq> None"
2250   using ms_lesseq_impl[of xs ys] by (cases "ms_lesseq_impl xs ys", auto)
2252 lemma [code]: "multiset_of xs < multiset_of ys \<longleftrightarrow> ms_lesseq_impl xs ys = Some True"
2253   using ms_lesseq_impl[of xs ys] by (cases "ms_lesseq_impl xs ys", auto)
2255 instantiation multiset :: (equal) equal
2256 begin
2258 definition
2259   [code del]: "HOL.equal A (B :: 'a multiset) \<longleftrightarrow> A = B"
2260 lemma [code]: "HOL.equal (multiset_of xs) (multiset_of ys) \<longleftrightarrow> ms_lesseq_impl xs ys = Some False"
2261   unfolding equal_multiset_def
2262   using ms_lesseq_impl[of xs ys] by (cases "ms_lesseq_impl xs ys", auto)
2264 instance
2265   by default (simp add: equal_multiset_def)
2266 end
2268 lemma [code]:
2269   "msetsum (multiset_of xs) = listsum xs"
2270   by (induct xs) (simp_all add: add.commute)
2272 lemma [code]:
2273   "msetprod (multiset_of xs) = fold times xs 1"
2274 proof -
2275   have "\<And>x. fold times xs x = msetprod (multiset_of xs) * x"
2276     by (induct xs) (simp_all add: mult.assoc)
2277   then show ?thesis by simp
2278 qed
2280 lemma [code]:
2281   "size = mcard"
2282   by (fact size_eq_mcard)
2284 text {*
2285   Exercise for the casual reader: add implementations for @{const le_multiset}
2286   and @{const less_multiset} (multiset order).
2287 *}
2289 text {* Quickcheck generators *}
2291 definition (in term_syntax)
2292   msetify :: "'a\<Colon>typerep list \<times> (unit \<Rightarrow> Code_Evaluation.term)
2293     \<Rightarrow> 'a multiset \<times> (unit \<Rightarrow> Code_Evaluation.term)" where
2294   [code_unfold]: "msetify xs = Code_Evaluation.valtermify multiset_of {\<cdot>} xs"
2296 notation fcomp (infixl "\<circ>>" 60)
2297 notation scomp (infixl "\<circ>\<rightarrow>" 60)
2299 instantiation multiset :: (random) random
2300 begin
2302 definition
2303   "Quickcheck_Random.random i = Quickcheck_Random.random i \<circ>\<rightarrow> (\<lambda>xs. Pair (msetify xs))"
2305 instance ..
2307 end
2309 no_notation fcomp (infixl "\<circ>>" 60)
2310 no_notation scomp (infixl "\<circ>\<rightarrow>" 60)
2312 instantiation multiset :: (full_exhaustive) full_exhaustive
2313 begin
2315 definition full_exhaustive_multiset :: "('a multiset \<times> (unit \<Rightarrow> term) \<Rightarrow> (bool \<times> term list) option) \<Rightarrow> natural \<Rightarrow> (bool \<times> term list) option"
2316 where
2317   "full_exhaustive_multiset f i = Quickcheck_Exhaustive.full_exhaustive (\<lambda>xs. f (msetify xs)) i"
2319 instance ..
2321 end
2323 hide_const (open) msetify
2326 subsection {* BNF setup *}
2328 definition rel_mset where
2329   "rel_mset R X Y \<longleftrightarrow> (\<exists>xs ys. multiset_of xs = X \<and> multiset_of ys = Y \<and> list_all2 R xs ys)"
2331 lemma multiset_of_zip_take_Cons_drop_twice:
2332   assumes "length xs = length ys" "j \<le> length xs"
2333   shows "multiset_of (zip (take j xs @ x # drop j xs) (take j ys @ y # drop j ys)) =
2334     multiset_of (zip xs ys) + {#(x, y)#}"
2335 using assms
2336 proof (induct xs ys arbitrary: x y j rule: list_induct2)
2337   case Nil
2338   thus ?case
2339     by simp
2340 next
2341   case (Cons x xs y ys)
2342   thus ?case
2343   proof (cases "j = 0")
2344     case True
2345     thus ?thesis
2346       by simp
2347   next
2348     case False
2349     then obtain k where k: "j = Suc k"
2350       by (case_tac j) simp
2351     hence "k \<le> length xs"
2352       using Cons.prems by auto
2353     hence "multiset_of (zip (take k xs @ x # drop k xs) (take k ys @ y # drop k ys)) =
2354       multiset_of (zip xs ys) + {#(x, y)#}"
2355       by (rule Cons.hyps(2))
2356     thus ?thesis
2357       unfolding k by (auto simp: add.commute union_lcomm)
2358   qed
2359 qed
2361 lemma ex_multiset_of_zip_left:
2362   assumes "length xs = length ys" "multiset_of xs' = multiset_of xs"
2363   shows "\<exists>ys'. length ys' = length xs' \<and> multiset_of (zip xs' ys') = multiset_of (zip xs ys)"
2364 using assms
2365 proof (induct xs ys arbitrary: xs' rule: list_induct2)
2366   case Nil
2367   thus ?case
2368     by auto
2369 next
2370   case (Cons x xs y ys xs')
2371   obtain j where j_len: "j < length xs'" and nth_j: "xs' ! j = x"
2372     by (metis Cons.prems in_set_conv_nth list.set_intros(1) multiset_of_eq_setD)
2374   def xsa \<equiv> "take j xs' @ drop (Suc j) xs'"
2375   have "multiset_of xs' = {#x#} + multiset_of xsa"
2376     unfolding xsa_def using j_len nth_j
2377     by (metis (no_types) ab_semigroup_add_class.add_ac(1) append_take_drop_id Cons_nth_drop_Suc
2378       multiset_of.simps(2) union_code add.commute)
2379   hence ms_x: "multiset_of xsa = multiset_of xs"
2380     by (metis Cons.prems add.commute add_right_imp_eq multiset_of.simps(2))
2381   then obtain ysa where
2382     len_a: "length ysa = length xsa" and ms_a: "multiset_of (zip xsa ysa) = multiset_of (zip xs ys)"
2383     using Cons.hyps(2) by blast
2385   def ys' \<equiv> "take j ysa @ y # drop j ysa"
2386   have xs': "xs' = take j xsa @ x # drop j xsa"
2387     using ms_x j_len nth_j Cons.prems xsa_def
2388     by (metis append_eq_append_conv append_take_drop_id diff_Suc_Suc Cons_nth_drop_Suc length_Cons
2389       length_drop mcard_multiset_of)
2390   have j_len': "j \<le> length xsa"
2391     using j_len xs' xsa_def
2392     by (metis add_Suc_right append_take_drop_id length_Cons length_append less_eq_Suc_le not_less)
2393   have "length ys' = length xs'"
2394     unfolding ys'_def using Cons.prems len_a ms_x
2395     by (metis add_Suc_right append_take_drop_id length_Cons length_append multiset_of_eq_length)
2396   moreover have "multiset_of (zip xs' ys') = multiset_of (zip (x # xs) (y # ys))"
2397     unfolding xs' ys'_def
2398     by (rule trans[OF multiset_of_zip_take_Cons_drop_twice])
2399       (auto simp: len_a ms_a j_len' add.commute)
2400   ultimately show ?case
2401     by blast
2402 qed
2404 lemma list_all2_reorder_left_invariance:
2405   assumes rel: "list_all2 R xs ys" and ms_x: "multiset_of xs' = multiset_of xs"
2406   shows "\<exists>ys'. list_all2 R xs' ys' \<and> multiset_of ys' = multiset_of ys"
2407 proof -
2408   have len: "length xs = length ys"
2409     using rel list_all2_conv_all_nth by auto
2410   obtain ys' where
2411     len': "length xs' = length ys'" and ms_xy: "multiset_of (zip xs' ys') = multiset_of (zip xs ys)"
2412     using len ms_x by (metis ex_multiset_of_zip_left)
2413   have "list_all2 R xs' ys'"
2414     using assms(1) len' ms_xy unfolding list_all2_iff by (blast dest: multiset_of_eq_setD)
2415   moreover have "multiset_of ys' = multiset_of ys"
2416     using len len' ms_xy map_snd_zip multiset_of_map by metis
2417   ultimately show ?thesis
2418     by blast
2419 qed
2421 lemma ex_multiset_of: "\<exists>xs. multiset_of xs = X"
2422   by (induct X) (simp, metis multiset_of.simps(2))
2424 bnf "'a multiset"
2425   map: image_mset
2426   sets: set_of
2427   bd: natLeq
2428   wits: "{#}"
2429   rel: rel_mset
2430 proof -
2431   show "image_mset id = id"
2432     by (rule image_mset.id)
2433 next
2434   show "\<And>f g. image_mset (g \<circ> f) = image_mset g \<circ> image_mset f"
2435     unfolding comp_def by (rule ext) (simp add: comp_def image_mset.compositionality)
2436 next
2437   fix X :: "'a multiset"
2438   show "\<And>f g. (\<And>z. z \<in> set_of X \<Longrightarrow> f z = g z) \<Longrightarrow> image_mset f X = image_mset g X"
2439     by (induct X, (simp (no_asm))+,
2440       metis One_nat_def Un_iff count_single mem_set_of_iff set_of_union zero_less_Suc)
2441 next
2442   show "\<And>f. set_of \<circ> image_mset f = op ` f \<circ> set_of"
2443     by auto
2444 next
2445   show "card_order natLeq"
2446     by (rule natLeq_card_order)
2447 next
2448   show "BNF_Cardinal_Arithmetic.cinfinite natLeq"
2449     by (rule natLeq_cinfinite)
2450 next
2451   show "\<And>X. ordLeq3 (card_of (set_of X)) natLeq"
2452     by transfer
2453       (auto intro!: ordLess_imp_ordLeq simp: finite_iff_ordLess_natLeq[symmetric] multiset_def)
2454 next
2455   show "\<And>R S. rel_mset R OO rel_mset S \<le> rel_mset (R OO S)"
2456     unfolding rel_mset_def[abs_def] OO_def
2457     apply clarify
2458     apply (rename_tac X Z Y xs ys' ys zs)
2459     apply (drule_tac xs = ys' and ys = zs and xs' = ys in list_all2_reorder_left_invariance)
2460     by (auto intro: list_all2_trans)
2461 next
2462   show "\<And>R. rel_mset R =
2463     (BNF_Def.Grp {x. set_of x \<subseteq> {(x, y). R x y}} (image_mset fst))\<inverse>\<inverse> OO
2464     BNF_Def.Grp {x. set_of x \<subseteq> {(x, y). R x y}} (image_mset snd)"
2465     unfolding rel_mset_def[abs_def] BNF_Def.Grp_def OO_def
2466     apply (rule ext)+
2467     apply auto
2468      apply (rule_tac x = "multiset_of (zip xs ys)" in exI)
2469      apply auto
2470         apply (metis list_all2_lengthD map_fst_zip multiset_of_map)
2471        apply (auto simp: list_all2_iff)
2472       apply (metis list_all2_lengthD map_snd_zip multiset_of_map)
2473      apply (auto simp: list_all2_iff)
2474     apply (rename_tac XY)
2475     apply (cut_tac X = XY in ex_multiset_of)
2476     apply (erule exE)
2477     apply (rename_tac xys)
2478     apply (rule_tac x = "map fst xys" in exI)
2479     apply (auto simp: multiset_of_map)
2480     apply (rule_tac x = "map snd xys" in exI)
2481     by (auto simp: multiset_of_map list_all2I subset_eq zip_map_fst_snd)
2482 next
2483   show "\<And>z. z \<in> set_of {#} \<Longrightarrow> False"
2484     by auto
2485 qed
2487 inductive rel_mset' where
2488   Zero[intro]: "rel_mset' R {#} {#}"
2489 | Plus[intro]: "\<lbrakk>R a b; rel_mset' R M N\<rbrakk> \<Longrightarrow> rel_mset' R (M + {#a#}) (N + {#b#})"
2491 lemma rel_mset_Zero: "rel_mset R {#} {#}"
2492 unfolding rel_mset_def Grp_def by auto
2494 declare multiset.count[simp]
2495 declare Abs_multiset_inverse[simp]
2496 declare multiset.count_inverse[simp]
2497 declare union_preserves_multiset[simp]
2499 lemma rel_mset_Plus:
2500 assumes ab: "R a b" and MN: "rel_mset R M N"
2501 shows "rel_mset R (M + {#a#}) (N + {#b#})"
2502 proof-
2503   {fix y assume "R a b" and "set_of y \<subseteq> {(x, y). R x y}"
2504    hence "\<exists>ya. image_mset fst y + {#a#} = image_mset fst ya \<and>
2505                image_mset snd y + {#b#} = image_mset snd ya \<and>
2506                set_of ya \<subseteq> {(x, y). R x y}"
2507    apply(intro exI[of _ "y + {#(a,b)#}"]) by auto
2508   }
2509   thus ?thesis
2510   using assms
2511   unfolding multiset.rel_compp_Grp Grp_def by blast
2512 qed
2514 lemma rel_mset'_imp_rel_mset:
2515 "rel_mset' R M N \<Longrightarrow> rel_mset R M N"
2516 apply(induct rule: rel_mset'.induct)
2517 using rel_mset_Zero rel_mset_Plus by auto
2519 lemma mcard_image_mset[simp]: "mcard (image_mset f M) = mcard M"
2520   unfolding size_eq_mcard[symmetric] by (rule size_image_mset)
2522 lemma rel_mset_mcard:
2523   assumes "rel_mset R M N"
2524   shows "mcard M = mcard N"
2525 using assms unfolding multiset.rel_compp_Grp Grp_def by auto
2528 assumes empty: "P {#} {#}"
2529 and addL: "\<And>M N a. P M N \<Longrightarrow> P (M + {#a#}) N"
2530 and addR: "\<And>M N a. P M N \<Longrightarrow> P M (N + {#a#})"
2531 shows "P M N"
2532 apply(induct N rule: multiset_induct)
2533   apply(induct M rule: multiset_induct, rule empty, erule addL)
2534   apply(induct M rule: multiset_induct, erule addR, erule addR)
2535 done
2537 lemma multiset_induct2_mcard[consumes 1, case_names empty add]:
2538 assumes c: "mcard M = mcard N"
2539 and empty: "P {#} {#}"
2540 and add: "\<And>M N a b. P M N \<Longrightarrow> P (M + {#a#}) (N + {#b#})"
2541 shows "P M N"
2542 using c proof(induct M arbitrary: N rule: measure_induct_rule[of mcard])
2543   case (less M)  show ?case
2544   proof(cases "M = {#}")
2545     case True hence "N = {#}" using less.prems by auto
2546     thus ?thesis using True empty by auto
2547   next
2548     case False then obtain M1 a where M: "M = M1 + {#a#}" by (metis multi_nonempty_split)
2549     have "N \<noteq> {#}" using False less.prems by auto
2550     then obtain N1 b where N: "N = N1 + {#b#}" by (metis multi_nonempty_split)
2551     have "mcard M1 = mcard N1" using less.prems unfolding M N by auto
2552     thus ?thesis using M N less.hyps add by auto
2553   qed
2554 qed
2556 lemma msed_map_invL:
2557 assumes "image_mset f (M + {#a#}) = N"
2558 shows "\<exists>N1. N = N1 + {#f a#} \<and> image_mset f M = N1"
2559 proof-
2560   have "f a \<in># N"
2561   using assms multiset.set_map[of f "M + {#a#}"] by auto
2562   then obtain N1 where N: "N = N1 + {#f a#}" using multi_member_split by metis
2563   have "image_mset f M = N1" using assms unfolding N by simp
2564   thus ?thesis using N by blast
2565 qed
2567 lemma msed_map_invR:
2568 assumes "image_mset f M = N + {#b#}"
2569 shows "\<exists>M1 a. M = M1 + {#a#} \<and> f a = b \<and> image_mset f M1 = N"
2570 proof-
2571   obtain a where a: "a \<in># M" and fa: "f a = b"
2572   using multiset.set_map[of f M] unfolding assms
2573   by (metis image_iff mem_set_of_iff union_single_eq_member)
2574   then obtain M1 where M: "M = M1 + {#a#}" using multi_member_split by metis
2575   have "image_mset f M1 = N" using assms unfolding M fa[symmetric] by simp
2576   thus ?thesis using M fa by blast
2577 qed
2579 lemma msed_rel_invL:
2580 assumes "rel_mset R (M + {#a#}) N"
2581 shows "\<exists>N1 b. N = N1 + {#b#} \<and> R a b \<and> rel_mset R M N1"
2582 proof-
2583   obtain K where KM: "image_mset fst K = M + {#a#}"
2584   and KN: "image_mset snd K = N" and sK: "set_of K \<subseteq> {(a, b). R a b}"
2585   using assms
2586   unfolding multiset.rel_compp_Grp Grp_def by auto
2587   obtain K1 ab where K: "K = K1 + {#ab#}" and a: "fst ab = a"
2588   and K1M: "image_mset fst K1 = M" using msed_map_invR[OF KM] by auto
2589   obtain N1 where N: "N = N1 + {#snd ab#}" and K1N1: "image_mset snd K1 = N1"
2590   using msed_map_invL[OF KN[unfolded K]] by auto
2591   have Rab: "R a (snd ab)" using sK a unfolding K by auto
2592   have "rel_mset R M N1" using sK K1M K1N1
2593   unfolding K multiset.rel_compp_Grp Grp_def by auto
2594   thus ?thesis using N Rab by auto
2595 qed
2597 lemma msed_rel_invR:
2598 assumes "rel_mset R M (N + {#b#})"
2599 shows "\<exists>M1 a. M = M1 + {#a#} \<and> R a b \<and> rel_mset R M1 N"
2600 proof-
2601   obtain K where KN: "image_mset snd K = N + {#b#}"
2602   and KM: "image_mset fst K = M" and sK: "set_of K \<subseteq> {(a, b). R a b}"
2603   using assms
2604   unfolding multiset.rel_compp_Grp Grp_def by auto
2605   obtain K1 ab where K: "K = K1 + {#ab#}" and b: "snd ab = b"
2606   and K1N: "image_mset snd K1 = N" using msed_map_invR[OF KN] by auto
2607   obtain M1 where M: "M = M1 + {#fst ab#}" and K1M1: "image_mset fst K1 = M1"
2608   using msed_map_invL[OF KM[unfolded K]] by auto
2609   have Rab: "R (fst ab) b" using sK b unfolding K by auto
2610   have "rel_mset R M1 N" using sK K1N K1M1
2611   unfolding K multiset.rel_compp_Grp Grp_def by auto
2612   thus ?thesis using M Rab by auto
2613 qed
2615 lemma rel_mset_imp_rel_mset':
2616 assumes "rel_mset R M N"
2617 shows "rel_mset' R M N"
2618 using assms proof(induct M arbitrary: N rule: measure_induct_rule[of mcard])
2619   case (less M)
2620   have c: "mcard M = mcard N" using rel_mset_mcard[OF less.prems] .
2621   show ?case
2622   proof(cases "M = {#}")
2623     case True hence "N = {#}" using c by simp
2624     thus ?thesis using True rel_mset'.Zero by auto
2625   next
2626     case False then obtain M1 a where M: "M = M1 + {#a#}" by (metis multi_nonempty_split)
2627     obtain N1 b where N: "N = N1 + {#b#}" and R: "R a b" and ms: "rel_mset R M1 N1"
2628     using msed_rel_invL[OF less.prems[unfolded M]] by auto
2629     have "rel_mset' R M1 N1" using less.hyps[of M1 N1] ms unfolding M by simp
2630     thus ?thesis using rel_mset'.Plus[of R a b, OF R] unfolding M N by simp
2631   qed
2632 qed
2634 lemma rel_mset_rel_mset':
2635 "rel_mset R M N = rel_mset' R M N"
2636 using rel_mset_imp_rel_mset' rel_mset'_imp_rel_mset by auto
2638 (* The main end product for rel_mset: inductive characterization *)
2639 theorems rel_mset_induct[case_names empty add, induct pred: rel_mset] =
2640          rel_mset'.induct[unfolded rel_mset_rel_mset'[symmetric]]
2643 subsection {* Size setup *}
2645 lemma multiset_size_o_map: "size_multiset g \<circ> image_mset f = size_multiset (g \<circ> f)"
2646   unfolding o_apply by (rule ext) (induct_tac, auto)
2648 setup {*
2649 BNF_LFP_Size.register_size_global @{type_name multiset} @{const_name size_multiset}
2650   @{thms size_multiset_empty size_multiset_single size_multiset_union size_empty size_single
2651     size_union}
2652   @{thms multiset_size_o_map}
2653 *}
2655 hide_const (open) wcount
2657 end