src/HOL/Library/Multiset.thy
 author haftmann Sun Jun 02 20:44:55 2013 +0200 (2013-06-02) changeset 52289 83ce5d2841e7 parent 51623 1194b438426a child 54295 45a5523d4a63 permissions -rw-r--r--
type class for confined subtraction
1 (*  Title:      HOL/Library/Multiset.thy
2     Author:     Tobias Nipkow, Markus Wenzel, Lawrence C Paulson, Norbert Voelker
3 *)
5 header {* (Finite) multisets *}
7 theory Multiset
8 imports Main
9 begin
11 subsection {* The type of multisets *}
13 definition "multiset = {f :: 'a => nat. finite {x. f x > 0}}"
15 typedef 'a multiset = "multiset :: ('a => nat) set"
16   morphisms count Abs_multiset
17   unfolding multiset_def
18 proof
19   show "(\<lambda>x. 0::nat) \<in> {f. finite {x. f x > 0}}" by simp
20 qed
22 setup_lifting type_definition_multiset
24 abbreviation Melem :: "'a => 'a multiset => bool"  ("(_/ :# _)" [50, 51] 50) where
25   "a :# M == 0 < count M a"
27 notation (xsymbols)
28   Melem (infix "\<in>#" 50)
30 lemma multiset_eq_iff:
31   "M = N \<longleftrightarrow> (\<forall>a. count M a = count N a)"
32   by (simp only: count_inject [symmetric] fun_eq_iff)
34 lemma multiset_eqI:
35   "(\<And>x. count A x = count B x) \<Longrightarrow> A = B"
36   using multiset_eq_iff by auto
38 text {*
39  \medskip Preservation of the representing set @{term multiset}.
40 *}
42 lemma const0_in_multiset:
43   "(\<lambda>a. 0) \<in> multiset"
44   by (simp add: multiset_def)
46 lemma only1_in_multiset:
47   "(\<lambda>b. if b = a then n else 0) \<in> multiset"
48   by (simp add: multiset_def)
50 lemma union_preserves_multiset:
51   "M \<in> multiset \<Longrightarrow> N \<in> multiset \<Longrightarrow> (\<lambda>a. M a + N a) \<in> multiset"
52   by (simp add: multiset_def)
54 lemma diff_preserves_multiset:
55   assumes "M \<in> multiset"
56   shows "(\<lambda>a. M a - N a) \<in> multiset"
57 proof -
58   have "{x. N x < M x} \<subseteq> {x. 0 < M x}"
59     by auto
60   with assms show ?thesis
61     by (auto simp add: multiset_def intro: finite_subset)
62 qed
64 lemma filter_preserves_multiset:
65   assumes "M \<in> multiset"
66   shows "(\<lambda>x. if P x then M x else 0) \<in> multiset"
67 proof -
68   have "{x. (P x \<longrightarrow> 0 < M x) \<and> P x} \<subseteq> {x. 0 < M x}"
69     by auto
70   with assms show ?thesis
71     by (auto simp add: multiset_def intro: finite_subset)
72 qed
74 lemmas in_multiset = const0_in_multiset only1_in_multiset
75   union_preserves_multiset diff_preserves_multiset filter_preserves_multiset
78 subsection {* Representing multisets *}
80 text {* Multiset enumeration *}
82 instantiation multiset :: (type) cancel_comm_monoid_add
83 begin
85 lift_definition zero_multiset :: "'a multiset" is "\<lambda>a. 0"
86 by (rule const0_in_multiset)
88 abbreviation Mempty :: "'a multiset" ("{#}") where
89   "Mempty \<equiv> 0"
91 lift_definition plus_multiset :: "'a multiset => 'a multiset => 'a multiset" is "\<lambda>M N. (\<lambda>a. M a + N a)"
92 by (rule union_preserves_multiset)
94 instance
95 by default (transfer, simp add: fun_eq_iff)+
97 end
99 lift_definition single :: "'a => 'a multiset" is "\<lambda>a b. if b = a then 1 else 0"
100 by (rule only1_in_multiset)
102 syntax
103   "_multiset" :: "args => 'a multiset"    ("{#(_)#}")
104 translations
105   "{#x, xs#}" == "{#x#} + {#xs#}"
106   "{#x#}" == "CONST single x"
108 lemma count_empty [simp]: "count {#} a = 0"
109   by (simp add: zero_multiset.rep_eq)
111 lemma count_single [simp]: "count {#b#} a = (if b = a then 1 else 0)"
112   by (simp add: single.rep_eq)
115 subsection {* Basic operations *}
117 subsubsection {* Union *}
119 lemma count_union [simp]: "count (M + N) a = count M a + count N a"
120   by (simp add: plus_multiset.rep_eq)
123 subsubsection {* Difference *}
125 instantiation multiset :: (type) comm_monoid_diff
126 begin
128 lift_definition minus_multiset :: "'a multiset => 'a multiset => 'a multiset" is "\<lambda> M N. \<lambda>a. M a - N a"
129 by (rule diff_preserves_multiset)
131 instance
132 by default (transfer, simp add: fun_eq_iff)+
134 end
136 lemma count_diff [simp]: "count (M - N) a = count M a - count N a"
137   by (simp add: minus_multiset.rep_eq)
139 lemma diff_empty [simp]: "M - {#} = M \<and> {#} - M = {#}"
140   by rule (fact Groups.diff_zero, fact Groups.zero_diff)
142 lemma diff_cancel[simp]: "A - A = {#}"
143   by (fact Groups.diff_cancel)
145 lemma diff_union_cancelR [simp]: "M + N - N = (M::'a multiset)"
146   by (fact add_diff_cancel_right')
148 lemma diff_union_cancelL [simp]: "N + M - N = (M::'a multiset)"
149   by (fact add_diff_cancel_left')
151 lemma diff_right_commute:
152   "(M::'a multiset) - N - Q = M - Q - N"
153   by (fact diff_right_commute)
156   "(M::'a multiset) - (N + Q) = M - N - Q"
157   by (rule sym) (fact diff_diff_add)
159 lemma insert_DiffM:
160   "x \<in># M \<Longrightarrow> {#x#} + (M - {#x#}) = M"
161   by (clarsimp simp: multiset_eq_iff)
163 lemma insert_DiffM2 [simp]:
164   "x \<in># M \<Longrightarrow> M - {#x#} + {#x#} = M"
165   by (clarsimp simp: multiset_eq_iff)
167 lemma diff_union_swap:
168   "a \<noteq> b \<Longrightarrow> M - {#a#} + {#b#} = M + {#b#} - {#a#}"
169   by (auto simp add: multiset_eq_iff)
171 lemma diff_union_single_conv:
172   "a \<in># J \<Longrightarrow> I + J - {#a#} = I + (J - {#a#})"
173   by (simp add: multiset_eq_iff)
176 subsubsection {* Equality of multisets *}
178 lemma single_not_empty [simp]: "{#a#} \<noteq> {#} \<and> {#} \<noteq> {#a#}"
179   by (simp add: multiset_eq_iff)
181 lemma single_eq_single [simp]: "{#a#} = {#b#} \<longleftrightarrow> a = b"
182   by (auto simp add: multiset_eq_iff)
184 lemma union_eq_empty [iff]: "M + N = {#} \<longleftrightarrow> M = {#} \<and> N = {#}"
185   by (auto simp add: multiset_eq_iff)
187 lemma empty_eq_union [iff]: "{#} = M + N \<longleftrightarrow> M = {#} \<and> N = {#}"
188   by (auto simp add: multiset_eq_iff)
190 lemma multi_self_add_other_not_self [simp]: "M = M + {#x#} \<longleftrightarrow> False"
191   by (auto simp add: multiset_eq_iff)
193 lemma diff_single_trivial:
194   "\<not> x \<in># M \<Longrightarrow> M - {#x#} = M"
195   by (auto simp add: multiset_eq_iff)
197 lemma diff_single_eq_union:
198   "x \<in># M \<Longrightarrow> M - {#x#} = N \<longleftrightarrow> M = N + {#x#}"
199   by auto
201 lemma union_single_eq_diff:
202   "M + {#x#} = N \<Longrightarrow> M = N - {#x#}"
203   by (auto dest: sym)
205 lemma union_single_eq_member:
206   "M + {#x#} = N \<Longrightarrow> x \<in># N"
207   by auto
209 lemma union_is_single:
210   "M + N = {#a#} \<longleftrightarrow> M = {#a#} \<and> N={#} \<or> M = {#} \<and> N = {#a#}" (is "?lhs = ?rhs")
211 proof
212   assume ?rhs then show ?lhs by auto
213 next
214   assume ?lhs then show ?rhs
215     by (simp add: multiset_eq_iff split:if_splits) (metis add_is_1)
216 qed
218 lemma single_is_union:
219   "{#a#} = M + N \<longleftrightarrow> {#a#} = M \<and> N = {#} \<or> M = {#} \<and> {#a#} = N"
220   by (auto simp add: eq_commute [of "{#a#}" "M + N"] union_is_single)
223   "M + {#a#} = N + {#b#} \<longleftrightarrow> M = N \<and> a = b \<or> M = N - {#a#} + {#b#} \<and> N = M - {#b#} + {#a#}"  (is "?lhs = ?rhs")
224 (* shorter: by (simp add: multiset_eq_iff) fastforce *)
225 proof
226   assume ?rhs then show ?lhs
228     (drule sym, simp add: add_assoc [symmetric])
229 next
230   assume ?lhs
231   show ?rhs
232   proof (cases "a = b")
233     case True with `?lhs` show ?thesis by simp
234   next
235     case False
236     from `?lhs` have "a \<in># N + {#b#}" by (rule union_single_eq_member)
237     with False have "a \<in># N" by auto
238     moreover from `?lhs` have "M = N + {#b#} - {#a#}" by (rule union_single_eq_diff)
239     moreover note False
240     ultimately show ?thesis by (auto simp add: diff_right_commute [of _ "{#a#}"] diff_union_swap)
241   qed
242 qed
244 lemma insert_noteq_member:
245   assumes BC: "B + {#b#} = C + {#c#}"
246    and bnotc: "b \<noteq> c"
247   shows "c \<in># B"
248 proof -
249   have "c \<in># C + {#c#}" by simp
250   have nc: "\<not> c \<in># {#b#}" using bnotc by simp
251   then have "c \<in># B + {#b#}" using BC by simp
252   then show "c \<in># B" using nc by simp
253 qed
256   "(M + {#a#} = N + {#b#}) =
257     (M = N \<and> a = b \<or> (\<exists>K. M = K + {#b#} \<and> N = K + {#a#}))"
260 lemma multi_member_split:
261   "x \<in># M \<Longrightarrow> \<exists>A. M = A + {#x#}"
262   by (rule_tac x = "M - {#x#}" in exI, simp)
265 subsubsection {* Pointwise ordering induced by count *}
267 instantiation multiset :: (type) ordered_ab_semigroup_add_imp_le
268 begin
270 lift_definition less_eq_multiset :: "'a multiset \<Rightarrow> 'a multiset \<Rightarrow> bool" is "\<lambda> A B. (\<forall>a. A a \<le> B a)"
271 by simp
272 lemmas mset_le_def = less_eq_multiset_def
274 definition less_multiset :: "'a multiset \<Rightarrow> 'a multiset \<Rightarrow> bool" where
275   mset_less_def: "(A::'a multiset) < B \<longleftrightarrow> A \<le> B \<and> A \<noteq> B"
277 instance
278   by default (auto simp add: mset_le_def mset_less_def multiset_eq_iff intro: order_trans antisym)
280 end
282 lemma mset_less_eqI:
283   "(\<And>x. count A x \<le> count B x) \<Longrightarrow> A \<le> B"
284   by (simp add: mset_le_def)
286 lemma mset_le_exists_conv:
287   "(A::'a multiset) \<le> B \<longleftrightarrow> (\<exists>C. B = A + C)"
288 apply (unfold mset_le_def, rule iffI, rule_tac x = "B - A" in exI)
289 apply (auto intro: multiset_eq_iff [THEN iffD2])
290 done
292 instance multiset :: (type) ordered_cancel_comm_monoid_diff
293   by default (simp, fact mset_le_exists_conv)
295 lemma mset_le_mono_add_right_cancel [simp]:
296   "(A::'a multiset) + C \<le> B + C \<longleftrightarrow> A \<le> B"
297   by (fact add_le_cancel_right)
299 lemma mset_le_mono_add_left_cancel [simp]:
300   "C + (A::'a multiset) \<le> C + B \<longleftrightarrow> A \<le> B"
301   by (fact add_le_cancel_left)
304   "(A::'a multiset) \<le> B \<Longrightarrow> C \<le> D \<Longrightarrow> A + C \<le> B + D"
305   by (fact add_mono)
307 lemma mset_le_add_left [simp]:
308   "(A::'a multiset) \<le> A + B"
309   unfolding mset_le_def by auto
311 lemma mset_le_add_right [simp]:
312   "B \<le> (A::'a multiset) + B"
313   unfolding mset_le_def by auto
315 lemma mset_le_single:
316   "a :# B \<Longrightarrow> {#a#} \<le> B"
317   by (simp add: mset_le_def)
319 lemma multiset_diff_union_assoc:
320   "C \<le> B \<Longrightarrow> (A::'a multiset) + B - C = A + (B - C)"
321   by (simp add: multiset_eq_iff mset_le_def)
323 lemma mset_le_multiset_union_diff_commute:
324   "B \<le> A \<Longrightarrow> (A::'a multiset) - B + C = A + C - B"
325 by (simp add: multiset_eq_iff mset_le_def)
327 lemma diff_le_self[simp]: "(M::'a multiset) - N \<le> M"
328 by(simp add: mset_le_def)
330 lemma mset_lessD: "A < B \<Longrightarrow> x \<in># A \<Longrightarrow> x \<in># B"
331 apply (clarsimp simp: mset_le_def mset_less_def)
332 apply (erule_tac x=x in allE)
333 apply auto
334 done
336 lemma mset_leD: "A \<le> B \<Longrightarrow> x \<in># A \<Longrightarrow> x \<in># B"
337 apply (clarsimp simp: mset_le_def mset_less_def)
338 apply (erule_tac x = x in allE)
339 apply auto
340 done
342 lemma mset_less_insertD: "(A + {#x#} < B) \<Longrightarrow> (x \<in># B \<and> A < B)"
343 apply (rule conjI)
344  apply (simp add: mset_lessD)
345 apply (clarsimp simp: mset_le_def mset_less_def)
346 apply safe
347  apply (erule_tac x = a in allE)
348  apply (auto split: split_if_asm)
349 done
351 lemma mset_le_insertD: "(A + {#x#} \<le> B) \<Longrightarrow> (x \<in># B \<and> A \<le> B)"
352 apply (rule conjI)
353  apply (simp add: mset_leD)
354 apply (force simp: mset_le_def mset_less_def split: split_if_asm)
355 done
357 lemma mset_less_of_empty[simp]: "A < {#} \<longleftrightarrow> False"
358   by (auto simp add: mset_less_def mset_le_def multiset_eq_iff)
360 lemma multi_psub_of_add_self[simp]: "A < A + {#x#}"
361   by (auto simp: mset_le_def mset_less_def)
363 lemma multi_psub_self[simp]: "(A::'a multiset) < A = False"
364   by simp
367   "T + {#x#} < S + {#x#} \<Longrightarrow> T < S"
368   by (fact add_less_imp_less_right)
370 lemma mset_less_empty_nonempty:
371   "{#} < S \<longleftrightarrow> S \<noteq> {#}"
372   by (auto simp: mset_le_def mset_less_def)
374 lemma mset_less_diff_self:
375   "c \<in># B \<Longrightarrow> B - {#c#} < B"
376   by (auto simp: mset_le_def mset_less_def multiset_eq_iff)
379 subsubsection {* Intersection *}
381 instantiation multiset :: (type) semilattice_inf
382 begin
384 definition inf_multiset :: "'a multiset \<Rightarrow> 'a multiset \<Rightarrow> 'a multiset" where
385   multiset_inter_def: "inf_multiset A B = A - (A - B)"
387 instance
388 proof -
389   have aux: "\<And>m n q :: nat. m \<le> n \<Longrightarrow> m \<le> q \<Longrightarrow> m \<le> n - (n - q)" by arith
390   show "OFCLASS('a multiset, semilattice_inf_class)"
391     by default (auto simp add: multiset_inter_def mset_le_def aux)
392 qed
394 end
396 abbreviation multiset_inter :: "'a multiset \<Rightarrow> 'a multiset \<Rightarrow> 'a multiset" (infixl "#\<inter>" 70) where
397   "multiset_inter \<equiv> inf"
399 lemma multiset_inter_count [simp]:
400   "count (A #\<inter> B) x = min (count A x) (count B x)"
401   by (simp add: multiset_inter_def)
403 lemma multiset_inter_single: "a \<noteq> b \<Longrightarrow> {#a#} #\<inter> {#b#} = {#}"
404   by (rule multiset_eqI) auto
406 lemma multiset_union_diff_commute:
407   assumes "B #\<inter> C = {#}"
408   shows "A + B - C = A - C + B"
409 proof (rule multiset_eqI)
410   fix x
411   from assms have "min (count B x) (count C x) = 0"
412     by (auto simp add: multiset_eq_iff)
413   then have "count B x = 0 \<or> count C x = 0"
414     by auto
415   then show "count (A + B - C) x = count (A - C + B) x"
416     by auto
417 qed
419 lemma empty_inter [simp]:
420   "{#} #\<inter> M = {#}"
421   by (simp add: multiset_eq_iff)
423 lemma inter_empty [simp]:
424   "M #\<inter> {#} = {#}"
425   by (simp add: multiset_eq_iff)
428   "\<not> x \<in># N \<Longrightarrow> (M + {#x#}) #\<inter> N = M #\<inter> N"
429   by (simp add: multiset_eq_iff)
432   "x \<in># N \<Longrightarrow> (M + {#x#}) #\<inter> N = (M #\<inter> (N - {#x#})) + {#x#}"
433   by (simp add: multiset_eq_iff)
436   "\<not> x \<in># N \<Longrightarrow> N #\<inter> (M + {#x#}) = N #\<inter> M"
437   by (simp add: multiset_eq_iff)
440   "x \<in># N \<Longrightarrow> N #\<inter> (M + {#x#}) = ((N - {#x#}) #\<inter> M) + {#x#}"
441   by (simp add: multiset_eq_iff)
444 subsubsection {* Bounded union *}
446 instantiation multiset :: (type) semilattice_sup
447 begin
449 definition sup_multiset :: "'a multiset \<Rightarrow> 'a multiset \<Rightarrow> 'a multiset" where
450   "sup_multiset A B = A + (B - A)"
452 instance
453 proof -
454   have aux: "\<And>m n q :: nat. m \<le> n \<Longrightarrow> q \<le> n \<Longrightarrow> m + (q - m) \<le> n" by arith
455   show "OFCLASS('a multiset, semilattice_sup_class)"
456     by default (auto simp add: sup_multiset_def mset_le_def aux)
457 qed
459 end
461 abbreviation sup_multiset :: "'a multiset \<Rightarrow> 'a multiset \<Rightarrow> 'a multiset" (infixl "#\<union>" 70) where
462   "sup_multiset \<equiv> sup"
464 lemma sup_multiset_count [simp]:
465   "count (A #\<union> B) x = max (count A x) (count B x)"
466   by (simp add: sup_multiset_def)
468 lemma empty_sup [simp]:
469   "{#} #\<union> M = M"
470   by (simp add: multiset_eq_iff)
472 lemma sup_empty [simp]:
473   "M #\<union> {#} = M"
474   by (simp add: multiset_eq_iff)
477   "\<not> x \<in># N \<Longrightarrow> (M + {#x#}) #\<union> N = (M #\<union> N) + {#x#}"
478   by (simp add: multiset_eq_iff)
481   "x \<in># N \<Longrightarrow> (M + {#x#}) #\<union> N = (M #\<union> (N - {#x#})) + {#x#}"
482   by (simp add: multiset_eq_iff)
485   "\<not> x \<in># N \<Longrightarrow> N #\<union> (M + {#x#}) = (N #\<union> M) + {#x#}"
486   by (simp add: multiset_eq_iff)
489   "x \<in># N \<Longrightarrow> N #\<union> (M + {#x#}) = ((N - {#x#}) #\<union> M) + {#x#}"
490   by (simp add: multiset_eq_iff)
493 subsubsection {* Filter (with comprehension syntax) *}
495 text {* Multiset comprehension *}
497 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"
498 by (rule filter_preserves_multiset)
500 hide_const (open) filter
502 lemma count_filter [simp]:
503   "count (Multiset.filter P M) a = (if P a then count M a else 0)"
504   by (simp add: filter.rep_eq)
506 lemma filter_empty [simp]:
507   "Multiset.filter P {#} = {#}"
508   by (rule multiset_eqI) simp
510 lemma filter_single [simp]:
511   "Multiset.filter P {#x#} = (if P x then {#x#} else {#})"
512   by (rule multiset_eqI) simp
514 lemma filter_union [simp]:
515   "Multiset.filter P (M + N) = Multiset.filter P M + Multiset.filter P N"
516   by (rule multiset_eqI) simp
518 lemma filter_diff [simp]:
519   "Multiset.filter P (M - N) = Multiset.filter P M - Multiset.filter P N"
520   by (rule multiset_eqI) simp
522 lemma filter_inter [simp]:
523   "Multiset.filter P (M #\<inter> N) = Multiset.filter P M #\<inter> Multiset.filter P N"
524   by (rule multiset_eqI) simp
526 syntax
527   "_MCollect" :: "pttrn \<Rightarrow> 'a multiset \<Rightarrow> bool \<Rightarrow> 'a multiset"    ("(1{# _ :# _./ _#})")
528 syntax (xsymbol)
529   "_MCollect" :: "pttrn \<Rightarrow> 'a multiset \<Rightarrow> bool \<Rightarrow> 'a multiset"    ("(1{# _ \<in># _./ _#})")
530 translations
531   "{#x \<in># M. P#}" == "CONST Multiset.filter (\<lambda>x. P) M"
534 subsubsection {* Set of elements *}
536 definition set_of :: "'a multiset => 'a set" where
537   "set_of M = {x. x :# M}"
539 lemma set_of_empty [simp]: "set_of {#} = {}"
540 by (simp add: set_of_def)
542 lemma set_of_single [simp]: "set_of {#b#} = {b}"
543 by (simp add: set_of_def)
545 lemma set_of_union [simp]: "set_of (M + N) = set_of M \<union> set_of N"
546 by (auto simp add: set_of_def)
548 lemma set_of_eq_empty_iff [simp]: "(set_of M = {}) = (M = {#})"
549 by (auto simp add: set_of_def multiset_eq_iff)
551 lemma mem_set_of_iff [simp]: "(x \<in> set_of M) = (x :# M)"
552 by (auto simp add: set_of_def)
554 lemma set_of_filter [simp]: "set_of {# x:#M. P x #} = set_of M \<inter> {x. P x}"
555 by (auto simp add: set_of_def)
557 lemma finite_set_of [iff]: "finite (set_of M)"
558   using count [of M] by (simp add: multiset_def set_of_def)
560 lemma finite_Collect_mem [iff]: "finite {x. x :# M}"
561   unfolding set_of_def[symmetric] by simp
563 subsubsection {* Size *}
565 instantiation multiset :: (type) size
566 begin
568 definition size_def:
569   "size M = setsum (count M) (set_of M)"
571 instance ..
573 end
575 lemma size_empty [simp]: "size {#} = 0"
576 by (simp add: size_def)
578 lemma size_single [simp]: "size {#b#} = 1"
579 by (simp add: size_def)
581 lemma setsum_count_Int:
582   "finite A ==> setsum (count N) (A \<inter> set_of N) = setsum (count N) A"
583 apply (induct rule: finite_induct)
584  apply simp
585 apply (simp add: Int_insert_left set_of_def)
586 done
588 lemma size_union [simp]: "size (M + N::'a multiset) = size M + size N"
589 apply (unfold size_def)
590 apply (subgoal_tac "count (M + N) = (\<lambda>a. count M a + count N a)")
591  prefer 2
592  apply (rule ext, simp)
593 apply (simp (no_asm_simp) add: setsum_Un_nat setsum_addf setsum_count_Int)
594 apply (subst Int_commute)
595 apply (simp (no_asm_simp) add: setsum_count_Int)
596 done
598 lemma size_eq_0_iff_empty [iff]: "(size M = 0) = (M = {#})"
599 by (auto simp add: size_def multiset_eq_iff)
601 lemma nonempty_has_size: "(S \<noteq> {#}) = (0 < size S)"
602 by (metis gr0I gr_implies_not0 size_empty size_eq_0_iff_empty)
604 lemma size_eq_Suc_imp_elem: "size M = Suc n ==> \<exists>a. a :# M"
605 apply (unfold size_def)
606 apply (drule setsum_SucD)
607 apply auto
608 done
610 lemma size_eq_Suc_imp_eq_union:
611   assumes "size M = Suc n"
612   shows "\<exists>a N. M = N + {#a#}"
613 proof -
614   from assms obtain a where "a \<in># M"
615     by (erule size_eq_Suc_imp_elem [THEN exE])
616   then have "M = M - {#a#} + {#a#}" by simp
617   then show ?thesis by blast
618 qed
621 subsection {* Induction and case splits *}
623 theorem multiset_induct [case_names empty add, induct type: multiset]:
624   assumes empty: "P {#}"
625   assumes add: "\<And>M x. P M \<Longrightarrow> P (M + {#x#})"
626   shows "P M"
627 proof (induct n \<equiv> "size M" arbitrary: M)
628   case 0 thus "P M" by (simp add: empty)
629 next
630   case (Suc k)
631   obtain N x where "M = N + {#x#}"
632     using `Suc k = size M` [symmetric]
633     using size_eq_Suc_imp_eq_union by fast
634   with Suc add show "P M" by simp
635 qed
637 lemma multi_nonempty_split: "M \<noteq> {#} \<Longrightarrow> \<exists>A a. M = A + {#a#}"
638 by (induct M) auto
640 lemma multiset_cases [cases type, case_names empty add]:
641 assumes em:  "M = {#} \<Longrightarrow> P"
642 assumes add: "\<And>N x. M = N + {#x#} \<Longrightarrow> P"
643 shows "P"
644 using assms by (induct M) simp_all
646 lemma multi_drop_mem_not_eq: "c \<in># B \<Longrightarrow> B - {#c#} \<noteq> B"
647 by (cases "B = {#}") (auto dest: multi_member_split)
649 lemma multiset_partition: "M = {# x:#M. P x #} + {# x:#M. \<not> P x #}"
650 apply (subst multiset_eq_iff)
651 apply auto
652 done
654 lemma mset_less_size: "(A::'a multiset) < B \<Longrightarrow> size A < size B"
655 proof (induct A arbitrary: B)
656   case (empty M)
657   then have "M \<noteq> {#}" by (simp add: mset_less_empty_nonempty)
658   then obtain M' x where "M = M' + {#x#}"
659     by (blast dest: multi_nonempty_split)
660   then show ?case by simp
661 next
662   case (add S x T)
663   have IH: "\<And>B. S < B \<Longrightarrow> size S < size B" by fact
664   have SxsubT: "S + {#x#} < T" by fact
665   then have "x \<in># T" and "S < T" by (auto dest: mset_less_insertD)
666   then obtain T' where T: "T = T' + {#x#}"
667     by (blast dest: multi_member_split)
668   then have "S < T'" using SxsubT
669     by (blast intro: mset_less_add_bothsides)
670   then have "size S < size T'" using IH by simp
671   then show ?case using T by simp
672 qed
675 subsubsection {* Strong induction and subset induction for multisets *}
677 text {* Well-foundedness of proper subset operator: *}
679 text {* proper multiset subset *}
681 definition
682   mset_less_rel :: "('a multiset * 'a multiset) set" where
683   "mset_less_rel = {(A,B). A < B}"
686   assumes "c \<in># B" and "b \<noteq> c"
687   shows "B - {#c#} + {#b#} = B + {#b#} - {#c#}"
688 proof -
689   from `c \<in># B` obtain A where B: "B = A + {#c#}"
690     by (blast dest: multi_member_split)
691   have "A + {#b#} = A + {#b#} + {#c#} - {#c#}" by simp
692   then have "A + {#b#} = A + {#c#} + {#b#} - {#c#}"
694   then show ?thesis using B by simp
695 qed
697 lemma wf_mset_less_rel: "wf mset_less_rel"
698 apply (unfold mset_less_rel_def)
699 apply (rule wf_measure [THEN wf_subset, where f1=size])
700 apply (clarsimp simp: measure_def inv_image_def mset_less_size)
701 done
703 text {* The induction rules: *}
705 lemma full_multiset_induct [case_names less]:
706 assumes ih: "\<And>B. \<forall>(A::'a multiset). A < B \<longrightarrow> P A \<Longrightarrow> P B"
707 shows "P B"
708 apply (rule wf_mset_less_rel [THEN wf_induct])
709 apply (rule ih, auto simp: mset_less_rel_def)
710 done
712 lemma multi_subset_induct [consumes 2, case_names empty add]:
713 assumes "F \<le> A"
714   and empty: "P {#}"
715   and insert: "\<And>a F. a \<in># A \<Longrightarrow> P F \<Longrightarrow> P (F + {#a#})"
716 shows "P F"
717 proof -
718   from `F \<le> A`
719   show ?thesis
720   proof (induct F)
721     show "P {#}" by fact
722   next
723     fix x F
724     assume P: "F \<le> A \<Longrightarrow> P F" and i: "F + {#x#} \<le> A"
725     show "P (F + {#x#})"
726     proof (rule insert)
727       from i show "x \<in># A" by (auto dest: mset_le_insertD)
728       from i have "F \<le> A" by (auto dest: mset_le_insertD)
729       with P show "P F" .
730     qed
731   qed
732 qed
735 subsection {* The fold combinator *}
737 definition fold :: "('a \<Rightarrow> 'b \<Rightarrow> 'b) \<Rightarrow> 'b \<Rightarrow> 'a multiset \<Rightarrow> 'b"
738 where
739   "fold f s M = Finite_Set.fold (\<lambda>x. f x ^^ count M x) s (set_of M)"
741 lemma fold_mset_empty [simp]:
742   "fold f s {#} = s"
743   by (simp add: fold_def)
745 context comp_fun_commute
746 begin
748 lemma fold_mset_insert:
749   "fold f s (M + {#x#}) = f x (fold f s M)"
750 proof -
751   interpret mset: comp_fun_commute "\<lambda>y. f y ^^ count M y"
752     by (fact comp_fun_commute_funpow)
753   interpret mset_union: comp_fun_commute "\<lambda>y. f y ^^ count (M + {#x#}) y"
754     by (fact comp_fun_commute_funpow)
755   show ?thesis
756   proof (cases "x \<in> set_of M")
757     case False
758     then have *: "count (M + {#x#}) x = 1" by simp
759     from False have "Finite_Set.fold (\<lambda>y. f y ^^ count (M + {#x#}) y) s (set_of M) =
760       Finite_Set.fold (\<lambda>y. f y ^^ count M y) s (set_of M)"
761       by (auto intro!: Finite_Set.fold_cong comp_fun_commute_funpow)
762     with False * show ?thesis
763       by (simp add: fold_def del: count_union)
764   next
765     case True
766     def N \<equiv> "set_of M - {x}"
767     from N_def True have *: "set_of M = insert x N" "x \<notin> N" "finite N" by auto
768     then have "Finite_Set.fold (\<lambda>y. f y ^^ count (M + {#x#}) y) s N =
769       Finite_Set.fold (\<lambda>y. f y ^^ count M y) s N"
770       by (auto intro!: Finite_Set.fold_cong comp_fun_commute_funpow)
771     with * show ?thesis by (simp add: fold_def del: count_union) simp
772   qed
773 qed
775 corollary fold_mset_single [simp]:
776   "fold f s {#x#} = f x s"
777 proof -
778   have "fold f s ({#} + {#x#}) = f x s" by (simp only: fold_mset_insert) simp
779   then show ?thesis by simp
780 qed
782 lemma fold_mset_fun_left_comm:
783   "f x (fold f s M) = fold f (f x s) M"
784   by (induct M) (simp_all add: fold_mset_insert fun_left_comm)
786 lemma fold_mset_union [simp]:
787   "fold f s (M + N) = fold f (fold f s M) N"
788 proof (induct M)
789   case empty then show ?case by simp
790 next
791   case (add M x)
792   have "M + {#x#} + N = (M + N) + {#x#}"
794   with add show ?case by (simp add: fold_mset_insert fold_mset_fun_left_comm)
795 qed
797 lemma fold_mset_fusion:
798   assumes "comp_fun_commute g"
799   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")
800 proof -
801   interpret comp_fun_commute g by (fact assms)
802   show "PROP ?P" by (induct A) auto
803 qed
805 end
807 text {*
808   A note on code generation: When defining some function containing a
809   subterm @{term "fold F"}, code generation is not automatic. When
810   interpreting locale @{text left_commutative} with @{text F}, the
811   would be code thms for @{const fold} become thms like
812   @{term "fold F z {#} = z"} where @{text F} is not a pattern but
813   contains defined symbols, i.e.\ is not a code thm. Hence a separate
814   constant with its own code thms needs to be introduced for @{text
815   F}. See the image operator below.
816 *}
819 subsection {* Image *}
821 definition image_mset :: "('a \<Rightarrow> 'b) \<Rightarrow> 'a multiset \<Rightarrow> 'b multiset" where
822   "image_mset f = fold (plus o single o f) {#}"
824 lemma comp_fun_commute_mset_image:
825   "comp_fun_commute (plus o single o f)"
826 proof
829 lemma image_mset_empty [simp]: "image_mset f {#} = {#}"
830   by (simp add: image_mset_def)
832 lemma image_mset_single [simp]: "image_mset f {#x#} = {#f x#}"
833 proof -
834   interpret comp_fun_commute "plus o single o f"
835     by (fact comp_fun_commute_mset_image)
836   show ?thesis by (simp add: image_mset_def)
837 qed
839 lemma image_mset_union [simp]:
840   "image_mset f (M + N) = image_mset f M + image_mset f N"
841 proof -
842   interpret comp_fun_commute "plus o single o f"
843     by (fact comp_fun_commute_mset_image)
844   show ?thesis by (induct N) (simp_all add: image_mset_def add_ac)
845 qed
847 corollary image_mset_insert:
848   "image_mset f (M + {#a#}) = image_mset f M + {#f a#}"
849   by simp
851 lemma set_of_image_mset [simp]:
852   "set_of (image_mset f M) = image f (set_of M)"
853   by (induct M) simp_all
855 lemma size_image_mset [simp]:
856   "size (image_mset f M) = size M"
857   by (induct M) simp_all
859 lemma image_mset_is_empty_iff [simp]:
860   "image_mset f M = {#} \<longleftrightarrow> M = {#}"
861   by (cases M) auto
863 syntax
864   "_comprehension1_mset" :: "'a \<Rightarrow> 'b \<Rightarrow> 'b multiset \<Rightarrow> 'a multiset"
865       ("({#_/. _ :# _#})")
866 translations
867   "{#e. x:#M#}" == "CONST image_mset (%x. e) M"
869 syntax
870   "_comprehension2_mset" :: "'a \<Rightarrow> 'b \<Rightarrow> 'b multiset \<Rightarrow> bool \<Rightarrow> 'a multiset"
871       ("({#_/ | _ :# _./ _#})")
872 translations
873   "{#e | x:#M. P#}" => "{#e. x :# {# x:#M. P#}#}"
875 text {*
876   This allows to write not just filters like @{term "{#x:#M. x<c#}"}
877   but also images like @{term "{#x+x. x:#M #}"} and @{term [source]
878   "{#x+x|x:#M. x<c#}"}, where the latter is currently displayed as
879   @{term "{#x+x|x:#M. x<c#}"}.
880 *}
882 enriched_type image_mset: image_mset
883 proof -
884   fix f g show "image_mset f \<circ> image_mset g = image_mset (f \<circ> g)"
885   proof
886     fix A
887     show "(image_mset f \<circ> image_mset g) A = image_mset (f \<circ> g) A"
888       by (induct A) simp_all
889   qed
890   show "image_mset id = id"
891   proof
892     fix A
893     show "image_mset id A = id A"
894       by (induct A) simp_all
895   qed
896 qed
898 declare image_mset.identity [simp]
901 subsection {* Further conversions *}
903 primrec multiset_of :: "'a list \<Rightarrow> 'a multiset" where
904   "multiset_of [] = {#}" |
905   "multiset_of (a # x) = multiset_of x + {# a #}"
907 lemma in_multiset_in_set:
908   "x \<in># multiset_of xs \<longleftrightarrow> x \<in> set xs"
909   by (induct xs) simp_all
911 lemma count_multiset_of:
912   "count (multiset_of xs) x = length (filter (\<lambda>y. x = y) xs)"
913   by (induct xs) simp_all
915 lemma multiset_of_zero_iff[simp]: "(multiset_of x = {#}) = (x = [])"
916 by (induct x) auto
918 lemma multiset_of_zero_iff_right[simp]: "({#} = multiset_of x) = (x = [])"
919 by (induct x) auto
921 lemma set_of_multiset_of[simp]: "set_of (multiset_of x) = set x"
922 by (induct x) auto
924 lemma mem_set_multiset_eq: "x \<in> set xs = (x :# multiset_of xs)"
925 by (induct xs) auto
927 lemma size_multiset_of [simp]: "size (multiset_of xs) = length xs"
928   by (induct xs) simp_all
930 lemma multiset_of_append [simp]:
931   "multiset_of (xs @ ys) = multiset_of xs + multiset_of ys"
932   by (induct xs arbitrary: ys) (auto simp: add_ac)
934 lemma multiset_of_filter:
935   "multiset_of (filter P xs) = {#x :# multiset_of xs. P x #}"
936   by (induct xs) simp_all
938 lemma multiset_of_rev [simp]:
939   "multiset_of (rev xs) = multiset_of xs"
940   by (induct xs) simp_all
942 lemma surj_multiset_of: "surj multiset_of"
943 apply (unfold surj_def)
944 apply (rule allI)
945 apply (rule_tac M = y in multiset_induct)
946  apply auto
947 apply (rule_tac x = "x # xa" in exI)
948 apply auto
949 done
951 lemma set_count_greater_0: "set x = {a. count (multiset_of x) a > 0}"
952 by (induct x) auto
954 lemma distinct_count_atmost_1:
955   "distinct x = (! a. count (multiset_of x) a = (if a \<in> set x then 1 else 0))"
956 apply (induct x, simp, rule iffI, simp_all)
957 apply (rule conjI)
958 apply (simp_all add: set_of_multiset_of [THEN sym] del: set_of_multiset_of)
959 apply (erule_tac x = a in allE, simp, clarify)
960 apply (erule_tac x = aa in allE, simp)
961 done
963 lemma multiset_of_eq_setD:
964   "multiset_of xs = multiset_of ys \<Longrightarrow> set xs = set ys"
965 by (rule) (auto simp add:multiset_eq_iff set_count_greater_0)
967 lemma set_eq_iff_multiset_of_eq_distinct:
968   "distinct x \<Longrightarrow> distinct y \<Longrightarrow>
969     (set x = set y) = (multiset_of x = multiset_of y)"
970 by (auto simp: multiset_eq_iff distinct_count_atmost_1)
972 lemma set_eq_iff_multiset_of_remdups_eq:
973    "(set x = set y) = (multiset_of (remdups x) = multiset_of (remdups y))"
974 apply (rule iffI)
975 apply (simp add: set_eq_iff_multiset_of_eq_distinct[THEN iffD1])
976 apply (drule distinct_remdups [THEN distinct_remdups
977       [THEN set_eq_iff_multiset_of_eq_distinct [THEN iffD2]]])
978 apply simp
979 done
981 lemma multiset_of_compl_union [simp]:
982   "multiset_of [x\<leftarrow>xs. P x] + multiset_of [x\<leftarrow>xs. \<not>P x] = multiset_of xs"
983   by (induct xs) (auto simp: add_ac)
985 lemma count_multiset_of_length_filter:
986   "count (multiset_of xs) x = length (filter (\<lambda>y. x = y) xs)"
987   by (induct xs) auto
989 lemma nth_mem_multiset_of: "i < length ls \<Longrightarrow> (ls ! i) :# multiset_of ls"
990 apply (induct ls arbitrary: i)
991  apply simp
992 apply (case_tac i)
993  apply auto
994 done
996 lemma multiset_of_remove1[simp]:
997   "multiset_of (remove1 a xs) = multiset_of xs - {#a#}"
998 by (induct xs) (auto simp add: multiset_eq_iff)
1000 lemma multiset_of_eq_length:
1001   assumes "multiset_of xs = multiset_of ys"
1002   shows "length xs = length ys"
1003   using assms by (metis size_multiset_of)
1005 lemma multiset_of_eq_length_filter:
1006   assumes "multiset_of xs = multiset_of ys"
1007   shows "length (filter (\<lambda>x. z = x) xs) = length (filter (\<lambda>y. z = y) ys)"
1008   using assms by (metis count_multiset_of)
1010 lemma fold_multiset_equiv:
1011   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"
1012     and equiv: "multiset_of xs = multiset_of ys"
1013   shows "List.fold f xs = List.fold f ys"
1014 using f equiv [symmetric]
1015 proof (induct xs arbitrary: ys)
1016   case Nil then show ?case by simp
1017 next
1018   case (Cons x xs)
1019   then have *: "set ys = set (x # xs)" by (blast dest: multiset_of_eq_setD)
1020   have "\<And>x y. x \<in> set ys \<Longrightarrow> y \<in> set ys \<Longrightarrow> f x \<circ> f y = f y \<circ> f x"
1021     by (rule Cons.prems(1)) (simp_all add: *)
1022   moreover from * have "x \<in> set ys" by simp
1023   ultimately have "List.fold f ys = List.fold f (remove1 x ys) \<circ> f x" by (fact fold_remove1_split)
1024   moreover from Cons.prems have "List.fold f xs = List.fold f (remove1 x ys)" by (auto intro: Cons.hyps)
1025   ultimately show ?case by simp
1026 qed
1028 lemma multiset_of_insort [simp]:
1029   "multiset_of (insort x xs) = multiset_of xs + {#x#}"
1030   by (induct xs) (simp_all add: ac_simps)
1032 lemma in_multiset_of:
1033   "x \<in># multiset_of xs \<longleftrightarrow> x \<in> set xs"
1034   by (induct xs) simp_all
1036 lemma multiset_of_map:
1037   "multiset_of (map f xs) = image_mset f (multiset_of xs)"
1038   by (induct xs) simp_all
1040 definition multiset_of_set :: "'a set \<Rightarrow> 'a multiset"
1041 where
1042   "multiset_of_set = folding.F (\<lambda>x M. {#x#} + M) {#}"
1044 interpretation multiset_of_set!: folding "\<lambda>x M. {#x#} + M" "{#}"
1045 where
1046   "folding.F (\<lambda>x M. {#x#} + M) {#} = multiset_of_set"
1047 proof -
1048   interpret comp_fun_commute "\<lambda>x M. {#x#} + M" by default (simp add: fun_eq_iff ac_simps)
1049   show "folding (\<lambda>x M. {#x#} + M)" by default (fact comp_fun_commute)
1050   from multiset_of_set_def show "folding.F (\<lambda>x M. {#x#} + M) {#} = multiset_of_set" ..
1051 qed
1053 lemma count_multiset_of_set [simp]:
1054   "finite A \<Longrightarrow> x \<in> A \<Longrightarrow> count (multiset_of_set A) x = 1" (is "PROP ?P")
1055   "\<not> finite A \<Longrightarrow> count (multiset_of_set A) x = 0" (is "PROP ?Q")
1056   "x \<notin> A \<Longrightarrow> count (multiset_of_set A) x = 0" (is "PROP ?R")
1057 proof -
1058   { fix A
1059     assume "x \<notin> A"
1060     have "count (multiset_of_set A) x = 0"
1061     proof (cases "finite A")
1062       case False then show ?thesis by simp
1063     next
1064       case True from True `x \<notin> A` show ?thesis by (induct A) auto
1065     qed
1066   } note * = this
1067   then show "PROP ?P" "PROP ?Q" "PROP ?R"
1068   by (auto elim!: Set.set_insert)
1069 qed -- {* TODO: maybe define @{const multiset_of_set} also in terms of @{const Abs_multiset} *}
1071 context linorder
1072 begin
1074 definition sorted_list_of_multiset :: "'a multiset \<Rightarrow> 'a list"
1075 where
1076   "sorted_list_of_multiset M = fold insort [] M"
1078 lemma sorted_list_of_multiset_empty [simp]:
1079   "sorted_list_of_multiset {#} = []"
1080   by (simp add: sorted_list_of_multiset_def)
1082 lemma sorted_list_of_multiset_singleton [simp]:
1083   "sorted_list_of_multiset {#x#} = [x]"
1084 proof -
1085   interpret comp_fun_commute insort by (fact comp_fun_commute_insort)
1086   show ?thesis by (simp add: sorted_list_of_multiset_def)
1087 qed
1089 lemma sorted_list_of_multiset_insert [simp]:
1090   "sorted_list_of_multiset (M + {#x#}) = List.insort x (sorted_list_of_multiset M)"
1091 proof -
1092   interpret comp_fun_commute insort by (fact comp_fun_commute_insort)
1093   show ?thesis by (simp add: sorted_list_of_multiset_def)
1094 qed
1096 end
1098 lemma multiset_of_sorted_list_of_multiset [simp]:
1099   "multiset_of (sorted_list_of_multiset M) = M"
1100   by (induct M) simp_all
1102 lemma sorted_list_of_multiset_multiset_of [simp]:
1103   "sorted_list_of_multiset (multiset_of xs) = sort xs"
1104   by (induct xs) simp_all
1106 lemma finite_set_of_multiset_of_set:
1107   assumes "finite A"
1108   shows "set_of (multiset_of_set A) = A"
1109   using assms by (induct A) simp_all
1111 lemma infinite_set_of_multiset_of_set:
1112   assumes "\<not> finite A"
1113   shows "set_of (multiset_of_set A) = {}"
1114   using assms by simp
1116 lemma set_sorted_list_of_multiset [simp]:
1117   "set (sorted_list_of_multiset M) = set_of M"
1118   by (induct M) (simp_all add: set_insort)
1120 lemma sorted_list_of_multiset_of_set [simp]:
1121   "sorted_list_of_multiset (multiset_of_set A) = sorted_list_of_set A"
1122   by (cases "finite A") (induct A rule: finite_induct, simp_all add: ac_simps)
1125 subsection {* Big operators *}
1127 no_notation times (infixl "*" 70)
1128 no_notation Groups.one ("1")
1130 locale comm_monoid_mset = comm_monoid
1131 begin
1133 definition F :: "'a multiset \<Rightarrow> 'a"
1134 where
1135   eq_fold: "F M = Multiset.fold f 1 M"
1137 lemma empty [simp]:
1138   "F {#} = 1"
1139   by (simp add: eq_fold)
1141 lemma singleton [simp]:
1142   "F {#x#} = x"
1143 proof -
1144   interpret comp_fun_commute
1145     by default (simp add: fun_eq_iff left_commute)
1146   show ?thesis by (simp add: eq_fold)
1147 qed
1149 lemma union [simp]:
1150   "F (M + N) = F M * F N"
1151 proof -
1152   interpret comp_fun_commute f
1153     by default (simp add: fun_eq_iff left_commute)
1154   show ?thesis by (induct N) (simp_all add: left_commute eq_fold)
1155 qed
1157 end
1159 notation times (infixl "*" 70)
1160 notation Groups.one ("1")
1162 definition (in comm_monoid_add) msetsum :: "'a multiset \<Rightarrow> 'a"
1163 where
1164   "msetsum = comm_monoid_mset.F plus 0"
1166 definition (in comm_monoid_mult) msetprod :: "'a multiset \<Rightarrow> 'a"
1167 where
1168   "msetprod = comm_monoid_mset.F times 1"
1170 sublocale comm_monoid_add < msetsum!: comm_monoid_mset plus 0
1171 where
1172   "comm_monoid_mset.F plus 0 = msetsum"
1173 proof -
1174   show "comm_monoid_mset plus 0" ..
1175   from msetsum_def show "comm_monoid_mset.F plus 0 = msetsum" ..
1176 qed
1179 begin
1181 lemma setsum_unfold_msetsum:
1182   "setsum f A = msetsum (image_mset f (multiset_of_set A))"
1183   by (cases "finite A") (induct A rule: finite_induct, simp_all)
1185 abbreviation msetsum_image :: "('b \<Rightarrow> 'a) \<Rightarrow> 'b multiset \<Rightarrow> 'a"
1186 where
1187   "msetsum_image f M \<equiv> msetsum (image_mset f M)"
1189 end
1191 syntax
1192   "_msetsum_image" :: "pttrn \<Rightarrow> 'b set \<Rightarrow> 'a \<Rightarrow> 'a::comm_monoid_add"
1193       ("(3SUM _:#_. _)" [0, 51, 10] 10)
1195 syntax (xsymbols)
1196   "_msetsum_image" :: "pttrn \<Rightarrow> 'b set \<Rightarrow> 'a \<Rightarrow> 'a::comm_monoid_add"
1197       ("(3\<Sum>_:#_. _)" [0, 51, 10] 10)
1199 syntax (HTML output)
1200   "_msetsum_image" :: "pttrn \<Rightarrow> 'b set \<Rightarrow> 'a \<Rightarrow> 'a::comm_monoid_add"
1201       ("(3\<Sum>_\<in>#_. _)" [0, 51, 10] 10)
1203 translations
1204   "SUM i :# A. b" == "CONST msetsum_image (\<lambda>i. b) A"
1206 sublocale comm_monoid_mult < msetprod!: comm_monoid_mset times 1
1207 where
1208   "comm_monoid_mset.F times 1 = msetprod"
1209 proof -
1210   show "comm_monoid_mset times 1" ..
1211   from msetprod_def show "comm_monoid_mset.F times 1 = msetprod" ..
1212 qed
1214 context comm_monoid_mult
1215 begin
1217 lemma msetprod_empty:
1218   "msetprod {#} = 1"
1219   by (fact msetprod.empty)
1221 lemma msetprod_singleton:
1222   "msetprod {#x#} = x"
1223   by (fact msetprod.singleton)
1225 lemma msetprod_Un:
1226   "msetprod (A + B) = msetprod A * msetprod B"
1227   by (fact msetprod.union)
1229 lemma setprod_unfold_msetprod:
1230   "setprod f A = msetprod (image_mset f (multiset_of_set A))"
1231   by (cases "finite A") (induct A rule: finite_induct, simp_all)
1233 lemma msetprod_multiplicity:
1234   "msetprod M = setprod (\<lambda>x. x ^ count M x) (set_of M)"
1235   by (simp add: Multiset.fold_def setprod.eq_fold msetprod.eq_fold funpow_times_power comp_def)
1237 abbreviation msetprod_image :: "('b \<Rightarrow> 'a) \<Rightarrow> 'b multiset \<Rightarrow> 'a"
1238 where
1239   "msetprod_image f M \<equiv> msetprod (image_mset f M)"
1241 end
1243 syntax
1244   "_msetprod_image" :: "pttrn \<Rightarrow> 'b set \<Rightarrow> 'a \<Rightarrow> 'a::comm_monoid_mult"
1245       ("(3PROD _:#_. _)" [0, 51, 10] 10)
1247 syntax (xsymbols)
1248   "_msetprod_image" :: "pttrn \<Rightarrow> 'b set \<Rightarrow> 'a \<Rightarrow> 'a::comm_monoid_mult"
1249       ("(3\<Prod>_\<in>#_. _)" [0, 51, 10] 10)
1251 syntax (HTML output)
1252   "_msetprod_image" :: "pttrn \<Rightarrow> 'b set \<Rightarrow> 'a \<Rightarrow> 'a::comm_monoid_mult"
1253       ("(3\<Prod>_\<in>#_. _)" [0, 51, 10] 10)
1255 translations
1256   "PROD i :# A. b" == "CONST msetprod_image (\<lambda>i. b) A"
1258 lemma (in comm_semiring_1) dvd_msetprod:
1259   assumes "x \<in># A"
1260   shows "x dvd msetprod A"
1261 proof -
1262   from assms have "A = (A - {#x#}) + {#x#}" by simp
1263   then obtain B where "A = B + {#x#}" ..
1264   then show ?thesis by simp
1265 qed
1268 subsection {* Cardinality *}
1270 definition mcard :: "'a multiset \<Rightarrow> nat"
1271 where
1272   "mcard = msetsum \<circ> image_mset (\<lambda>_. 1)"
1274 lemma mcard_empty [simp]:
1275   "mcard {#} = 0"
1276   by (simp add: mcard_def)
1278 lemma mcard_singleton [simp]:
1279   "mcard {#a#} = Suc 0"
1280   by (simp add: mcard_def)
1282 lemma mcard_plus [simp]:
1283   "mcard (M + N) = mcard M + mcard N"
1284   by (simp add: mcard_def)
1286 lemma mcard_empty_iff [simp]:
1287   "mcard M = 0 \<longleftrightarrow> M = {#}"
1288   by (induct M) simp_all
1290 lemma mcard_unfold_setsum:
1291   "mcard M = setsum (count M) (set_of M)"
1292 proof (induct M)
1293   case empty then show ?case by simp
1294 next
1295   case (add M x) then show ?case
1296     by (cases "x \<in> set_of M")
1297       (simp_all del: mem_set_of_iff add: setsum.distrib setsum.delta' insert_absorb, simp)
1298 qed
1300 lemma size_eq_mcard:
1301   "size = mcard"
1302   by (simp add: fun_eq_iff size_def mcard_unfold_setsum)
1304 lemma mcard_multiset_of:
1305   "mcard (multiset_of xs) = length xs"
1306   by (induct xs) simp_all
1309 subsection {* Alternative representations *}
1311 subsubsection {* Lists *}
1313 context linorder
1314 begin
1316 lemma multiset_of_insort [simp]:
1317   "multiset_of (insort_key k x xs) = {#x#} + multiset_of xs"
1318   by (induct xs) (simp_all add: ac_simps)
1320 lemma multiset_of_sort [simp]:
1321   "multiset_of (sort_key k xs) = multiset_of xs"
1322   by (induct xs) (simp_all add: ac_simps)
1324 text {*
1325   This lemma shows which properties suffice to show that a function
1326   @{text "f"} with @{text "f xs = ys"} behaves like sort.
1327 *}
1329 lemma properties_for_sort_key:
1330   assumes "multiset_of ys = multiset_of xs"
1331   and "\<And>k. k \<in> set ys \<Longrightarrow> filter (\<lambda>x. f k = f x) ys = filter (\<lambda>x. f k = f x) xs"
1332   and "sorted (map f ys)"
1333   shows "sort_key f xs = ys"
1334 using assms
1335 proof (induct xs arbitrary: ys)
1336   case Nil then show ?case by simp
1337 next
1338   case (Cons x xs)
1339   from Cons.prems(2) have
1340     "\<forall>k \<in> set ys. filter (\<lambda>x. f k = f x) (remove1 x ys) = filter (\<lambda>x. f k = f x) xs"
1341     by (simp add: filter_remove1)
1342   with Cons.prems have "sort_key f xs = remove1 x ys"
1343     by (auto intro!: Cons.hyps simp add: sorted_map_remove1)
1344   moreover from Cons.prems have "x \<in> set ys"
1345     by (auto simp add: mem_set_multiset_eq intro!: ccontr)
1346   ultimately show ?case using Cons.prems by (simp add: insort_key_remove1)
1347 qed
1349 lemma properties_for_sort:
1350   assumes multiset: "multiset_of ys = multiset_of xs"
1351   and "sorted ys"
1352   shows "sort xs = ys"
1353 proof (rule properties_for_sort_key)
1354   from multiset show "multiset_of ys = multiset_of xs" .
1355   from `sorted ys` show "sorted (map (\<lambda>x. x) ys)" by simp
1356   from multiset have "\<And>k. length (filter (\<lambda>y. k = y) ys) = length (filter (\<lambda>x. k = x) xs)"
1357     by (rule multiset_of_eq_length_filter)
1358   then have "\<And>k. replicate (length (filter (\<lambda>y. k = y) ys)) k = replicate (length (filter (\<lambda>x. k = x) xs)) k"
1359     by simp
1360   then show "\<And>k. k \<in> set ys \<Longrightarrow> filter (\<lambda>y. k = y) ys = filter (\<lambda>x. k = x) xs"
1361     by (simp add: replicate_length_filter)
1362 qed
1364 lemma sort_key_by_quicksort:
1365   "sort_key f xs = sort_key f [x\<leftarrow>xs. f x < f (xs ! (length xs div 2))]
1366     @ [x\<leftarrow>xs. f x = f (xs ! (length xs div 2))]
1367     @ sort_key f [x\<leftarrow>xs. f x > f (xs ! (length xs div 2))]" (is "sort_key f ?lhs = ?rhs")
1368 proof (rule properties_for_sort_key)
1369   show "multiset_of ?rhs = multiset_of ?lhs"
1370     by (rule multiset_eqI) (auto simp add: multiset_of_filter)
1371 next
1372   show "sorted (map f ?rhs)"
1373     by (auto simp add: sorted_append intro: sorted_map_same)
1374 next
1375   fix l
1376   assume "l \<in> set ?rhs"
1377   let ?pivot = "f (xs ! (length xs div 2))"
1378   have *: "\<And>x. f l = f x \<longleftrightarrow> f x = f l" by auto
1379   have "[x \<leftarrow> sort_key f xs . f x = f l] = [x \<leftarrow> xs. f x = f l]"
1380     unfolding filter_sort by (rule properties_for_sort_key) (auto intro: sorted_map_same)
1381   with * have **: "[x \<leftarrow> sort_key f xs . f l = f x] = [x \<leftarrow> xs. f l = f x]" by simp
1382   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
1383   then have "\<And>P. [x \<leftarrow> sort_key f xs . P (f x) ?pivot \<and> f l = f x] =
1384     [x \<leftarrow> sort_key f xs. P (f l) ?pivot \<and> f l = f x]" by simp
1385   note *** = this [of "op <"] this [of "op >"] this [of "op ="]
1386   show "[x \<leftarrow> ?rhs. f l = f x] = [x \<leftarrow> ?lhs. f l = f x]"
1387   proof (cases "f l" ?pivot rule: linorder_cases)
1388     case less
1389     then have "f l \<noteq> ?pivot" and "\<not> f l > ?pivot" by auto
1390     with less show ?thesis
1391       by (simp add: filter_sort [symmetric] ** ***)
1392   next
1393     case equal then show ?thesis
1394       by (simp add: * less_le)
1395   next
1396     case greater
1397     then have "f l \<noteq> ?pivot" and "\<not> f l < ?pivot" by auto
1398     with greater show ?thesis
1399       by (simp add: filter_sort [symmetric] ** ***)
1400   qed
1401 qed
1403 lemma sort_by_quicksort:
1404   "sort xs = sort [x\<leftarrow>xs. x < xs ! (length xs div 2)]
1405     @ [x\<leftarrow>xs. x = xs ! (length xs div 2)]
1406     @ sort [x\<leftarrow>xs. x > xs ! (length xs div 2)]" (is "sort ?lhs = ?rhs")
1407   using sort_key_by_quicksort [of "\<lambda>x. x", symmetric] by simp
1409 text {* A stable parametrized quicksort *}
1411 definition part :: "('b \<Rightarrow> 'a) \<Rightarrow> 'a \<Rightarrow> 'b list \<Rightarrow> 'b list \<times> 'b list \<times> 'b list" where
1412   "part f pivot xs = ([x \<leftarrow> xs. f x < pivot], [x \<leftarrow> xs. f x = pivot], [x \<leftarrow> xs. pivot < f x])"
1414 lemma part_code [code]:
1415   "part f pivot [] = ([], [], [])"
1416   "part f pivot (x # xs) = (let (lts, eqs, gts) = part f pivot xs; x' = f x in
1417      if x' < pivot then (x # lts, eqs, gts)
1418      else if x' > pivot then (lts, eqs, x # gts)
1419      else (lts, x # eqs, gts))"
1420   by (auto simp add: part_def Let_def split_def)
1422 lemma sort_key_by_quicksort_code [code]:
1423   "sort_key f xs = (case xs of [] \<Rightarrow> []
1424     | [x] \<Rightarrow> xs
1425     | [x, y] \<Rightarrow> (if f x \<le> f y then xs else [y, x])
1426     | _ \<Rightarrow> (let (lts, eqs, gts) = part f (f (xs ! (length xs div 2))) xs
1427        in sort_key f lts @ eqs @ sort_key f gts))"
1428 proof (cases xs)
1429   case Nil then show ?thesis by simp
1430 next
1431   case (Cons _ ys) note hyps = Cons show ?thesis
1432   proof (cases ys)
1433     case Nil with hyps show ?thesis by simp
1434   next
1435     case (Cons _ zs) note hyps = hyps Cons show ?thesis
1436     proof (cases zs)
1437       case Nil with hyps show ?thesis by auto
1438     next
1439       case Cons
1440       from sort_key_by_quicksort [of f xs]
1441       have "sort_key f xs = (let (lts, eqs, gts) = part f (f (xs ! (length xs div 2))) xs
1442         in sort_key f lts @ eqs @ sort_key f gts)"
1443       by (simp only: split_def Let_def part_def fst_conv snd_conv)
1444       with hyps Cons show ?thesis by (simp only: list.cases)
1445     qed
1446   qed
1447 qed
1449 end
1451 hide_const (open) part
1453 lemma multiset_of_remdups_le: "multiset_of (remdups xs) \<le> multiset_of xs"
1454   by (induct xs) (auto intro: order_trans)
1456 lemma multiset_of_update:
1457   "i < length ls \<Longrightarrow> multiset_of (ls[i := v]) = multiset_of ls - {#ls ! i#} + {#v#}"
1458 proof (induct ls arbitrary: i)
1459   case Nil then show ?case by simp
1460 next
1461   case (Cons x xs)
1462   show ?case
1463   proof (cases i)
1464     case 0 then show ?thesis by simp
1465   next
1466     case (Suc i')
1467     with Cons show ?thesis
1468       apply simp
1469       apply (subst add_assoc)
1470       apply (subst add_commute [of "{#v#}" "{#x#}"])
1471       apply (subst add_assoc [symmetric])
1472       apply simp
1473       apply (rule mset_le_multiset_union_diff_commute)
1474       apply (simp add: mset_le_single nth_mem_multiset_of)
1475       done
1476   qed
1477 qed
1479 lemma multiset_of_swap:
1480   "i < length ls \<Longrightarrow> j < length ls \<Longrightarrow>
1481     multiset_of (ls[j := ls ! i, i := ls ! j]) = multiset_of ls"
1482   by (cases "i = j") (simp_all add: multiset_of_update nth_mem_multiset_of)
1485 subsection {* The multiset order *}
1487 subsubsection {* Well-foundedness *}
1489 definition mult1 :: "('a \<times> 'a) set => ('a multiset \<times> 'a multiset) set" where
1490   "mult1 r = {(N, M). \<exists>a M0 K. M = M0 + {#a#} \<and> N = M0 + K \<and>
1491       (\<forall>b. b :# K --> (b, a) \<in> r)}"
1493 definition mult :: "('a \<times> 'a) set => ('a multiset \<times> 'a multiset) set" where
1494   "mult r = (mult1 r)\<^sup>+"
1496 lemma not_less_empty [iff]: "(M, {#}) \<notin> mult1 r"
1497 by (simp add: mult1_def)
1499 lemma less_add: "(N, M0 + {#a#}) \<in> mult1 r ==>
1500     (\<exists>M. (M, M0) \<in> mult1 r \<and> N = M + {#a#}) \<or>
1501     (\<exists>K. (\<forall>b. b :# K --> (b, a) \<in> r) \<and> N = M0 + K)"
1502   (is "_ \<Longrightarrow> ?case1 (mult1 r) \<or> ?case2")
1503 proof (unfold mult1_def)
1504   let ?r = "\<lambda>K a. \<forall>b. b :# K --> (b, a) \<in> r"
1505   let ?R = "\<lambda>N M. \<exists>a M0 K. M = M0 + {#a#} \<and> N = M0 + K \<and> ?r K a"
1506   let ?case1 = "?case1 {(N, M). ?R N M}"
1508   assume "(N, M0 + {#a#}) \<in> {(N, M). ?R N M}"
1509   then have "\<exists>a' M0' K.
1510       M0 + {#a#} = M0' + {#a'#} \<and> N = M0' + K \<and> ?r K a'" by simp
1511   then show "?case1 \<or> ?case2"
1512   proof (elim exE conjE)
1513     fix a' M0' K
1514     assume N: "N = M0' + K" and r: "?r K a'"
1515     assume "M0 + {#a#} = M0' + {#a'#}"
1516     then have "M0 = M0' \<and> a = a' \<or>
1517         (\<exists>K'. M0 = K' + {#a'#} \<and> M0' = K' + {#a#})"
1518       by (simp only: add_eq_conv_ex)
1519     then show ?thesis
1520     proof (elim disjE conjE exE)
1521       assume "M0 = M0'" "a = a'"
1522       with N r have "?r K a \<and> N = M0 + K" by simp
1523       then have ?case2 .. then show ?thesis ..
1524     next
1525       fix K'
1526       assume "M0' = K' + {#a#}"
1527       with N have n: "N = K' + K + {#a#}" by (simp add: add_ac)
1529       assume "M0 = K' + {#a'#}"
1530       with r have "?R (K' + K) M0" by blast
1531       with n have ?case1 by simp then show ?thesis ..
1532     qed
1533   qed
1534 qed
1536 lemma all_accessible: "wf r ==> \<forall>M. M \<in> acc (mult1 r)"
1537 proof
1538   let ?R = "mult1 r"
1539   let ?W = "acc ?R"
1540   {
1541     fix M M0 a
1542     assume M0: "M0 \<in> ?W"
1543       and wf_hyp: "!!b. (b, a) \<in> r ==> (\<forall>M \<in> ?W. M + {#b#} \<in> ?W)"
1544       and acc_hyp: "\<forall>M. (M, M0) \<in> ?R --> M + {#a#} \<in> ?W"
1545     have "M0 + {#a#} \<in> ?W"
1546     proof (rule accI [of "M0 + {#a#}"])
1547       fix N
1548       assume "(N, M0 + {#a#}) \<in> ?R"
1549       then have "((\<exists>M. (M, M0) \<in> ?R \<and> N = M + {#a#}) \<or>
1550           (\<exists>K. (\<forall>b. b :# K --> (b, a) \<in> r) \<and> N = M0 + K))"
1551         by (rule less_add)
1552       then show "N \<in> ?W"
1553       proof (elim exE disjE conjE)
1554         fix M assume "(M, M0) \<in> ?R" and N: "N = M + {#a#}"
1555         from acc_hyp have "(M, M0) \<in> ?R --> M + {#a#} \<in> ?W" ..
1556         from this and `(M, M0) \<in> ?R` have "M + {#a#} \<in> ?W" ..
1557         then show "N \<in> ?W" by (simp only: N)
1558       next
1559         fix K
1560         assume N: "N = M0 + K"
1561         assume "\<forall>b. b :# K --> (b, a) \<in> r"
1562         then have "M0 + K \<in> ?W"
1563         proof (induct K)
1564           case empty
1565           from M0 show "M0 + {#} \<in> ?W" by simp
1566         next
1567           case (add K x)
1568           from add.prems have "(x, a) \<in> r" by simp
1569           with wf_hyp have "\<forall>M \<in> ?W. M + {#x#} \<in> ?W" by blast
1570           moreover from add have "M0 + K \<in> ?W" by simp
1571           ultimately have "(M0 + K) + {#x#} \<in> ?W" ..
1572           then show "M0 + (K + {#x#}) \<in> ?W" by (simp only: add_assoc)
1573         qed
1574         then show "N \<in> ?W" by (simp only: N)
1575       qed
1576     qed
1577   } note tedious_reasoning = this
1579   assume wf: "wf r"
1580   fix M
1581   show "M \<in> ?W"
1582   proof (induct M)
1583     show "{#} \<in> ?W"
1584     proof (rule accI)
1585       fix b assume "(b, {#}) \<in> ?R"
1586       with not_less_empty show "b \<in> ?W" by contradiction
1587     qed
1589     fix M a assume "M \<in> ?W"
1590     from wf have "\<forall>M \<in> ?W. M + {#a#} \<in> ?W"
1591     proof induct
1592       fix a
1593       assume r: "!!b. (b, a) \<in> r ==> (\<forall>M \<in> ?W. M + {#b#} \<in> ?W)"
1594       show "\<forall>M \<in> ?W. M + {#a#} \<in> ?W"
1595       proof
1596         fix M assume "M \<in> ?W"
1597         then show "M + {#a#} \<in> ?W"
1598           by (rule acc_induct) (rule tedious_reasoning [OF _ r])
1599       qed
1600     qed
1601     from this and `M \<in> ?W` show "M + {#a#} \<in> ?W" ..
1602   qed
1603 qed
1605 theorem wf_mult1: "wf r ==> wf (mult1 r)"
1606 by (rule acc_wfI) (rule all_accessible)
1608 theorem wf_mult: "wf r ==> wf (mult r)"
1609 unfolding mult_def by (rule wf_trancl) (rule wf_mult1)
1612 subsubsection {* Closure-free presentation *}
1614 text {* One direction. *}
1616 lemma mult_implies_one_step:
1617   "trans r ==> (M, N) \<in> mult r ==>
1618     \<exists>I J K. N = I + J \<and> M = I + K \<and> J \<noteq> {#} \<and>
1619     (\<forall>k \<in> set_of K. \<exists>j \<in> set_of J. (k, j) \<in> r)"
1620 apply (unfold mult_def mult1_def set_of_def)
1621 apply (erule converse_trancl_induct, clarify)
1622  apply (rule_tac x = M0 in exI, simp, clarify)
1623 apply (case_tac "a :# K")
1624  apply (rule_tac x = I in exI)
1625  apply (simp (no_asm))
1626  apply (rule_tac x = "(K - {#a#}) + Ka" in exI)
1627  apply (simp (no_asm_simp) add: add_assoc [symmetric])
1628  apply (drule_tac f = "\<lambda>M. M - {#a#}" in arg_cong)
1629  apply (simp add: diff_union_single_conv)
1630  apply (simp (no_asm_use) add: trans_def)
1631  apply blast
1632 apply (subgoal_tac "a :# I")
1633  apply (rule_tac x = "I - {#a#}" in exI)
1634  apply (rule_tac x = "J + {#a#}" in exI)
1635  apply (rule_tac x = "K + Ka" in exI)
1636  apply (rule conjI)
1637   apply (simp add: multiset_eq_iff split: nat_diff_split)
1638  apply (rule conjI)
1639   apply (drule_tac f = "\<lambda>M. M - {#a#}" in arg_cong, simp)
1640   apply (simp add: multiset_eq_iff split: nat_diff_split)
1641  apply (simp (no_asm_use) add: trans_def)
1642  apply blast
1643 apply (subgoal_tac "a :# (M0 + {#a#})")
1644  apply simp
1645 apply (simp (no_asm))
1646 done
1648 lemma one_step_implies_mult_aux:
1649   "trans r ==>
1650     \<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))
1651       --> (I + K, I + J) \<in> mult r"
1652 apply (induct_tac n, auto)
1653 apply (frule size_eq_Suc_imp_eq_union, clarify)
1654 apply (rename_tac "J'", simp)
1655 apply (erule notE, auto)
1656 apply (case_tac "J' = {#}")
1657  apply (simp add: mult_def)
1658  apply (rule r_into_trancl)
1659  apply (simp add: mult1_def set_of_def, blast)
1660 txt {* Now we know @{term "J' \<noteq> {#}"}. *}
1661 apply (cut_tac M = K and P = "\<lambda>x. (x, a) \<in> r" in multiset_partition)
1662 apply (erule_tac P = "\<forall>k \<in> set_of K. ?P k" in rev_mp)
1663 apply (erule ssubst)
1664 apply (simp add: Ball_def, auto)
1665 apply (subgoal_tac
1666   "((I + {# x :# K. (x, a) \<in> r #}) + {# x :# K. (x, a) \<notin> r #},
1667     (I + {# x :# K. (x, a) \<in> r #}) + J') \<in> mult r")
1668  prefer 2
1669  apply force
1670 apply (simp (no_asm_use) add: add_assoc [symmetric] mult_def)
1671 apply (erule trancl_trans)
1672 apply (rule r_into_trancl)
1673 apply (simp add: mult1_def set_of_def)
1674 apply (rule_tac x = a in exI)
1675 apply (rule_tac x = "I + J'" in exI)
1677 done
1679 lemma one_step_implies_mult:
1680   "trans r ==> J \<noteq> {#} ==> \<forall>k \<in> set_of K. \<exists>j \<in> set_of J. (k, j) \<in> r
1681     ==> (I + K, I + J) \<in> mult r"
1682 using one_step_implies_mult_aux by blast
1685 subsubsection {* Partial-order properties *}
1687 definition less_multiset :: "'a\<Colon>order multiset \<Rightarrow> 'a multiset \<Rightarrow> bool" (infix "<#" 50) where
1688   "M' <# M \<longleftrightarrow> (M', M) \<in> mult {(x', x). x' < x}"
1690 definition le_multiset :: "'a\<Colon>order multiset \<Rightarrow> 'a multiset \<Rightarrow> bool" (infix "<=#" 50) where
1691   "M' <=# M \<longleftrightarrow> M' <# M \<or> M' = M"
1693 notation (xsymbols) less_multiset (infix "\<subset>#" 50)
1694 notation (xsymbols) le_multiset (infix "\<subseteq>#" 50)
1696 interpretation multiset_order: order le_multiset less_multiset
1697 proof -
1698   have irrefl: "\<And>M :: 'a multiset. \<not> M \<subset># M"
1699   proof
1700     fix M :: "'a multiset"
1701     assume "M \<subset># M"
1702     then have MM: "(M, M) \<in> mult {(x, y). x < y}" by (simp add: less_multiset_def)
1703     have "trans {(x'::'a, x). x' < x}"
1704       by (rule transI) simp
1705     moreover note MM
1706     ultimately have "\<exists>I J K. M = I + J \<and> M = I + K
1707       \<and> J \<noteq> {#} \<and> (\<forall>k\<in>set_of K. \<exists>j\<in>set_of J. (k, j) \<in> {(x, y). x < y})"
1708       by (rule mult_implies_one_step)
1709     then obtain I J K where "M = I + J" and "M = I + K"
1710       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
1711     then have aux1: "K \<noteq> {#}" and aux2: "\<forall>k\<in>set_of K. \<exists>j\<in>set_of K. k < j" by auto
1712     have "finite (set_of K)" by simp
1713     moreover note aux2
1714     ultimately have "set_of K = {}"
1715       by (induct rule: finite_induct) (auto intro: order_less_trans)
1716     with aux1 show False by simp
1717   qed
1718   have trans: "\<And>K M N :: 'a multiset. K \<subset># M \<Longrightarrow> M \<subset># N \<Longrightarrow> K \<subset># N"
1719     unfolding less_multiset_def mult_def by (blast intro: trancl_trans)
1720   show "class.order (le_multiset :: 'a multiset \<Rightarrow> _) less_multiset"
1721     by default (auto simp add: le_multiset_def irrefl dest: trans)
1722 qed
1724 lemma mult_less_irrefl [elim!]: "M \<subset># (M::'a::order multiset) ==> R"
1725   by simp
1728 subsubsection {* Monotonicity of multiset union *}
1730 lemma mult1_union: "(B, D) \<in> mult1 r ==> (C + B, C + D) \<in> mult1 r"
1731 apply (unfold mult1_def)
1732 apply auto
1733 apply (rule_tac x = a in exI)
1734 apply (rule_tac x = "C + M0" in exI)
1736 done
1738 lemma union_less_mono2: "B \<subset># D ==> C + B \<subset># C + (D::'a::order multiset)"
1739 apply (unfold less_multiset_def mult_def)
1740 apply (erule trancl_induct)
1741  apply (blast intro: mult1_union)
1742 apply (blast intro: mult1_union trancl_trans)
1743 done
1745 lemma union_less_mono1: "B \<subset># D ==> B + C \<subset># D + (C::'a::order multiset)"
1746 apply (subst add_commute [of B C])
1747 apply (subst add_commute [of D C])
1748 apply (erule union_less_mono2)
1749 done
1751 lemma union_less_mono:
1752   "A \<subset># C ==> B \<subset># D ==> A + B \<subset># C + (D::'a::order multiset)"
1753   by (blast intro!: union_less_mono1 union_less_mono2 multiset_order.less_trans)
1755 interpretation multiset_order: ordered_ab_semigroup_add plus le_multiset less_multiset
1756 proof
1757 qed (auto simp add: le_multiset_def intro: union_less_mono2)
1760 subsection {* Termination proofs with multiset orders *}
1762 lemma multi_member_skip: "x \<in># XS \<Longrightarrow> x \<in># {# y #} + XS"
1763   and multi_member_this: "x \<in># {# x #} + XS"
1764   and multi_member_last: "x \<in># {# x #}"
1765   by auto
1767 definition "ms_strict = mult pair_less"
1768 definition "ms_weak = ms_strict \<union> Id"
1770 lemma ms_reduction_pair: "reduction_pair (ms_strict, ms_weak)"
1771 unfolding reduction_pair_def ms_strict_def ms_weak_def pair_less_def
1772 by (auto intro: wf_mult1 wf_trancl simp: mult_def)
1774 lemma smsI:
1775   "(set_of A, set_of B) \<in> max_strict \<Longrightarrow> (Z + A, Z + B) \<in> ms_strict"
1776   unfolding ms_strict_def
1777 by (rule one_step_implies_mult) (auto simp add: max_strict_def pair_less_def elim!:max_ext.cases)
1779 lemma wmsI:
1780   "(set_of A, set_of B) \<in> max_strict \<or> A = {#} \<and> B = {#}
1781   \<Longrightarrow> (Z + A, Z + B) \<in> ms_weak"
1782 unfolding ms_weak_def ms_strict_def
1783 by (auto simp add: pair_less_def max_strict_def elim!:max_ext.cases intro: one_step_implies_mult)
1785 inductive pw_leq
1786 where
1787   pw_leq_empty: "pw_leq {#} {#}"
1788 | pw_leq_step:  "\<lbrakk>(x,y) \<in> pair_leq; pw_leq X Y \<rbrakk> \<Longrightarrow> pw_leq ({#x#} + X) ({#y#} + Y)"
1790 lemma pw_leq_lstep:
1791   "(x, y) \<in> pair_leq \<Longrightarrow> pw_leq {#x#} {#y#}"
1792 by (drule pw_leq_step) (rule pw_leq_empty, simp)
1794 lemma pw_leq_split:
1795   assumes "pw_leq X Y"
1796   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 = {#}))"
1797   using assms
1798 proof (induct)
1799   case pw_leq_empty thus ?case by auto
1800 next
1801   case (pw_leq_step x y X Y)
1802   then obtain A B Z where
1803     [simp]: "X = A + Z" "Y = B + Z"
1804       and 1[simp]: "(set_of A, set_of B) \<in> max_strict \<or> (B = {#} \<and> A = {#})"
1805     by auto
1806   from pw_leq_step have "x = y \<or> (x, y) \<in> pair_less"
1807     unfolding pair_leq_def by auto
1808   thus ?case
1809   proof
1810     assume [simp]: "x = y"
1811     have
1812       "{#x#} + X = A + ({#y#}+Z)
1813       \<and> {#y#} + Y = B + ({#y#}+Z)
1814       \<and> ((set_of A, set_of B) \<in> max_strict \<or> (B = {#} \<and> A = {#}))"
1815       by (auto simp: add_ac)
1816     thus ?case by (intro exI)
1817   next
1818     assume A: "(x, y) \<in> pair_less"
1819     let ?A' = "{#x#} + A" and ?B' = "{#y#} + B"
1820     have "{#x#} + X = ?A' + Z"
1821       "{#y#} + Y = ?B' + Z"
1823     moreover have
1824       "(set_of ?A', set_of ?B') \<in> max_strict"
1825       using 1 A unfolding max_strict_def
1826       by (auto elim!: max_ext.cases)
1827     ultimately show ?thesis by blast
1828   qed
1829 qed
1831 lemma
1832   assumes pwleq: "pw_leq Z Z'"
1833   shows ms_strictI: "(set_of A, set_of B) \<in> max_strict \<Longrightarrow> (Z + A, Z' + B) \<in> ms_strict"
1834   and   ms_weakI1:  "(set_of A, set_of B) \<in> max_strict \<Longrightarrow> (Z + A, Z' + B) \<in> ms_weak"
1835   and   ms_weakI2:  "(Z + {#}, Z' + {#}) \<in> ms_weak"
1836 proof -
1837   from pw_leq_split[OF pwleq]
1838   obtain A' B' Z''
1839     where [simp]: "Z = A' + Z''" "Z' = B' + Z''"
1840     and mx_or_empty: "(set_of A', set_of B') \<in> max_strict \<or> (A' = {#} \<and> B' = {#})"
1841     by blast
1842   {
1843     assume max: "(set_of A, set_of B) \<in> max_strict"
1844     from mx_or_empty
1845     have "(Z'' + (A + A'), Z'' + (B + B')) \<in> ms_strict"
1846     proof
1847       assume max': "(set_of A', set_of B') \<in> max_strict"
1848       with max have "(set_of (A + A'), set_of (B + B')) \<in> max_strict"
1849         by (auto simp: max_strict_def intro: max_ext_additive)
1850       thus ?thesis by (rule smsI)
1851     next
1852       assume [simp]: "A' = {#} \<and> B' = {#}"
1853       show ?thesis by (rule smsI) (auto intro: max)
1854     qed
1855     thus "(Z + A, Z' + B) \<in> ms_strict" by (simp add:add_ac)
1856     thus "(Z + A, Z' + B) \<in> ms_weak" by (simp add: ms_weak_def)
1857   }
1858   from mx_or_empty
1859   have "(Z'' + A', Z'' + B') \<in> ms_weak" by (rule wmsI)
1860   thus "(Z + {#}, Z' + {#}) \<in> ms_weak" by (simp add:add_ac)
1861 qed
1863 lemma empty_neutral: "{#} + x = x" "x + {#} = x"
1864 and nonempty_plus: "{# x #} + rs \<noteq> {#}"
1865 and nonempty_single: "{# x #} \<noteq> {#}"
1866 by auto
1868 setup {*
1869 let
1870   fun msetT T = Type (@{type_name multiset}, [T]);
1872   fun mk_mset T [] = Const (@{const_abbrev Mempty}, msetT T)
1873     | mk_mset T [x] = Const (@{const_name single}, T --> msetT T) \$ x
1874     | mk_mset T (x :: xs) =
1875           Const (@{const_name plus}, msetT T --> msetT T --> msetT T) \$
1876                 mk_mset T [x] \$ mk_mset T xs
1878   fun mset_member_tac m i =
1879       (if m <= 0 then
1880            rtac @{thm multi_member_this} i ORELSE rtac @{thm multi_member_last} i
1881        else
1882            rtac @{thm multi_member_skip} i THEN mset_member_tac (m - 1) i)
1884   val mset_nonempty_tac =
1885       rtac @{thm nonempty_plus} ORELSE' rtac @{thm nonempty_single}
1887   val regroup_munion_conv =
1888       Function_Lib.regroup_conv @{const_abbrev Mempty} @{const_name plus}
1889         (map (fn t => t RS eq_reflection) (@{thms add_ac} @ @{thms empty_neutral}))
1891   fun unfold_pwleq_tac i =
1892     (rtac @{thm pw_leq_step} i THEN (fn st => unfold_pwleq_tac (i + 1) st))
1893       ORELSE (rtac @{thm pw_leq_lstep} i)
1894       ORELSE (rtac @{thm pw_leq_empty} i)
1896   val set_of_simps = [@{thm set_of_empty}, @{thm set_of_single}, @{thm set_of_union},
1897                       @{thm Un_insert_left}, @{thm Un_empty_left}]
1898 in
1899   ScnpReconstruct.multiset_setup (ScnpReconstruct.Multiset
1900   {
1901     msetT=msetT, mk_mset=mk_mset, mset_regroup_conv=regroup_munion_conv,
1902     mset_member_tac=mset_member_tac, mset_nonempty_tac=mset_nonempty_tac,
1903     mset_pwleq_tac=unfold_pwleq_tac, set_of_simps=set_of_simps,
1904     smsI'= @{thm ms_strictI}, wmsI2''= @{thm ms_weakI2}, wmsI1= @{thm ms_weakI1},
1905     reduction_pair= @{thm ms_reduction_pair}
1906   })
1907 end
1908 *}
1911 subsection {* Legacy theorem bindings *}
1913 lemmas multi_count_eq = multiset_eq_iff [symmetric]
1915 lemma union_commute: "M + N = N + (M::'a multiset)"
1916   by (fact add_commute)
1918 lemma union_assoc: "(M + N) + K = M + (N + (K::'a multiset))"
1919   by (fact add_assoc)
1921 lemma union_lcomm: "M + (N + K) = N + (M + (K::'a multiset))"
1922   by (fact add_left_commute)
1924 lemmas union_ac = union_assoc union_commute union_lcomm
1926 lemma union_right_cancel: "M + K = N + K \<longleftrightarrow> M = (N::'a multiset)"
1927   by (fact add_right_cancel)
1929 lemma union_left_cancel: "K + M = K + N \<longleftrightarrow> M = (N::'a multiset)"
1930   by (fact add_left_cancel)
1932 lemma multi_union_self_other_eq: "(A::'a multiset) + X = A + Y \<Longrightarrow> X = Y"
1933   by (fact add_imp_eq)
1935 lemma mset_less_trans: "(M::'a multiset) < K \<Longrightarrow> K < N \<Longrightarrow> M < N"
1936   by (fact order_less_trans)
1938 lemma multiset_inter_commute: "A #\<inter> B = B #\<inter> A"
1939   by (fact inf.commute)
1941 lemma multiset_inter_assoc: "A #\<inter> (B #\<inter> C) = A #\<inter> B #\<inter> C"
1942   by (fact inf.assoc [symmetric])
1944 lemma multiset_inter_left_commute: "A #\<inter> (B #\<inter> C) = B #\<inter> (A #\<inter> C)"
1945   by (fact inf.left_commute)
1947 lemmas multiset_inter_ac =
1948   multiset_inter_commute
1949   multiset_inter_assoc
1950   multiset_inter_left_commute
1952 lemma mult_less_not_refl:
1953   "\<not> M \<subset># (M::'a::order multiset)"
1954   by (fact multiset_order.less_irrefl)
1956 lemma mult_less_trans:
1957   "K \<subset># M ==> M \<subset># N ==> K \<subset># (N::'a::order multiset)"
1958   by (fact multiset_order.less_trans)
1960 lemma mult_less_not_sym:
1961   "M \<subset># N ==> \<not> N \<subset># (M::'a::order multiset)"
1962   by (fact multiset_order.less_not_sym)
1964 lemma mult_less_asym:
1965   "M \<subset># N ==> (\<not> P ==> N \<subset># (M::'a::order multiset)) ==> P"
1966   by (fact multiset_order.less_asym)
1968 ML {*
1969 fun multiset_postproc _ maybe_name all_values (T as Type (_, [elem_T]))
1970                       (Const _ \$ t') =
1971     let
1972       val (maybe_opt, ps) =
1973         Nitpick_Model.dest_plain_fun t' ||> op ~~
1974         ||> map (apsnd (snd o HOLogic.dest_number))
1975       fun elems_for t =
1976         case AList.lookup (op =) ps t of
1977           SOME n => replicate n t
1978         | NONE => [Const (maybe_name, elem_T --> elem_T) \$ t]
1979     in
1980       case maps elems_for (all_values elem_T) @
1981            (if maybe_opt then [Const (Nitpick_Model.unrep (), elem_T)]
1982             else []) of
1983         [] => Const (@{const_name zero_class.zero}, T)
1984       | ts => foldl1 (fn (t1, t2) =>
1985                          Const (@{const_name plus_class.plus}, T --> T --> T)
1986                          \$ t1 \$ t2)
1987                      (map (curry (op \$) (Const (@{const_name single},
1988                                                 elem_T --> T))) ts)
1989     end
1990   | multiset_postproc _ _ _ _ t = t
1991 *}
1993 declaration {*
1994 Nitpick_Model.register_term_postprocessor @{typ "'a multiset"}
1995     multiset_postproc
1996 *}
1998 hide_const (open) fold
2001 subsection {* Naive implementation using lists *}
2003 code_datatype multiset_of
2005 lemma [code]:
2006   "{#} = multiset_of []"
2007   by simp
2009 lemma [code]:
2010   "{#x#} = multiset_of [x]"
2011   by simp
2013 lemma union_code [code]:
2014   "multiset_of xs + multiset_of ys = multiset_of (xs @ ys)"
2015   by simp
2017 lemma [code]:
2018   "image_mset f (multiset_of xs) = multiset_of (map f xs)"
2019   by (simp add: multiset_of_map)
2021 lemma [code]:
2022   "Multiset.filter f (multiset_of xs) = multiset_of (filter f xs)"
2023   by (simp add: multiset_of_filter)
2025 lemma [code]:
2026   "multiset_of xs - multiset_of ys = multiset_of (fold remove1 ys xs)"
2027   by (rule sym, induct ys arbitrary: xs) (simp_all add: diff_add diff_right_commute)
2029 lemma [code]:
2030   "multiset_of xs #\<inter> multiset_of ys =
2031     multiset_of (snd (fold (\<lambda>x (ys, zs).
2032       if x \<in> set ys then (remove1 x ys, x # zs) else (ys, zs)) xs (ys, [])))"
2033 proof -
2034   have "\<And>zs. multiset_of (snd (fold (\<lambda>x (ys, zs).
2035     if x \<in> set ys then (remove1 x ys, x # zs) else (ys, zs)) xs (ys, zs))) =
2036       (multiset_of xs #\<inter> multiset_of ys) + multiset_of zs"
2037     by (induct xs arbitrary: ys)
2039   then show ?thesis by simp
2040 qed
2042 lemma [code]:
2043   "multiset_of xs #\<union> multiset_of ys =
2044     multiset_of (split append (fold (\<lambda>x (ys, zs). (remove1 x ys, x # zs)) xs (ys, [])))"
2045 proof -
2046   have "\<And>zs. multiset_of (split append (fold (\<lambda>x (ys, zs). (remove1 x ys, x # zs)) xs (ys, zs))) =
2047       (multiset_of xs #\<union> multiset_of ys) + multiset_of zs"
2048     by (induct xs arbitrary: ys) (simp_all add: multiset_eq_iff)
2049   then show ?thesis by simp
2050 qed
2052 lemma [code_unfold]:
2053   "x \<in># multiset_of xs \<longleftrightarrow> x \<in> set xs"
2054   by (simp add: in_multiset_of)
2056 lemma [code]:
2057   "count (multiset_of xs) x = fold (\<lambda>y. if x = y then Suc else id) xs 0"
2058 proof -
2059   have "\<And>n. fold (\<lambda>y. if x = y then Suc else id) xs n = count (multiset_of xs) x + n"
2060     by (induct xs) simp_all
2061   then show ?thesis by simp
2062 qed
2064 lemma [code]:
2065   "set_of (multiset_of xs) = set xs"
2066   by simp
2068 lemma [code]:
2069   "sorted_list_of_multiset (multiset_of xs) = sort xs"
2070   by (induct xs) simp_all
2072 lemma [code]: -- {* not very efficient, but representation-ignorant! *}
2073   "multiset_of_set A = multiset_of (sorted_list_of_set A)"
2074   apply (cases "finite A")
2075   apply simp_all
2076   apply (induct A rule: finite_induct)
2077   apply (simp_all add: union_commute)
2078   done
2080 lemma [code]:
2081   "mcard (multiset_of xs) = length xs"
2082   by (simp add: mcard_multiset_of)
2084 lemma [code]:
2085   "A \<le> B \<longleftrightarrow> A #\<inter> B = A"
2086   by (auto simp add: inf.order_iff)
2088 instantiation multiset :: (equal) equal
2089 begin
2091 definition
2092   [code]: "HOL.equal A B \<longleftrightarrow> (A::'a multiset) \<le> B \<and> B \<le> A"
2094 instance
2095   by default (simp add: equal_multiset_def eq_iff)
2097 end
2099 lemma [code]:
2100   "(A::'a multiset) < B \<longleftrightarrow> A \<le> B \<and> A \<noteq> B"
2101   by auto
2103 lemma [code]:
2104   "msetsum (multiset_of xs) = listsum xs"
2105   by (induct xs) (simp_all add: add.commute)
2107 lemma [code]:
2108   "msetprod (multiset_of xs) = fold times xs 1"
2109 proof -
2110   have "\<And>x. fold times xs x = msetprod (multiset_of xs) * x"
2111     by (induct xs) (simp_all add: mult.assoc)
2112   then show ?thesis by simp
2113 qed
2115 lemma [code]:
2116   "size = mcard"
2117   by (fact size_eq_mcard)
2119 text {*
2120   Exercise for the casual reader: add implementations for @{const le_multiset}
2121   and @{const less_multiset} (multiset order).
2122 *}
2124 text {* Quickcheck generators *}
2126 definition (in term_syntax)
2127   msetify :: "'a\<Colon>typerep list \<times> (unit \<Rightarrow> Code_Evaluation.term)
2128     \<Rightarrow> 'a multiset \<times> (unit \<Rightarrow> Code_Evaluation.term)" where
2129   [code_unfold]: "msetify xs = Code_Evaluation.valtermify multiset_of {\<cdot>} xs"
2131 notation fcomp (infixl "\<circ>>" 60)
2132 notation scomp (infixl "\<circ>\<rightarrow>" 60)
2134 instantiation multiset :: (random) random
2135 begin
2137 definition
2138   "Quickcheck_Random.random i = Quickcheck_Random.random i \<circ>\<rightarrow> (\<lambda>xs. Pair (msetify xs))"
2140 instance ..
2142 end
2144 no_notation fcomp (infixl "\<circ>>" 60)
2145 no_notation scomp (infixl "\<circ>\<rightarrow>" 60)
2147 instantiation multiset :: (full_exhaustive) full_exhaustive
2148 begin
2150 definition full_exhaustive_multiset :: "('a multiset \<times> (unit \<Rightarrow> term) \<Rightarrow> (bool \<times> term list) option) \<Rightarrow> natural \<Rightarrow> (bool \<times> term list) option"
2151 where
2152   "full_exhaustive_multiset f i = Quickcheck_Exhaustive.full_exhaustive (\<lambda>xs. f (msetify xs)) i"
2154 instance ..
2156 end
2158 hide_const (open) msetify
2160 end