src/HOL/Library/Multiset.thy
 author haftmann Thu Apr 04 22:46:14 2013 +0200 (2013-04-04) changeset 51623 1194b438426a parent 51600 197e25f13f0c child 52289 83ce5d2841e7 permissions -rw-r--r--
sup on multisets
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(simp add: multiset_eq_iff)
142 lemma diff_cancel[simp]: "A - A = {#}"
143 by (rule multiset_eqI) simp
145 lemma diff_union_cancelR [simp]: "M + N - N = (M::'a multiset)"
146 by(simp add: multiset_eq_iff)
148 lemma diff_union_cancelL [simp]: "N + M - N = (M::'a multiset)"
149 by(simp add: multiset_eq_iff)
151 lemma insert_DiffM:
152   "x \<in># M \<Longrightarrow> {#x#} + (M - {#x#}) = M"
153   by (clarsimp simp: multiset_eq_iff)
155 lemma insert_DiffM2 [simp]:
156   "x \<in># M \<Longrightarrow> M - {#x#} + {#x#} = M"
157   by (clarsimp simp: multiset_eq_iff)
159 lemma diff_right_commute:
160   "(M::'a multiset) - N - Q = M - Q - N"
161   by (auto simp add: multiset_eq_iff)
164   "(M::'a multiset) - (N + Q) = M - N - Q"
165 by (simp add: 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 lemma mset_le_mono_add_right_cancel [simp]:
293   "(A::'a multiset) + C \<le> B + C \<longleftrightarrow> A \<le> B"
294   by (fact add_le_cancel_right)
296 lemma mset_le_mono_add_left_cancel [simp]:
297   "C + (A::'a multiset) \<le> C + B \<longleftrightarrow> A \<le> B"
298   by (fact add_le_cancel_left)
301   "(A::'a multiset) \<le> B \<Longrightarrow> C \<le> D \<Longrightarrow> A + C \<le> B + D"
302   by (fact add_mono)
304 lemma mset_le_add_left [simp]:
305   "(A::'a multiset) \<le> A + B"
306   unfolding mset_le_def by auto
308 lemma mset_le_add_right [simp]:
309   "B \<le> (A::'a multiset) + B"
310   unfolding mset_le_def by auto
312 lemma mset_le_single:
313   "a :# B \<Longrightarrow> {#a#} \<le> B"
314   by (simp add: mset_le_def)
316 lemma multiset_diff_union_assoc:
317   "C \<le> B \<Longrightarrow> (A::'a multiset) + B - C = A + (B - C)"
318   by (simp add: multiset_eq_iff mset_le_def)
320 lemma mset_le_multiset_union_diff_commute:
321   "B \<le> A \<Longrightarrow> (A::'a multiset) - B + C = A + C - B"
322 by (simp add: multiset_eq_iff mset_le_def)
324 lemma diff_le_self[simp]: "(M::'a multiset) - N \<le> M"
325 by(simp add: mset_le_def)
327 lemma mset_lessD: "A < B \<Longrightarrow> x \<in># A \<Longrightarrow> x \<in># B"
328 apply (clarsimp simp: mset_le_def mset_less_def)
329 apply (erule_tac x=x in allE)
330 apply auto
331 done
333 lemma mset_leD: "A \<le> B \<Longrightarrow> x \<in># A \<Longrightarrow> x \<in># B"
334 apply (clarsimp simp: mset_le_def mset_less_def)
335 apply (erule_tac x = x in allE)
336 apply auto
337 done
339 lemma mset_less_insertD: "(A + {#x#} < B) \<Longrightarrow> (x \<in># B \<and> A < B)"
340 apply (rule conjI)
341  apply (simp add: mset_lessD)
342 apply (clarsimp simp: mset_le_def mset_less_def)
343 apply safe
344  apply (erule_tac x = a in allE)
345  apply (auto split: split_if_asm)
346 done
348 lemma mset_le_insertD: "(A + {#x#} \<le> B) \<Longrightarrow> (x \<in># B \<and> A \<le> B)"
349 apply (rule conjI)
350  apply (simp add: mset_leD)
351 apply (force simp: mset_le_def mset_less_def split: split_if_asm)
352 done
354 lemma mset_less_of_empty[simp]: "A < {#} \<longleftrightarrow> False"
355   by (auto simp add: mset_less_def mset_le_def multiset_eq_iff)
357 lemma multi_psub_of_add_self[simp]: "A < A + {#x#}"
358   by (auto simp: mset_le_def mset_less_def)
360 lemma multi_psub_self[simp]: "(A::'a multiset) < A = False"
361   by simp
364   "T + {#x#} < S + {#x#} \<Longrightarrow> T < S"
365   by (fact add_less_imp_less_right)
367 lemma mset_less_empty_nonempty:
368   "{#} < S \<longleftrightarrow> S \<noteq> {#}"
369   by (auto simp: mset_le_def mset_less_def)
371 lemma mset_less_diff_self:
372   "c \<in># B \<Longrightarrow> B - {#c#} < B"
373   by (auto simp: mset_le_def mset_less_def multiset_eq_iff)
376 subsubsection {* Intersection *}
378 instantiation multiset :: (type) semilattice_inf
379 begin
381 definition inf_multiset :: "'a multiset \<Rightarrow> 'a multiset \<Rightarrow> 'a multiset" where
382   multiset_inter_def: "inf_multiset A B = A - (A - B)"
384 instance
385 proof -
386   have aux: "\<And>m n q :: nat. m \<le> n \<Longrightarrow> m \<le> q \<Longrightarrow> m \<le> n - (n - q)" by arith
387   show "OFCLASS('a multiset, semilattice_inf_class)"
388     by default (auto simp add: multiset_inter_def mset_le_def aux)
389 qed
391 end
393 abbreviation multiset_inter :: "'a multiset \<Rightarrow> 'a multiset \<Rightarrow> 'a multiset" (infixl "#\<inter>" 70) where
394   "multiset_inter \<equiv> inf"
396 lemma multiset_inter_count [simp]:
397   "count (A #\<inter> B) x = min (count A x) (count B x)"
398   by (simp add: multiset_inter_def)
400 lemma multiset_inter_single: "a \<noteq> b \<Longrightarrow> {#a#} #\<inter> {#b#} = {#}"
401   by (rule multiset_eqI) auto
403 lemma multiset_union_diff_commute:
404   assumes "B #\<inter> C = {#}"
405   shows "A + B - C = A - C + B"
406 proof (rule multiset_eqI)
407   fix x
408   from assms have "min (count B x) (count C x) = 0"
409     by (auto simp add: multiset_eq_iff)
410   then have "count B x = 0 \<or> count C x = 0"
411     by auto
412   then show "count (A + B - C) x = count (A - C + B) x"
413     by auto
414 qed
416 lemma empty_inter [simp]:
417   "{#} #\<inter> M = {#}"
418   by (simp add: multiset_eq_iff)
420 lemma inter_empty [simp]:
421   "M #\<inter> {#} = {#}"
422   by (simp add: multiset_eq_iff)
425   "\<not> x \<in># N \<Longrightarrow> (M + {#x#}) #\<inter> N = M #\<inter> N"
426   by (simp add: multiset_eq_iff)
429   "x \<in># N \<Longrightarrow> (M + {#x#}) #\<inter> N = (M #\<inter> (N - {#x#})) + {#x#}"
430   by (simp add: multiset_eq_iff)
433   "\<not> x \<in># N \<Longrightarrow> N #\<inter> (M + {#x#}) = N #\<inter> M"
434   by (simp add: multiset_eq_iff)
437   "x \<in># N \<Longrightarrow> N #\<inter> (M + {#x#}) = ((N - {#x#}) #\<inter> M) + {#x#}"
438   by (simp add: multiset_eq_iff)
441 subsubsection {* Bounded union *}
443 instantiation multiset :: (type) semilattice_sup
444 begin
446 definition sup_multiset :: "'a multiset \<Rightarrow> 'a multiset \<Rightarrow> 'a multiset" where
447   "sup_multiset A B = A + (B - A)"
449 instance
450 proof -
451   have aux: "\<And>m n q :: nat. m \<le> n \<Longrightarrow> q \<le> n \<Longrightarrow> m + (q - m) \<le> n" by arith
452   show "OFCLASS('a multiset, semilattice_sup_class)"
453     by default (auto simp add: sup_multiset_def mset_le_def aux)
454 qed
456 end
458 abbreviation sup_multiset :: "'a multiset \<Rightarrow> 'a multiset \<Rightarrow> 'a multiset" (infixl "#\<union>" 70) where
459   "sup_multiset \<equiv> sup"
461 lemma sup_multiset_count [simp]:
462   "count (A #\<union> B) x = max (count A x) (count B x)"
463   by (simp add: sup_multiset_def)
465 lemma empty_sup [simp]:
466   "{#} #\<union> M = M"
467   by (simp add: multiset_eq_iff)
469 lemma sup_empty [simp]:
470   "M #\<union> {#} = M"
471   by (simp add: multiset_eq_iff)
474   "\<not> x \<in># N \<Longrightarrow> (M + {#x#}) #\<union> N = (M #\<union> N) + {#x#}"
475   by (simp add: multiset_eq_iff)
478   "x \<in># N \<Longrightarrow> (M + {#x#}) #\<union> N = (M #\<union> (N - {#x#})) + {#x#}"
479   by (simp add: multiset_eq_iff)
482   "\<not> x \<in># N \<Longrightarrow> N #\<union> (M + {#x#}) = (N #\<union> M) + {#x#}"
483   by (simp add: multiset_eq_iff)
486   "x \<in># N \<Longrightarrow> N #\<union> (M + {#x#}) = ((N - {#x#}) #\<union> M) + {#x#}"
487   by (simp add: multiset_eq_iff)
490 subsubsection {* Filter (with comprehension syntax) *}
492 text {* Multiset comprehension *}
494 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"
495 by (rule filter_preserves_multiset)
497 hide_const (open) filter
499 lemma count_filter [simp]:
500   "count (Multiset.filter P M) a = (if P a then count M a else 0)"
501   by (simp add: filter.rep_eq)
503 lemma filter_empty [simp]:
504   "Multiset.filter P {#} = {#}"
505   by (rule multiset_eqI) simp
507 lemma filter_single [simp]:
508   "Multiset.filter P {#x#} = (if P x then {#x#} else {#})"
509   by (rule multiset_eqI) simp
511 lemma filter_union [simp]:
512   "Multiset.filter P (M + N) = Multiset.filter P M + Multiset.filter P N"
513   by (rule multiset_eqI) simp
515 lemma filter_diff [simp]:
516   "Multiset.filter P (M - N) = Multiset.filter P M - Multiset.filter P N"
517   by (rule multiset_eqI) simp
519 lemma filter_inter [simp]:
520   "Multiset.filter P (M #\<inter> N) = Multiset.filter P M #\<inter> Multiset.filter P N"
521   by (rule multiset_eqI) simp
523 syntax
524   "_MCollect" :: "pttrn \<Rightarrow> 'a multiset \<Rightarrow> bool \<Rightarrow> 'a multiset"    ("(1{# _ :# _./ _#})")
525 syntax (xsymbol)
526   "_MCollect" :: "pttrn \<Rightarrow> 'a multiset \<Rightarrow> bool \<Rightarrow> 'a multiset"    ("(1{# _ \<in># _./ _#})")
527 translations
528   "{#x \<in># M. P#}" == "CONST Multiset.filter (\<lambda>x. P) M"
531 subsubsection {* Set of elements *}
533 definition set_of :: "'a multiset => 'a set" where
534   "set_of M = {x. x :# M}"
536 lemma set_of_empty [simp]: "set_of {#} = {}"
537 by (simp add: set_of_def)
539 lemma set_of_single [simp]: "set_of {#b#} = {b}"
540 by (simp add: set_of_def)
542 lemma set_of_union [simp]: "set_of (M + N) = set_of M \<union> set_of N"
543 by (auto simp add: set_of_def)
545 lemma set_of_eq_empty_iff [simp]: "(set_of M = {}) = (M = {#})"
546 by (auto simp add: set_of_def multiset_eq_iff)
548 lemma mem_set_of_iff [simp]: "(x \<in> set_of M) = (x :# M)"
549 by (auto simp add: set_of_def)
551 lemma set_of_filter [simp]: "set_of {# x:#M. P x #} = set_of M \<inter> {x. P x}"
552 by (auto simp add: set_of_def)
554 lemma finite_set_of [iff]: "finite (set_of M)"
555   using count [of M] by (simp add: multiset_def set_of_def)
557 lemma finite_Collect_mem [iff]: "finite {x. x :# M}"
558   unfolding set_of_def[symmetric] by simp
560 subsubsection {* Size *}
562 instantiation multiset :: (type) size
563 begin
565 definition size_def:
566   "size M = setsum (count M) (set_of M)"
568 instance ..
570 end
572 lemma size_empty [simp]: "size {#} = 0"
573 by (simp add: size_def)
575 lemma size_single [simp]: "size {#b#} = 1"
576 by (simp add: size_def)
578 lemma setsum_count_Int:
579   "finite A ==> setsum (count N) (A \<inter> set_of N) = setsum (count N) A"
580 apply (induct rule: finite_induct)
581  apply simp
582 apply (simp add: Int_insert_left set_of_def)
583 done
585 lemma size_union [simp]: "size (M + N::'a multiset) = size M + size N"
586 apply (unfold size_def)
587 apply (subgoal_tac "count (M + N) = (\<lambda>a. count M a + count N a)")
588  prefer 2
589  apply (rule ext, simp)
590 apply (simp (no_asm_simp) add: setsum_Un_nat setsum_addf setsum_count_Int)
591 apply (subst Int_commute)
592 apply (simp (no_asm_simp) add: setsum_count_Int)
593 done
595 lemma size_eq_0_iff_empty [iff]: "(size M = 0) = (M = {#})"
596 by (auto simp add: size_def multiset_eq_iff)
598 lemma nonempty_has_size: "(S \<noteq> {#}) = (0 < size S)"
599 by (metis gr0I gr_implies_not0 size_empty size_eq_0_iff_empty)
601 lemma size_eq_Suc_imp_elem: "size M = Suc n ==> \<exists>a. a :# M"
602 apply (unfold size_def)
603 apply (drule setsum_SucD)
604 apply auto
605 done
607 lemma size_eq_Suc_imp_eq_union:
608   assumes "size M = Suc n"
609   shows "\<exists>a N. M = N + {#a#}"
610 proof -
611   from assms obtain a where "a \<in># M"
612     by (erule size_eq_Suc_imp_elem [THEN exE])
613   then have "M = M - {#a#} + {#a#}" by simp
614   then show ?thesis by blast
615 qed
618 subsection {* Induction and case splits *}
620 theorem multiset_induct [case_names empty add, induct type: multiset]:
621   assumes empty: "P {#}"
622   assumes add: "\<And>M x. P M \<Longrightarrow> P (M + {#x#})"
623   shows "P M"
624 proof (induct n \<equiv> "size M" arbitrary: M)
625   case 0 thus "P M" by (simp add: empty)
626 next
627   case (Suc k)
628   obtain N x where "M = N + {#x#}"
629     using `Suc k = size M` [symmetric]
630     using size_eq_Suc_imp_eq_union by fast
631   with Suc add show "P M" by simp
632 qed
634 lemma multi_nonempty_split: "M \<noteq> {#} \<Longrightarrow> \<exists>A a. M = A + {#a#}"
635 by (induct M) auto
637 lemma multiset_cases [cases type, case_names empty add]:
638 assumes em:  "M = {#} \<Longrightarrow> P"
639 assumes add: "\<And>N x. M = N + {#x#} \<Longrightarrow> P"
640 shows "P"
641 using assms by (induct M) simp_all
643 lemma multi_drop_mem_not_eq: "c \<in># B \<Longrightarrow> B - {#c#} \<noteq> B"
644 by (cases "B = {#}") (auto dest: multi_member_split)
646 lemma multiset_partition: "M = {# x:#M. P x #} + {# x:#M. \<not> P x #}"
647 apply (subst multiset_eq_iff)
648 apply auto
649 done
651 lemma mset_less_size: "(A::'a multiset) < B \<Longrightarrow> size A < size B"
652 proof (induct A arbitrary: B)
653   case (empty M)
654   then have "M \<noteq> {#}" by (simp add: mset_less_empty_nonempty)
655   then obtain M' x where "M = M' + {#x#}"
656     by (blast dest: multi_nonempty_split)
657   then show ?case by simp
658 next
659   case (add S x T)
660   have IH: "\<And>B. S < B \<Longrightarrow> size S < size B" by fact
661   have SxsubT: "S + {#x#} < T" by fact
662   then have "x \<in># T" and "S < T" by (auto dest: mset_less_insertD)
663   then obtain T' where T: "T = T' + {#x#}"
664     by (blast dest: multi_member_split)
665   then have "S < T'" using SxsubT
666     by (blast intro: mset_less_add_bothsides)
667   then have "size S < size T'" using IH by simp
668   then show ?case using T by simp
669 qed
672 subsubsection {* Strong induction and subset induction for multisets *}
674 text {* Well-foundedness of proper subset operator: *}
676 text {* proper multiset subset *}
678 definition
679   mset_less_rel :: "('a multiset * 'a multiset) set" where
680   "mset_less_rel = {(A,B). A < B}"
683   assumes "c \<in># B" and "b \<noteq> c"
684   shows "B - {#c#} + {#b#} = B + {#b#} - {#c#}"
685 proof -
686   from `c \<in># B` obtain A where B: "B = A + {#c#}"
687     by (blast dest: multi_member_split)
688   have "A + {#b#} = A + {#b#} + {#c#} - {#c#}" by simp
689   then have "A + {#b#} = A + {#c#} + {#b#} - {#c#}"
691   then show ?thesis using B by simp
692 qed
694 lemma wf_mset_less_rel: "wf mset_less_rel"
695 apply (unfold mset_less_rel_def)
696 apply (rule wf_measure [THEN wf_subset, where f1=size])
697 apply (clarsimp simp: measure_def inv_image_def mset_less_size)
698 done
700 text {* The induction rules: *}
702 lemma full_multiset_induct [case_names less]:
703 assumes ih: "\<And>B. \<forall>(A::'a multiset). A < B \<longrightarrow> P A \<Longrightarrow> P B"
704 shows "P B"
705 apply (rule wf_mset_less_rel [THEN wf_induct])
706 apply (rule ih, auto simp: mset_less_rel_def)
707 done
709 lemma multi_subset_induct [consumes 2, case_names empty add]:
710 assumes "F \<le> A"
711   and empty: "P {#}"
712   and insert: "\<And>a F. a \<in># A \<Longrightarrow> P F \<Longrightarrow> P (F + {#a#})"
713 shows "P F"
714 proof -
715   from `F \<le> A`
716   show ?thesis
717   proof (induct F)
718     show "P {#}" by fact
719   next
720     fix x F
721     assume P: "F \<le> A \<Longrightarrow> P F" and i: "F + {#x#} \<le> A"
722     show "P (F + {#x#})"
723     proof (rule insert)
724       from i show "x \<in># A" by (auto dest: mset_le_insertD)
725       from i have "F \<le> A" by (auto dest: mset_le_insertD)
726       with P show "P F" .
727     qed
728   qed
729 qed
732 subsection {* The fold combinator *}
734 definition fold :: "('a \<Rightarrow> 'b \<Rightarrow> 'b) \<Rightarrow> 'b \<Rightarrow> 'a multiset \<Rightarrow> 'b"
735 where
736   "fold f s M = Finite_Set.fold (\<lambda>x. f x ^^ count M x) s (set_of M)"
738 lemma fold_mset_empty [simp]:
739   "fold f s {#} = s"
740   by (simp add: fold_def)
742 context comp_fun_commute
743 begin
745 lemma fold_mset_insert:
746   "fold f s (M + {#x#}) = f x (fold f s M)"
747 proof -
748   interpret mset: comp_fun_commute "\<lambda>y. f y ^^ count M y"
749     by (fact comp_fun_commute_funpow)
750   interpret mset_union: comp_fun_commute "\<lambda>y. f y ^^ count (M + {#x#}) y"
751     by (fact comp_fun_commute_funpow)
752   show ?thesis
753   proof (cases "x \<in> set_of M")
754     case False
755     then have *: "count (M + {#x#}) x = 1" by simp
756     from False have "Finite_Set.fold (\<lambda>y. f y ^^ count (M + {#x#}) y) s (set_of M) =
757       Finite_Set.fold (\<lambda>y. f y ^^ count M y) s (set_of M)"
758       by (auto intro!: Finite_Set.fold_cong comp_fun_commute_funpow)
759     with False * show ?thesis
760       by (simp add: fold_def del: count_union)
761   next
762     case True
763     def N \<equiv> "set_of M - {x}"
764     from N_def True have *: "set_of M = insert x N" "x \<notin> N" "finite N" by auto
765     then have "Finite_Set.fold (\<lambda>y. f y ^^ count (M + {#x#}) y) s N =
766       Finite_Set.fold (\<lambda>y. f y ^^ count M y) s N"
767       by (auto intro!: Finite_Set.fold_cong comp_fun_commute_funpow)
768     with * show ?thesis by (simp add: fold_def del: count_union) simp
769   qed
770 qed
772 corollary fold_mset_single [simp]:
773   "fold f s {#x#} = f x s"
774 proof -
775   have "fold f s ({#} + {#x#}) = f x s" by (simp only: fold_mset_insert) simp
776   then show ?thesis by simp
777 qed
779 lemma fold_mset_fun_left_comm:
780   "f x (fold f s M) = fold f (f x s) M"
781   by (induct M) (simp_all add: fold_mset_insert fun_left_comm)
783 lemma fold_mset_union [simp]:
784   "fold f s (M + N) = fold f (fold f s M) N"
785 proof (induct M)
786   case empty then show ?case by simp
787 next
788   case (add M x)
789   have "M + {#x#} + N = (M + N) + {#x#}"
791   with add show ?case by (simp add: fold_mset_insert fold_mset_fun_left_comm)
792 qed
794 lemma fold_mset_fusion:
795   assumes "comp_fun_commute g"
796   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")
797 proof -
798   interpret comp_fun_commute g by (fact assms)
799   show "PROP ?P" by (induct A) auto
800 qed
802 end
804 text {*
805   A note on code generation: When defining some function containing a
806   subterm @{term "fold F"}, code generation is not automatic. When
807   interpreting locale @{text left_commutative} with @{text F}, the
808   would be code thms for @{const fold} become thms like
809   @{term "fold F z {#} = z"} where @{text F} is not a pattern but
810   contains defined symbols, i.e.\ is not a code thm. Hence a separate
811   constant with its own code thms needs to be introduced for @{text
812   F}. See the image operator below.
813 *}
816 subsection {* Image *}
818 definition image_mset :: "('a \<Rightarrow> 'b) \<Rightarrow> 'a multiset \<Rightarrow> 'b multiset" where
819   "image_mset f = fold (plus o single o f) {#}"
821 lemma comp_fun_commute_mset_image:
822   "comp_fun_commute (plus o single o f)"
823 proof
826 lemma image_mset_empty [simp]: "image_mset f {#} = {#}"
827   by (simp add: image_mset_def)
829 lemma image_mset_single [simp]: "image_mset f {#x#} = {#f x#}"
830 proof -
831   interpret comp_fun_commute "plus o single o f"
832     by (fact comp_fun_commute_mset_image)
833   show ?thesis by (simp add: image_mset_def)
834 qed
836 lemma image_mset_union [simp]:
837   "image_mset f (M + N) = image_mset f M + image_mset f N"
838 proof -
839   interpret comp_fun_commute "plus o single o f"
840     by (fact comp_fun_commute_mset_image)
841   show ?thesis by (induct N) (simp_all add: image_mset_def add_ac)
842 qed
844 corollary image_mset_insert:
845   "image_mset f (M + {#a#}) = image_mset f M + {#f a#}"
846   by simp
848 lemma set_of_image_mset [simp]:
849   "set_of (image_mset f M) = image f (set_of M)"
850   by (induct M) simp_all
852 lemma size_image_mset [simp]:
853   "size (image_mset f M) = size M"
854   by (induct M) simp_all
856 lemma image_mset_is_empty_iff [simp]:
857   "image_mset f M = {#} \<longleftrightarrow> M = {#}"
858   by (cases M) auto
860 syntax
861   "_comprehension1_mset" :: "'a \<Rightarrow> 'b \<Rightarrow> 'b multiset \<Rightarrow> 'a multiset"
862       ("({#_/. _ :# _#})")
863 translations
864   "{#e. x:#M#}" == "CONST image_mset (%x. e) M"
866 syntax
867   "_comprehension2_mset" :: "'a \<Rightarrow> 'b \<Rightarrow> 'b multiset \<Rightarrow> bool \<Rightarrow> 'a multiset"
868       ("({#_/ | _ :# _./ _#})")
869 translations
870   "{#e | x:#M. P#}" => "{#e. x :# {# x:#M. P#}#}"
872 text {*
873   This allows to write not just filters like @{term "{#x:#M. x<c#}"}
874   but also images like @{term "{#x+x. x:#M #}"} and @{term [source]
875   "{#x+x|x:#M. x<c#}"}, where the latter is currently displayed as
876   @{term "{#x+x|x:#M. x<c#}"}.
877 *}
879 enriched_type image_mset: image_mset
880 proof -
881   fix f g show "image_mset f \<circ> image_mset g = image_mset (f \<circ> g)"
882   proof
883     fix A
884     show "(image_mset f \<circ> image_mset g) A = image_mset (f \<circ> g) A"
885       by (induct A) simp_all
886   qed
887   show "image_mset id = id"
888   proof
889     fix A
890     show "image_mset id A = id A"
891       by (induct A) simp_all
892   qed
893 qed
895 declare image_mset.identity [simp]
898 subsection {* Further conversions *}
900 primrec multiset_of :: "'a list \<Rightarrow> 'a multiset" where
901   "multiset_of [] = {#}" |
902   "multiset_of (a # x) = multiset_of x + {# a #}"
904 lemma in_multiset_in_set:
905   "x \<in># multiset_of xs \<longleftrightarrow> x \<in> set xs"
906   by (induct xs) simp_all
908 lemma count_multiset_of:
909   "count (multiset_of xs) x = length (filter (\<lambda>y. x = y) xs)"
910   by (induct xs) simp_all
912 lemma multiset_of_zero_iff[simp]: "(multiset_of x = {#}) = (x = [])"
913 by (induct x) auto
915 lemma multiset_of_zero_iff_right[simp]: "({#} = multiset_of x) = (x = [])"
916 by (induct x) auto
918 lemma set_of_multiset_of[simp]: "set_of (multiset_of x) = set x"
919 by (induct x) auto
921 lemma mem_set_multiset_eq: "x \<in> set xs = (x :# multiset_of xs)"
922 by (induct xs) auto
924 lemma size_multiset_of [simp]: "size (multiset_of xs) = length xs"
925   by (induct xs) simp_all
927 lemma multiset_of_append [simp]:
928   "multiset_of (xs @ ys) = multiset_of xs + multiset_of ys"
929   by (induct xs arbitrary: ys) (auto simp: add_ac)
931 lemma multiset_of_filter:
932   "multiset_of (filter P xs) = {#x :# multiset_of xs. P x #}"
933   by (induct xs) simp_all
935 lemma multiset_of_rev [simp]:
936   "multiset_of (rev xs) = multiset_of xs"
937   by (induct xs) simp_all
939 lemma surj_multiset_of: "surj multiset_of"
940 apply (unfold surj_def)
941 apply (rule allI)
942 apply (rule_tac M = y in multiset_induct)
943  apply auto
944 apply (rule_tac x = "x # xa" in exI)
945 apply auto
946 done
948 lemma set_count_greater_0: "set x = {a. count (multiset_of x) a > 0}"
949 by (induct x) auto
951 lemma distinct_count_atmost_1:
952   "distinct x = (! a. count (multiset_of x) a = (if a \<in> set x then 1 else 0))"
953 apply (induct x, simp, rule iffI, simp_all)
954 apply (rule conjI)
955 apply (simp_all add: set_of_multiset_of [THEN sym] del: set_of_multiset_of)
956 apply (erule_tac x = a in allE, simp, clarify)
957 apply (erule_tac x = aa in allE, simp)
958 done
960 lemma multiset_of_eq_setD:
961   "multiset_of xs = multiset_of ys \<Longrightarrow> set xs = set ys"
962 by (rule) (auto simp add:multiset_eq_iff set_count_greater_0)
964 lemma set_eq_iff_multiset_of_eq_distinct:
965   "distinct x \<Longrightarrow> distinct y \<Longrightarrow>
966     (set x = set y) = (multiset_of x = multiset_of y)"
967 by (auto simp: multiset_eq_iff distinct_count_atmost_1)
969 lemma set_eq_iff_multiset_of_remdups_eq:
970    "(set x = set y) = (multiset_of (remdups x) = multiset_of (remdups y))"
971 apply (rule iffI)
972 apply (simp add: set_eq_iff_multiset_of_eq_distinct[THEN iffD1])
973 apply (drule distinct_remdups [THEN distinct_remdups
974       [THEN set_eq_iff_multiset_of_eq_distinct [THEN iffD2]]])
975 apply simp
976 done
978 lemma multiset_of_compl_union [simp]:
979   "multiset_of [x\<leftarrow>xs. P x] + multiset_of [x\<leftarrow>xs. \<not>P x] = multiset_of xs"
980   by (induct xs) (auto simp: add_ac)
982 lemma count_multiset_of_length_filter:
983   "count (multiset_of xs) x = length (filter (\<lambda>y. x = y) xs)"
984   by (induct xs) auto
986 lemma nth_mem_multiset_of: "i < length ls \<Longrightarrow> (ls ! i) :# multiset_of ls"
987 apply (induct ls arbitrary: i)
988  apply simp
989 apply (case_tac i)
990  apply auto
991 done
993 lemma multiset_of_remove1[simp]:
994   "multiset_of (remove1 a xs) = multiset_of xs - {#a#}"
995 by (induct xs) (auto simp add: multiset_eq_iff)
997 lemma multiset_of_eq_length:
998   assumes "multiset_of xs = multiset_of ys"
999   shows "length xs = length ys"
1000   using assms by (metis size_multiset_of)
1002 lemma multiset_of_eq_length_filter:
1003   assumes "multiset_of xs = multiset_of ys"
1004   shows "length (filter (\<lambda>x. z = x) xs) = length (filter (\<lambda>y. z = y) ys)"
1005   using assms by (metis count_multiset_of)
1007 lemma fold_multiset_equiv:
1008   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"
1009     and equiv: "multiset_of xs = multiset_of ys"
1010   shows "List.fold f xs = List.fold f ys"
1011 using f equiv [symmetric]
1012 proof (induct xs arbitrary: ys)
1013   case Nil then show ?case by simp
1014 next
1015   case (Cons x xs)
1016   then have *: "set ys = set (x # xs)" by (blast dest: multiset_of_eq_setD)
1017   have "\<And>x y. x \<in> set ys \<Longrightarrow> y \<in> set ys \<Longrightarrow> f x \<circ> f y = f y \<circ> f x"
1018     by (rule Cons.prems(1)) (simp_all add: *)
1019   moreover from * have "x \<in> set ys" by simp
1020   ultimately have "List.fold f ys = List.fold f (remove1 x ys) \<circ> f x" by (fact fold_remove1_split)
1021   moreover from Cons.prems have "List.fold f xs = List.fold f (remove1 x ys)" by (auto intro: Cons.hyps)
1022   ultimately show ?case by simp
1023 qed
1025 lemma multiset_of_insort [simp]:
1026   "multiset_of (insort x xs) = multiset_of xs + {#x#}"
1027   by (induct xs) (simp_all add: ac_simps)
1029 lemma in_multiset_of:
1030   "x \<in># multiset_of xs \<longleftrightarrow> x \<in> set xs"
1031   by (induct xs) simp_all
1033 lemma multiset_of_map:
1034   "multiset_of (map f xs) = image_mset f (multiset_of xs)"
1035   by (induct xs) simp_all
1037 definition multiset_of_set :: "'a set \<Rightarrow> 'a multiset"
1038 where
1039   "multiset_of_set = folding.F (\<lambda>x M. {#x#} + M) {#}"
1041 interpretation multiset_of_set!: folding "\<lambda>x M. {#x#} + M" "{#}"
1042 where
1043   "folding.F (\<lambda>x M. {#x#} + M) {#} = multiset_of_set"
1044 proof -
1045   interpret comp_fun_commute "\<lambda>x M. {#x#} + M" by default (simp add: fun_eq_iff ac_simps)
1046   show "folding (\<lambda>x M. {#x#} + M)" by default (fact comp_fun_commute)
1047   from multiset_of_set_def show "folding.F (\<lambda>x M. {#x#} + M) {#} = multiset_of_set" ..
1048 qed
1050 lemma count_multiset_of_set [simp]:
1051   "finite A \<Longrightarrow> x \<in> A \<Longrightarrow> count (multiset_of_set A) x = 1" (is "PROP ?P")
1052   "\<not> finite A \<Longrightarrow> count (multiset_of_set A) x = 0" (is "PROP ?Q")
1053   "x \<notin> A \<Longrightarrow> count (multiset_of_set A) x = 0" (is "PROP ?R")
1054 proof -
1055   { fix A
1056     assume "x \<notin> A"
1057     have "count (multiset_of_set A) x = 0"
1058     proof (cases "finite A")
1059       case False then show ?thesis by simp
1060     next
1061       case True from True `x \<notin> A` show ?thesis by (induct A) auto
1062     qed
1063   } note * = this
1064   then show "PROP ?P" "PROP ?Q" "PROP ?R"
1065   by (auto elim!: Set.set_insert)
1066 qed -- {* TODO: maybe define @{const multiset_of_set} also in terms of @{const Abs_multiset} *}
1068 context linorder
1069 begin
1071 definition sorted_list_of_multiset :: "'a multiset \<Rightarrow> 'a list"
1072 where
1073   "sorted_list_of_multiset M = fold insort [] M"
1075 lemma sorted_list_of_multiset_empty [simp]:
1076   "sorted_list_of_multiset {#} = []"
1077   by (simp add: sorted_list_of_multiset_def)
1079 lemma sorted_list_of_multiset_singleton [simp]:
1080   "sorted_list_of_multiset {#x#} = [x]"
1081 proof -
1082   interpret comp_fun_commute insort by (fact comp_fun_commute_insort)
1083   show ?thesis by (simp add: sorted_list_of_multiset_def)
1084 qed
1086 lemma sorted_list_of_multiset_insert [simp]:
1087   "sorted_list_of_multiset (M + {#x#}) = List.insort x (sorted_list_of_multiset M)"
1088 proof -
1089   interpret comp_fun_commute insort by (fact comp_fun_commute_insort)
1090   show ?thesis by (simp add: sorted_list_of_multiset_def)
1091 qed
1093 end
1095 lemma multiset_of_sorted_list_of_multiset [simp]:
1096   "multiset_of (sorted_list_of_multiset M) = M"
1097   by (induct M) simp_all
1099 lemma sorted_list_of_multiset_multiset_of [simp]:
1100   "sorted_list_of_multiset (multiset_of xs) = sort xs"
1101   by (induct xs) simp_all
1103 lemma finite_set_of_multiset_of_set:
1104   assumes "finite A"
1105   shows "set_of (multiset_of_set A) = A"
1106   using assms by (induct A) simp_all
1108 lemma infinite_set_of_multiset_of_set:
1109   assumes "\<not> finite A"
1110   shows "set_of (multiset_of_set A) = {}"
1111   using assms by simp
1113 lemma set_sorted_list_of_multiset [simp]:
1114   "set (sorted_list_of_multiset M) = set_of M"
1115   by (induct M) (simp_all add: set_insort)
1117 lemma sorted_list_of_multiset_of_set [simp]:
1118   "sorted_list_of_multiset (multiset_of_set A) = sorted_list_of_set A"
1119   by (cases "finite A") (induct A rule: finite_induct, simp_all add: ac_simps)
1122 subsection {* Big operators *}
1124 no_notation times (infixl "*" 70)
1125 no_notation Groups.one ("1")
1127 locale comm_monoid_mset = comm_monoid
1128 begin
1130 definition F :: "'a multiset \<Rightarrow> 'a"
1131 where
1132   eq_fold: "F M = Multiset.fold f 1 M"
1134 lemma empty [simp]:
1135   "F {#} = 1"
1136   by (simp add: eq_fold)
1138 lemma singleton [simp]:
1139   "F {#x#} = x"
1140 proof -
1141   interpret comp_fun_commute
1142     by default (simp add: fun_eq_iff left_commute)
1143   show ?thesis by (simp add: eq_fold)
1144 qed
1146 lemma union [simp]:
1147   "F (M + N) = F M * F N"
1148 proof -
1149   interpret comp_fun_commute f
1150     by default (simp add: fun_eq_iff left_commute)
1151   show ?thesis by (induct N) (simp_all add: left_commute eq_fold)
1152 qed
1154 end
1156 notation times (infixl "*" 70)
1157 notation Groups.one ("1")
1159 definition (in comm_monoid_add) msetsum :: "'a multiset \<Rightarrow> 'a"
1160 where
1161   "msetsum = comm_monoid_mset.F plus 0"
1163 definition (in comm_monoid_mult) msetprod :: "'a multiset \<Rightarrow> 'a"
1164 where
1165   "msetprod = comm_monoid_mset.F times 1"
1167 sublocale comm_monoid_add < msetsum!: comm_monoid_mset plus 0
1168 where
1169   "comm_monoid_mset.F plus 0 = msetsum"
1170 proof -
1171   show "comm_monoid_mset plus 0" ..
1172   from msetsum_def show "comm_monoid_mset.F plus 0 = msetsum" ..
1173 qed
1176 begin
1178 lemma setsum_unfold_msetsum:
1179   "setsum f A = msetsum (image_mset f (multiset_of_set A))"
1180   by (cases "finite A") (induct A rule: finite_induct, simp_all)
1182 abbreviation msetsum_image :: "('b \<Rightarrow> 'a) \<Rightarrow> 'b multiset \<Rightarrow> 'a"
1183 where
1184   "msetsum_image f M \<equiv> msetsum (image_mset f M)"
1186 end
1188 syntax
1189   "_msetsum_image" :: "pttrn \<Rightarrow> 'b set \<Rightarrow> 'a \<Rightarrow> 'a::comm_monoid_add"
1190       ("(3SUM _:#_. _)" [0, 51, 10] 10)
1192 syntax (xsymbols)
1193   "_msetsum_image" :: "pttrn \<Rightarrow> 'b set \<Rightarrow> 'a \<Rightarrow> 'a::comm_monoid_add"
1194       ("(3\<Sum>_:#_. _)" [0, 51, 10] 10)
1196 syntax (HTML output)
1197   "_msetsum_image" :: "pttrn \<Rightarrow> 'b set \<Rightarrow> 'a \<Rightarrow> 'a::comm_monoid_add"
1198       ("(3\<Sum>_\<in>#_. _)" [0, 51, 10] 10)
1200 translations
1201   "SUM i :# A. b" == "CONST msetsum_image (\<lambda>i. b) A"
1203 sublocale comm_monoid_mult < msetprod!: comm_monoid_mset times 1
1204 where
1205   "comm_monoid_mset.F times 1 = msetprod"
1206 proof -
1207   show "comm_monoid_mset times 1" ..
1208   from msetprod_def show "comm_monoid_mset.F times 1 = msetprod" ..
1209 qed
1211 context comm_monoid_mult
1212 begin
1214 lemma msetprod_empty:
1215   "msetprod {#} = 1"
1216   by (fact msetprod.empty)
1218 lemma msetprod_singleton:
1219   "msetprod {#x#} = x"
1220   by (fact msetprod.singleton)
1222 lemma msetprod_Un:
1223   "msetprod (A + B) = msetprod A * msetprod B"
1224   by (fact msetprod.union)
1226 lemma setprod_unfold_msetprod:
1227   "setprod f A = msetprod (image_mset f (multiset_of_set A))"
1228   by (cases "finite A") (induct A rule: finite_induct, simp_all)
1230 lemma msetprod_multiplicity:
1231   "msetprod M = setprod (\<lambda>x. x ^ count M x) (set_of M)"
1232   by (simp add: Multiset.fold_def setprod.eq_fold msetprod.eq_fold funpow_times_power comp_def)
1234 abbreviation msetprod_image :: "('b \<Rightarrow> 'a) \<Rightarrow> 'b multiset \<Rightarrow> 'a"
1235 where
1236   "msetprod_image f M \<equiv> msetprod (image_mset f M)"
1238 end
1240 syntax
1241   "_msetprod_image" :: "pttrn \<Rightarrow> 'b set \<Rightarrow> 'a \<Rightarrow> 'a::comm_monoid_mult"
1242       ("(3PROD _:#_. _)" [0, 51, 10] 10)
1244 syntax (xsymbols)
1245   "_msetprod_image" :: "pttrn \<Rightarrow> 'b set \<Rightarrow> 'a \<Rightarrow> 'a::comm_monoid_mult"
1246       ("(3\<Prod>_\<in>#_. _)" [0, 51, 10] 10)
1248 syntax (HTML output)
1249   "_msetprod_image" :: "pttrn \<Rightarrow> 'b set \<Rightarrow> 'a \<Rightarrow> 'a::comm_monoid_mult"
1250       ("(3\<Prod>_\<in>#_. _)" [0, 51, 10] 10)
1252 translations
1253   "PROD i :# A. b" == "CONST msetprod_image (\<lambda>i. b) A"
1255 lemma (in comm_semiring_1) dvd_msetprod:
1256   assumes "x \<in># A"
1257   shows "x dvd msetprod A"
1258 proof -
1259   from assms have "A = (A - {#x#}) + {#x#}" by simp
1260   then obtain B where "A = B + {#x#}" ..
1261   then show ?thesis by simp
1262 qed
1265 subsection {* Cardinality *}
1267 definition mcard :: "'a multiset \<Rightarrow> nat"
1268 where
1269   "mcard = msetsum \<circ> image_mset (\<lambda>_. 1)"
1271 lemma mcard_empty [simp]:
1272   "mcard {#} = 0"
1273   by (simp add: mcard_def)
1275 lemma mcard_singleton [simp]:
1276   "mcard {#a#} = Suc 0"
1277   by (simp add: mcard_def)
1279 lemma mcard_plus [simp]:
1280   "mcard (M + N) = mcard M + mcard N"
1281   by (simp add: mcard_def)
1283 lemma mcard_empty_iff [simp]:
1284   "mcard M = 0 \<longleftrightarrow> M = {#}"
1285   by (induct M) simp_all
1287 lemma mcard_unfold_setsum:
1288   "mcard M = setsum (count M) (set_of M)"
1289 proof (induct M)
1290   case empty then show ?case by simp
1291 next
1292   case (add M x) then show ?case
1293     by (cases "x \<in> set_of M")
1294       (simp_all del: mem_set_of_iff add: setsum.distrib setsum.delta' insert_absorb, simp)
1295 qed
1297 lemma size_eq_mcard:
1298   "size = mcard"
1299   by (simp add: fun_eq_iff size_def mcard_unfold_setsum)
1301 lemma mcard_multiset_of:
1302   "mcard (multiset_of xs) = length xs"
1303   by (induct xs) simp_all
1306 subsection {* Alternative representations *}
1308 subsubsection {* Lists *}
1310 context linorder
1311 begin
1313 lemma multiset_of_insort [simp]:
1314   "multiset_of (insort_key k x xs) = {#x#} + multiset_of xs"
1315   by (induct xs) (simp_all add: ac_simps)
1317 lemma multiset_of_sort [simp]:
1318   "multiset_of (sort_key k xs) = multiset_of xs"
1319   by (induct xs) (simp_all add: ac_simps)
1321 text {*
1322   This lemma shows which properties suffice to show that a function
1323   @{text "f"} with @{text "f xs = ys"} behaves like sort.
1324 *}
1326 lemma properties_for_sort_key:
1327   assumes "multiset_of ys = multiset_of xs"
1328   and "\<And>k. k \<in> set ys \<Longrightarrow> filter (\<lambda>x. f k = f x) ys = filter (\<lambda>x. f k = f x) xs"
1329   and "sorted (map f ys)"
1330   shows "sort_key f xs = ys"
1331 using assms
1332 proof (induct xs arbitrary: ys)
1333   case Nil then show ?case by simp
1334 next
1335   case (Cons x xs)
1336   from Cons.prems(2) have
1337     "\<forall>k \<in> set ys. filter (\<lambda>x. f k = f x) (remove1 x ys) = filter (\<lambda>x. f k = f x) xs"
1338     by (simp add: filter_remove1)
1339   with Cons.prems have "sort_key f xs = remove1 x ys"
1340     by (auto intro!: Cons.hyps simp add: sorted_map_remove1)
1341   moreover from Cons.prems have "x \<in> set ys"
1342     by (auto simp add: mem_set_multiset_eq intro!: ccontr)
1343   ultimately show ?case using Cons.prems by (simp add: insort_key_remove1)
1344 qed
1346 lemma properties_for_sort:
1347   assumes multiset: "multiset_of ys = multiset_of xs"
1348   and "sorted ys"
1349   shows "sort xs = ys"
1350 proof (rule properties_for_sort_key)
1351   from multiset show "multiset_of ys = multiset_of xs" .
1352   from `sorted ys` show "sorted (map (\<lambda>x. x) ys)" by simp
1353   from multiset have "\<And>k. length (filter (\<lambda>y. k = y) ys) = length (filter (\<lambda>x. k = x) xs)"
1354     by (rule multiset_of_eq_length_filter)
1355   then have "\<And>k. replicate (length (filter (\<lambda>y. k = y) ys)) k = replicate (length (filter (\<lambda>x. k = x) xs)) k"
1356     by simp
1357   then show "\<And>k. k \<in> set ys \<Longrightarrow> filter (\<lambda>y. k = y) ys = filter (\<lambda>x. k = x) xs"
1358     by (simp add: replicate_length_filter)
1359 qed
1361 lemma sort_key_by_quicksort:
1362   "sort_key f xs = sort_key f [x\<leftarrow>xs. f x < f (xs ! (length xs div 2))]
1363     @ [x\<leftarrow>xs. f x = f (xs ! (length xs div 2))]
1364     @ sort_key f [x\<leftarrow>xs. f x > f (xs ! (length xs div 2))]" (is "sort_key f ?lhs = ?rhs")
1365 proof (rule properties_for_sort_key)
1366   show "multiset_of ?rhs = multiset_of ?lhs"
1367     by (rule multiset_eqI) (auto simp add: multiset_of_filter)
1368 next
1369   show "sorted (map f ?rhs)"
1370     by (auto simp add: sorted_append intro: sorted_map_same)
1371 next
1372   fix l
1373   assume "l \<in> set ?rhs"
1374   let ?pivot = "f (xs ! (length xs div 2))"
1375   have *: "\<And>x. f l = f x \<longleftrightarrow> f x = f l" by auto
1376   have "[x \<leftarrow> sort_key f xs . f x = f l] = [x \<leftarrow> xs. f x = f l]"
1377     unfolding filter_sort by (rule properties_for_sort_key) (auto intro: sorted_map_same)
1378   with * have **: "[x \<leftarrow> sort_key f xs . f l = f x] = [x \<leftarrow> xs. f l = f x]" by simp
1379   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
1380   then have "\<And>P. [x \<leftarrow> sort_key f xs . P (f x) ?pivot \<and> f l = f x] =
1381     [x \<leftarrow> sort_key f xs. P (f l) ?pivot \<and> f l = f x]" by simp
1382   note *** = this [of "op <"] this [of "op >"] this [of "op ="]
1383   show "[x \<leftarrow> ?rhs. f l = f x] = [x \<leftarrow> ?lhs. f l = f x]"
1384   proof (cases "f l" ?pivot rule: linorder_cases)
1385     case less
1386     then have "f l \<noteq> ?pivot" and "\<not> f l > ?pivot" by auto
1387     with less show ?thesis
1388       by (simp add: filter_sort [symmetric] ** ***)
1389   next
1390     case equal then show ?thesis
1391       by (simp add: * less_le)
1392   next
1393     case greater
1394     then have "f l \<noteq> ?pivot" and "\<not> f l < ?pivot" by auto
1395     with greater show ?thesis
1396       by (simp add: filter_sort [symmetric] ** ***)
1397   qed
1398 qed
1400 lemma sort_by_quicksort:
1401   "sort xs = sort [x\<leftarrow>xs. x < xs ! (length xs div 2)]
1402     @ [x\<leftarrow>xs. x = xs ! (length xs div 2)]
1403     @ sort [x\<leftarrow>xs. x > xs ! (length xs div 2)]" (is "sort ?lhs = ?rhs")
1404   using sort_key_by_quicksort [of "\<lambda>x. x", symmetric] by simp
1406 text {* A stable parametrized quicksort *}
1408 definition part :: "('b \<Rightarrow> 'a) \<Rightarrow> 'a \<Rightarrow> 'b list \<Rightarrow> 'b list \<times> 'b list \<times> 'b list" where
1409   "part f pivot xs = ([x \<leftarrow> xs. f x < pivot], [x \<leftarrow> xs. f x = pivot], [x \<leftarrow> xs. pivot < f x])"
1411 lemma part_code [code]:
1412   "part f pivot [] = ([], [], [])"
1413   "part f pivot (x # xs) = (let (lts, eqs, gts) = part f pivot xs; x' = f x in
1414      if x' < pivot then (x # lts, eqs, gts)
1415      else if x' > pivot then (lts, eqs, x # gts)
1416      else (lts, x # eqs, gts))"
1417   by (auto simp add: part_def Let_def split_def)
1419 lemma sort_key_by_quicksort_code [code]:
1420   "sort_key f xs = (case xs of [] \<Rightarrow> []
1421     | [x] \<Rightarrow> xs
1422     | [x, y] \<Rightarrow> (if f x \<le> f y then xs else [y, x])
1423     | _ \<Rightarrow> (let (lts, eqs, gts) = part f (f (xs ! (length xs div 2))) xs
1424        in sort_key f lts @ eqs @ sort_key f gts))"
1425 proof (cases xs)
1426   case Nil then show ?thesis by simp
1427 next
1428   case (Cons _ ys) note hyps = Cons show ?thesis
1429   proof (cases ys)
1430     case Nil with hyps show ?thesis by simp
1431   next
1432     case (Cons _ zs) note hyps = hyps Cons show ?thesis
1433     proof (cases zs)
1434       case Nil with hyps show ?thesis by auto
1435     next
1436       case Cons
1437       from sort_key_by_quicksort [of f xs]
1438       have "sort_key f xs = (let (lts, eqs, gts) = part f (f (xs ! (length xs div 2))) xs
1439         in sort_key f lts @ eqs @ sort_key f gts)"
1440       by (simp only: split_def Let_def part_def fst_conv snd_conv)
1441       with hyps Cons show ?thesis by (simp only: list.cases)
1442     qed
1443   qed
1444 qed
1446 end
1448 hide_const (open) part
1450 lemma multiset_of_remdups_le: "multiset_of (remdups xs) \<le> multiset_of xs"
1451   by (induct xs) (auto intro: order_trans)
1453 lemma multiset_of_update:
1454   "i < length ls \<Longrightarrow> multiset_of (ls[i := v]) = multiset_of ls - {#ls ! i#} + {#v#}"
1455 proof (induct ls arbitrary: i)
1456   case Nil then show ?case by simp
1457 next
1458   case (Cons x xs)
1459   show ?case
1460   proof (cases i)
1461     case 0 then show ?thesis by simp
1462   next
1463     case (Suc i')
1464     with Cons show ?thesis
1465       apply simp
1466       apply (subst add_assoc)
1467       apply (subst add_commute [of "{#v#}" "{#x#}"])
1468       apply (subst add_assoc [symmetric])
1469       apply simp
1470       apply (rule mset_le_multiset_union_diff_commute)
1471       apply (simp add: mset_le_single nth_mem_multiset_of)
1472       done
1473   qed
1474 qed
1476 lemma multiset_of_swap:
1477   "i < length ls \<Longrightarrow> j < length ls \<Longrightarrow>
1478     multiset_of (ls[j := ls ! i, i := ls ! j]) = multiset_of ls"
1479   by (cases "i = j") (simp_all add: multiset_of_update nth_mem_multiset_of)
1482 subsection {* The multiset order *}
1484 subsubsection {* Well-foundedness *}
1486 definition mult1 :: "('a \<times> 'a) set => ('a multiset \<times> 'a multiset) set" where
1487   "mult1 r = {(N, M). \<exists>a M0 K. M = M0 + {#a#} \<and> N = M0 + K \<and>
1488       (\<forall>b. b :# K --> (b, a) \<in> r)}"
1490 definition mult :: "('a \<times> 'a) set => ('a multiset \<times> 'a multiset) set" where
1491   "mult r = (mult1 r)\<^sup>+"
1493 lemma not_less_empty [iff]: "(M, {#}) \<notin> mult1 r"
1494 by (simp add: mult1_def)
1496 lemma less_add: "(N, M0 + {#a#}) \<in> mult1 r ==>
1497     (\<exists>M. (M, M0) \<in> mult1 r \<and> N = M + {#a#}) \<or>
1498     (\<exists>K. (\<forall>b. b :# K --> (b, a) \<in> r) \<and> N = M0 + K)"
1499   (is "_ \<Longrightarrow> ?case1 (mult1 r) \<or> ?case2")
1500 proof (unfold mult1_def)
1501   let ?r = "\<lambda>K a. \<forall>b. b :# K --> (b, a) \<in> r"
1502   let ?R = "\<lambda>N M. \<exists>a M0 K. M = M0 + {#a#} \<and> N = M0 + K \<and> ?r K a"
1503   let ?case1 = "?case1 {(N, M). ?R N M}"
1505   assume "(N, M0 + {#a#}) \<in> {(N, M). ?R N M}"
1506   then have "\<exists>a' M0' K.
1507       M0 + {#a#} = M0' + {#a'#} \<and> N = M0' + K \<and> ?r K a'" by simp
1508   then show "?case1 \<or> ?case2"
1509   proof (elim exE conjE)
1510     fix a' M0' K
1511     assume N: "N = M0' + K" and r: "?r K a'"
1512     assume "M0 + {#a#} = M0' + {#a'#}"
1513     then have "M0 = M0' \<and> a = a' \<or>
1514         (\<exists>K'. M0 = K' + {#a'#} \<and> M0' = K' + {#a#})"
1515       by (simp only: add_eq_conv_ex)
1516     then show ?thesis
1517     proof (elim disjE conjE exE)
1518       assume "M0 = M0'" "a = a'"
1519       with N r have "?r K a \<and> N = M0 + K" by simp
1520       then have ?case2 .. then show ?thesis ..
1521     next
1522       fix K'
1523       assume "M0' = K' + {#a#}"
1524       with N have n: "N = K' + K + {#a#}" by (simp add: add_ac)
1526       assume "M0 = K' + {#a'#}"
1527       with r have "?R (K' + K) M0" by blast
1528       with n have ?case1 by simp then show ?thesis ..
1529     qed
1530   qed
1531 qed
1533 lemma all_accessible: "wf r ==> \<forall>M. M \<in> acc (mult1 r)"
1534 proof
1535   let ?R = "mult1 r"
1536   let ?W = "acc ?R"
1537   {
1538     fix M M0 a
1539     assume M0: "M0 \<in> ?W"
1540       and wf_hyp: "!!b. (b, a) \<in> r ==> (\<forall>M \<in> ?W. M + {#b#} \<in> ?W)"
1541       and acc_hyp: "\<forall>M. (M, M0) \<in> ?R --> M + {#a#} \<in> ?W"
1542     have "M0 + {#a#} \<in> ?W"
1543     proof (rule accI [of "M0 + {#a#}"])
1544       fix N
1545       assume "(N, M0 + {#a#}) \<in> ?R"
1546       then have "((\<exists>M. (M, M0) \<in> ?R \<and> N = M + {#a#}) \<or>
1547           (\<exists>K. (\<forall>b. b :# K --> (b, a) \<in> r) \<and> N = M0 + K))"
1548         by (rule less_add)
1549       then show "N \<in> ?W"
1550       proof (elim exE disjE conjE)
1551         fix M assume "(M, M0) \<in> ?R" and N: "N = M + {#a#}"
1552         from acc_hyp have "(M, M0) \<in> ?R --> M + {#a#} \<in> ?W" ..
1553         from this and `(M, M0) \<in> ?R` have "M + {#a#} \<in> ?W" ..
1554         then show "N \<in> ?W" by (simp only: N)
1555       next
1556         fix K
1557         assume N: "N = M0 + K"
1558         assume "\<forall>b. b :# K --> (b, a) \<in> r"
1559         then have "M0 + K \<in> ?W"
1560         proof (induct K)
1561           case empty
1562           from M0 show "M0 + {#} \<in> ?W" by simp
1563         next
1564           case (add K x)
1565           from add.prems have "(x, a) \<in> r" by simp
1566           with wf_hyp have "\<forall>M \<in> ?W. M + {#x#} \<in> ?W" by blast
1567           moreover from add have "M0 + K \<in> ?W" by simp
1568           ultimately have "(M0 + K) + {#x#} \<in> ?W" ..
1569           then show "M0 + (K + {#x#}) \<in> ?W" by (simp only: add_assoc)
1570         qed
1571         then show "N \<in> ?W" by (simp only: N)
1572       qed
1573     qed
1574   } note tedious_reasoning = this
1576   assume wf: "wf r"
1577   fix M
1578   show "M \<in> ?W"
1579   proof (induct M)
1580     show "{#} \<in> ?W"
1581     proof (rule accI)
1582       fix b assume "(b, {#}) \<in> ?R"
1583       with not_less_empty show "b \<in> ?W" by contradiction
1584     qed
1586     fix M a assume "M \<in> ?W"
1587     from wf have "\<forall>M \<in> ?W. M + {#a#} \<in> ?W"
1588     proof induct
1589       fix a
1590       assume r: "!!b. (b, a) \<in> r ==> (\<forall>M \<in> ?W. M + {#b#} \<in> ?W)"
1591       show "\<forall>M \<in> ?W. M + {#a#} \<in> ?W"
1592       proof
1593         fix M assume "M \<in> ?W"
1594         then show "M + {#a#} \<in> ?W"
1595           by (rule acc_induct) (rule tedious_reasoning [OF _ r])
1596       qed
1597     qed
1598     from this and `M \<in> ?W` show "M + {#a#} \<in> ?W" ..
1599   qed
1600 qed
1602 theorem wf_mult1: "wf r ==> wf (mult1 r)"
1603 by (rule acc_wfI) (rule all_accessible)
1605 theorem wf_mult: "wf r ==> wf (mult r)"
1606 unfolding mult_def by (rule wf_trancl) (rule wf_mult1)
1609 subsubsection {* Closure-free presentation *}
1611 text {* One direction. *}
1613 lemma mult_implies_one_step:
1614   "trans r ==> (M, N) \<in> mult r ==>
1615     \<exists>I J K. N = I + J \<and> M = I + K \<and> J \<noteq> {#} \<and>
1616     (\<forall>k \<in> set_of K. \<exists>j \<in> set_of J. (k, j) \<in> r)"
1617 apply (unfold mult_def mult1_def set_of_def)
1618 apply (erule converse_trancl_induct, clarify)
1619  apply (rule_tac x = M0 in exI, simp, clarify)
1620 apply (case_tac "a :# K")
1621  apply (rule_tac x = I in exI)
1622  apply (simp (no_asm))
1623  apply (rule_tac x = "(K - {#a#}) + Ka" in exI)
1624  apply (simp (no_asm_simp) add: add_assoc [symmetric])
1625  apply (drule_tac f = "\<lambda>M. M - {#a#}" in arg_cong)
1626  apply (simp add: diff_union_single_conv)
1627  apply (simp (no_asm_use) add: trans_def)
1628  apply blast
1629 apply (subgoal_tac "a :# I")
1630  apply (rule_tac x = "I - {#a#}" in exI)
1631  apply (rule_tac x = "J + {#a#}" in exI)
1632  apply (rule_tac x = "K + Ka" in exI)
1633  apply (rule conjI)
1634   apply (simp add: multiset_eq_iff split: nat_diff_split)
1635  apply (rule conjI)
1636   apply (drule_tac f = "\<lambda>M. M - {#a#}" in arg_cong, simp)
1637   apply (simp add: multiset_eq_iff split: nat_diff_split)
1638  apply (simp (no_asm_use) add: trans_def)
1639  apply blast
1640 apply (subgoal_tac "a :# (M0 + {#a#})")
1641  apply simp
1642 apply (simp (no_asm))
1643 done
1645 lemma one_step_implies_mult_aux:
1646   "trans r ==>
1647     \<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))
1648       --> (I + K, I + J) \<in> mult r"
1649 apply (induct_tac n, auto)
1650 apply (frule size_eq_Suc_imp_eq_union, clarify)
1651 apply (rename_tac "J'", simp)
1652 apply (erule notE, auto)
1653 apply (case_tac "J' = {#}")
1654  apply (simp add: mult_def)
1655  apply (rule r_into_trancl)
1656  apply (simp add: mult1_def set_of_def, blast)
1657 txt {* Now we know @{term "J' \<noteq> {#}"}. *}
1658 apply (cut_tac M = K and P = "\<lambda>x. (x, a) \<in> r" in multiset_partition)
1659 apply (erule_tac P = "\<forall>k \<in> set_of K. ?P k" in rev_mp)
1660 apply (erule ssubst)
1661 apply (simp add: Ball_def, auto)
1662 apply (subgoal_tac
1663   "((I + {# x :# K. (x, a) \<in> r #}) + {# x :# K. (x, a) \<notin> r #},
1664     (I + {# x :# K. (x, a) \<in> r #}) + J') \<in> mult r")
1665  prefer 2
1666  apply force
1667 apply (simp (no_asm_use) add: add_assoc [symmetric] mult_def)
1668 apply (erule trancl_trans)
1669 apply (rule r_into_trancl)
1670 apply (simp add: mult1_def set_of_def)
1671 apply (rule_tac x = a in exI)
1672 apply (rule_tac x = "I + J'" in exI)
1674 done
1676 lemma one_step_implies_mult:
1677   "trans r ==> J \<noteq> {#} ==> \<forall>k \<in> set_of K. \<exists>j \<in> set_of J. (k, j) \<in> r
1678     ==> (I + K, I + J) \<in> mult r"
1679 using one_step_implies_mult_aux by blast
1682 subsubsection {* Partial-order properties *}
1684 definition less_multiset :: "'a\<Colon>order multiset \<Rightarrow> 'a multiset \<Rightarrow> bool" (infix "<#" 50) where
1685   "M' <# M \<longleftrightarrow> (M', M) \<in> mult {(x', x). x' < x}"
1687 definition le_multiset :: "'a\<Colon>order multiset \<Rightarrow> 'a multiset \<Rightarrow> bool" (infix "<=#" 50) where
1688   "M' <=# M \<longleftrightarrow> M' <# M \<or> M' = M"
1690 notation (xsymbols) less_multiset (infix "\<subset>#" 50)
1691 notation (xsymbols) le_multiset (infix "\<subseteq>#" 50)
1693 interpretation multiset_order: order le_multiset less_multiset
1694 proof -
1695   have irrefl: "\<And>M :: 'a multiset. \<not> M \<subset># M"
1696   proof
1697     fix M :: "'a multiset"
1698     assume "M \<subset># M"
1699     then have MM: "(M, M) \<in> mult {(x, y). x < y}" by (simp add: less_multiset_def)
1700     have "trans {(x'::'a, x). x' < x}"
1701       by (rule transI) simp
1702     moreover note MM
1703     ultimately have "\<exists>I J K. M = I + J \<and> M = I + K
1704       \<and> J \<noteq> {#} \<and> (\<forall>k\<in>set_of K. \<exists>j\<in>set_of J. (k, j) \<in> {(x, y). x < y})"
1705       by (rule mult_implies_one_step)
1706     then obtain I J K where "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})" by blast
1708     then have aux1: "K \<noteq> {#}" and aux2: "\<forall>k\<in>set_of K. \<exists>j\<in>set_of K. k < j" by auto
1709     have "finite (set_of K)" by simp
1710     moreover note aux2
1711     ultimately have "set_of K = {}"
1712       by (induct rule: finite_induct) (auto intro: order_less_trans)
1713     with aux1 show False by simp
1714   qed
1715   have trans: "\<And>K M N :: 'a multiset. K \<subset># M \<Longrightarrow> M \<subset># N \<Longrightarrow> K \<subset># N"
1716     unfolding less_multiset_def mult_def by (blast intro: trancl_trans)
1717   show "class.order (le_multiset :: 'a multiset \<Rightarrow> _) less_multiset"
1718     by default (auto simp add: le_multiset_def irrefl dest: trans)
1719 qed
1721 lemma mult_less_irrefl [elim!]: "M \<subset># (M::'a::order multiset) ==> R"
1722   by simp
1725 subsubsection {* Monotonicity of multiset union *}
1727 lemma mult1_union: "(B, D) \<in> mult1 r ==> (C + B, C + D) \<in> mult1 r"
1728 apply (unfold mult1_def)
1729 apply auto
1730 apply (rule_tac x = a in exI)
1731 apply (rule_tac x = "C + M0" in exI)
1733 done
1735 lemma union_less_mono2: "B \<subset># D ==> C + B \<subset># C + (D::'a::order multiset)"
1736 apply (unfold less_multiset_def mult_def)
1737 apply (erule trancl_induct)
1738  apply (blast intro: mult1_union)
1739 apply (blast intro: mult1_union trancl_trans)
1740 done
1742 lemma union_less_mono1: "B \<subset># D ==> B + C \<subset># D + (C::'a::order multiset)"
1743 apply (subst add_commute [of B C])
1744 apply (subst add_commute [of D C])
1745 apply (erule union_less_mono2)
1746 done
1748 lemma union_less_mono:
1749   "A \<subset># C ==> B \<subset># D ==> A + B \<subset># C + (D::'a::order multiset)"
1750   by (blast intro!: union_less_mono1 union_less_mono2 multiset_order.less_trans)
1752 interpretation multiset_order: ordered_ab_semigroup_add plus le_multiset less_multiset
1753 proof
1754 qed (auto simp add: le_multiset_def intro: union_less_mono2)
1757 subsection {* Termination proofs with multiset orders *}
1759 lemma multi_member_skip: "x \<in># XS \<Longrightarrow> x \<in># {# y #} + XS"
1760   and multi_member_this: "x \<in># {# x #} + XS"
1761   and multi_member_last: "x \<in># {# x #}"
1762   by auto
1764 definition "ms_strict = mult pair_less"
1765 definition "ms_weak = ms_strict \<union> Id"
1767 lemma ms_reduction_pair: "reduction_pair (ms_strict, ms_weak)"
1768 unfolding reduction_pair_def ms_strict_def ms_weak_def pair_less_def
1769 by (auto intro: wf_mult1 wf_trancl simp: mult_def)
1771 lemma smsI:
1772   "(set_of A, set_of B) \<in> max_strict \<Longrightarrow> (Z + A, Z + B) \<in> ms_strict"
1773   unfolding ms_strict_def
1774 by (rule one_step_implies_mult) (auto simp add: max_strict_def pair_less_def elim!:max_ext.cases)
1776 lemma wmsI:
1777   "(set_of A, set_of B) \<in> max_strict \<or> A = {#} \<and> B = {#}
1778   \<Longrightarrow> (Z + A, Z + B) \<in> ms_weak"
1779 unfolding ms_weak_def ms_strict_def
1780 by (auto simp add: pair_less_def max_strict_def elim!:max_ext.cases intro: one_step_implies_mult)
1782 inductive pw_leq
1783 where
1784   pw_leq_empty: "pw_leq {#} {#}"
1785 | pw_leq_step:  "\<lbrakk>(x,y) \<in> pair_leq; pw_leq X Y \<rbrakk> \<Longrightarrow> pw_leq ({#x#} + X) ({#y#} + Y)"
1787 lemma pw_leq_lstep:
1788   "(x, y) \<in> pair_leq \<Longrightarrow> pw_leq {#x#} {#y#}"
1789 by (drule pw_leq_step) (rule pw_leq_empty, simp)
1791 lemma pw_leq_split:
1792   assumes "pw_leq X Y"
1793   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 = {#}))"
1794   using assms
1795 proof (induct)
1796   case pw_leq_empty thus ?case by auto
1797 next
1798   case (pw_leq_step x y X Y)
1799   then obtain A B Z where
1800     [simp]: "X = A + Z" "Y = B + Z"
1801       and 1[simp]: "(set_of A, set_of B) \<in> max_strict \<or> (B = {#} \<and> A = {#})"
1802     by auto
1803   from pw_leq_step have "x = y \<or> (x, y) \<in> pair_less"
1804     unfolding pair_leq_def by auto
1805   thus ?case
1806   proof
1807     assume [simp]: "x = y"
1808     have
1809       "{#x#} + X = A + ({#y#}+Z)
1810       \<and> {#y#} + Y = B + ({#y#}+Z)
1811       \<and> ((set_of A, set_of B) \<in> max_strict \<or> (B = {#} \<and> A = {#}))"
1812       by (auto simp: add_ac)
1813     thus ?case by (intro exI)
1814   next
1815     assume A: "(x, y) \<in> pair_less"
1816     let ?A' = "{#x#} + A" and ?B' = "{#y#} + B"
1817     have "{#x#} + X = ?A' + Z"
1818       "{#y#} + Y = ?B' + Z"
1820     moreover have
1821       "(set_of ?A', set_of ?B') \<in> max_strict"
1822       using 1 A unfolding max_strict_def
1823       by (auto elim!: max_ext.cases)
1824     ultimately show ?thesis by blast
1825   qed
1826 qed
1828 lemma
1829   assumes pwleq: "pw_leq Z Z'"
1830   shows ms_strictI: "(set_of A, set_of B) \<in> max_strict \<Longrightarrow> (Z + A, Z' + B) \<in> ms_strict"
1831   and   ms_weakI1:  "(set_of A, set_of B) \<in> max_strict \<Longrightarrow> (Z + A, Z' + B) \<in> ms_weak"
1832   and   ms_weakI2:  "(Z + {#}, Z' + {#}) \<in> ms_weak"
1833 proof -
1834   from pw_leq_split[OF pwleq]
1835   obtain A' B' Z''
1836     where [simp]: "Z = A' + Z''" "Z' = B' + Z''"
1837     and mx_or_empty: "(set_of A', set_of B') \<in> max_strict \<or> (A' = {#} \<and> B' = {#})"
1838     by blast
1839   {
1840     assume max: "(set_of A, set_of B) \<in> max_strict"
1841     from mx_or_empty
1842     have "(Z'' + (A + A'), Z'' + (B + B')) \<in> ms_strict"
1843     proof
1844       assume max': "(set_of A', set_of B') \<in> max_strict"
1845       with max have "(set_of (A + A'), set_of (B + B')) \<in> max_strict"
1846         by (auto simp: max_strict_def intro: max_ext_additive)
1847       thus ?thesis by (rule smsI)
1848     next
1849       assume [simp]: "A' = {#} \<and> B' = {#}"
1850       show ?thesis by (rule smsI) (auto intro: max)
1851     qed
1852     thus "(Z + A, Z' + B) \<in> ms_strict" by (simp add:add_ac)
1853     thus "(Z + A, Z' + B) \<in> ms_weak" by (simp add: ms_weak_def)
1854   }
1855   from mx_or_empty
1856   have "(Z'' + A', Z'' + B') \<in> ms_weak" by (rule wmsI)
1857   thus "(Z + {#}, Z' + {#}) \<in> ms_weak" by (simp add:add_ac)
1858 qed
1860 lemma empty_neutral: "{#} + x = x" "x + {#} = x"
1861 and nonempty_plus: "{# x #} + rs \<noteq> {#}"
1862 and nonempty_single: "{# x #} \<noteq> {#}"
1863 by auto
1865 setup {*
1866 let
1867   fun msetT T = Type (@{type_name multiset}, [T]);
1869   fun mk_mset T [] = Const (@{const_abbrev Mempty}, msetT T)
1870     | mk_mset T [x] = Const (@{const_name single}, T --> msetT T) \$ x
1871     | mk_mset T (x :: xs) =
1872           Const (@{const_name plus}, msetT T --> msetT T --> msetT T) \$
1873                 mk_mset T [x] \$ mk_mset T xs
1875   fun mset_member_tac m i =
1876       (if m <= 0 then
1877            rtac @{thm multi_member_this} i ORELSE rtac @{thm multi_member_last} i
1878        else
1879            rtac @{thm multi_member_skip} i THEN mset_member_tac (m - 1) i)
1881   val mset_nonempty_tac =
1882       rtac @{thm nonempty_plus} ORELSE' rtac @{thm nonempty_single}
1884   val regroup_munion_conv =
1885       Function_Lib.regroup_conv @{const_abbrev Mempty} @{const_name plus}
1886         (map (fn t => t RS eq_reflection) (@{thms add_ac} @ @{thms empty_neutral}))
1888   fun unfold_pwleq_tac i =
1889     (rtac @{thm pw_leq_step} i THEN (fn st => unfold_pwleq_tac (i + 1) st))
1890       ORELSE (rtac @{thm pw_leq_lstep} i)
1891       ORELSE (rtac @{thm pw_leq_empty} i)
1893   val set_of_simps = [@{thm set_of_empty}, @{thm set_of_single}, @{thm set_of_union},
1894                       @{thm Un_insert_left}, @{thm Un_empty_left}]
1895 in
1896   ScnpReconstruct.multiset_setup (ScnpReconstruct.Multiset
1897   {
1898     msetT=msetT, mk_mset=mk_mset, mset_regroup_conv=regroup_munion_conv,
1899     mset_member_tac=mset_member_tac, mset_nonempty_tac=mset_nonempty_tac,
1900     mset_pwleq_tac=unfold_pwleq_tac, set_of_simps=set_of_simps,
1901     smsI'= @{thm ms_strictI}, wmsI2''= @{thm ms_weakI2}, wmsI1= @{thm ms_weakI1},
1902     reduction_pair= @{thm ms_reduction_pair}
1903   })
1904 end
1905 *}
1908 subsection {* Legacy theorem bindings *}
1910 lemmas multi_count_eq = multiset_eq_iff [symmetric]
1912 lemma union_commute: "M + N = N + (M::'a multiset)"
1913   by (fact add_commute)
1915 lemma union_assoc: "(M + N) + K = M + (N + (K::'a multiset))"
1916   by (fact add_assoc)
1918 lemma union_lcomm: "M + (N + K) = N + (M + (K::'a multiset))"
1919   by (fact add_left_commute)
1921 lemmas union_ac = union_assoc union_commute union_lcomm
1923 lemma union_right_cancel: "M + K = N + K \<longleftrightarrow> M = (N::'a multiset)"
1924   by (fact add_right_cancel)
1926 lemma union_left_cancel: "K + M = K + N \<longleftrightarrow> M = (N::'a multiset)"
1927   by (fact add_left_cancel)
1929 lemma multi_union_self_other_eq: "(A::'a multiset) + X = A + Y \<Longrightarrow> X = Y"
1930   by (fact add_imp_eq)
1932 lemma mset_less_trans: "(M::'a multiset) < K \<Longrightarrow> K < N \<Longrightarrow> M < N"
1933   by (fact order_less_trans)
1935 lemma multiset_inter_commute: "A #\<inter> B = B #\<inter> A"
1936   by (fact inf.commute)
1938 lemma multiset_inter_assoc: "A #\<inter> (B #\<inter> C) = A #\<inter> B #\<inter> C"
1939   by (fact inf.assoc [symmetric])
1941 lemma multiset_inter_left_commute: "A #\<inter> (B #\<inter> C) = B #\<inter> (A #\<inter> C)"
1942   by (fact inf.left_commute)
1944 lemmas multiset_inter_ac =
1945   multiset_inter_commute
1946   multiset_inter_assoc
1947   multiset_inter_left_commute
1949 lemma mult_less_not_refl:
1950   "\<not> M \<subset># (M::'a::order multiset)"
1951   by (fact multiset_order.less_irrefl)
1953 lemma mult_less_trans:
1954   "K \<subset># M ==> M \<subset># N ==> K \<subset># (N::'a::order multiset)"
1955   by (fact multiset_order.less_trans)
1957 lemma mult_less_not_sym:
1958   "M \<subset># N ==> \<not> N \<subset># (M::'a::order multiset)"
1959   by (fact multiset_order.less_not_sym)
1961 lemma mult_less_asym:
1962   "M \<subset># N ==> (\<not> P ==> N \<subset># (M::'a::order multiset)) ==> P"
1963   by (fact multiset_order.less_asym)
1965 ML {*
1966 fun multiset_postproc _ maybe_name all_values (T as Type (_, [elem_T]))
1967                       (Const _ \$ t') =
1968     let
1969       val (maybe_opt, ps) =
1970         Nitpick_Model.dest_plain_fun t' ||> op ~~
1971         ||> map (apsnd (snd o HOLogic.dest_number))
1972       fun elems_for t =
1973         case AList.lookup (op =) ps t of
1974           SOME n => replicate n t
1975         | NONE => [Const (maybe_name, elem_T --> elem_T) \$ t]
1976     in
1977       case maps elems_for (all_values elem_T) @
1978            (if maybe_opt then [Const (Nitpick_Model.unrep (), elem_T)]
1979             else []) of
1980         [] => Const (@{const_name zero_class.zero}, T)
1981       | ts => foldl1 (fn (t1, t2) =>
1982                          Const (@{const_name plus_class.plus}, T --> T --> T)
1983                          \$ t1 \$ t2)
1984                      (map (curry (op \$) (Const (@{const_name single},
1985                                                 elem_T --> T))) ts)
1986     end
1987   | multiset_postproc _ _ _ _ t = t
1988 *}
1990 declaration {*
1991 Nitpick_Model.register_term_postprocessor @{typ "'a multiset"}
1992     multiset_postproc
1993 *}
1995 hide_const (open) fold
1998 subsection {* Naive implementation using lists *}
2000 code_datatype multiset_of
2002 lemma [code]:
2003   "{#} = multiset_of []"
2004   by simp
2006 lemma [code]:
2007   "{#x#} = multiset_of [x]"
2008   by simp
2010 lemma union_code [code]:
2011   "multiset_of xs + multiset_of ys = multiset_of (xs @ ys)"
2012   by simp
2014 lemma [code]:
2015   "image_mset f (multiset_of xs) = multiset_of (map f xs)"
2016   by (simp add: multiset_of_map)
2018 lemma [code]:
2019   "Multiset.filter f (multiset_of xs) = multiset_of (filter f xs)"
2020   by (simp add: multiset_of_filter)
2022 lemma [code]:
2023   "multiset_of xs - multiset_of ys = multiset_of (fold remove1 ys xs)"
2024   by (rule sym, induct ys arbitrary: xs) (simp_all add: diff_add diff_right_commute)
2026 lemma [code]:
2027   "multiset_of xs #\<inter> multiset_of ys =
2028     multiset_of (snd (fold (\<lambda>x (ys, zs).
2029       if x \<in> set ys then (remove1 x ys, x # zs) else (ys, zs)) xs (ys, [])))"
2030 proof -
2031   have "\<And>zs. 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, zs))) =
2033       (multiset_of xs #\<inter> multiset_of ys) + multiset_of zs"
2034     by (induct xs arbitrary: ys)
2036   then show ?thesis by simp
2037 qed
2039 lemma [code]:
2040   "multiset_of xs #\<union> multiset_of ys =
2041     multiset_of (split append (fold (\<lambda>x (ys, zs). (remove1 x ys, x # zs)) xs (ys, [])))"
2042 proof -
2043   have "\<And>zs. multiset_of (split append (fold (\<lambda>x (ys, zs). (remove1 x ys, x # zs)) xs (ys, zs))) =
2044       (multiset_of xs #\<union> multiset_of ys) + multiset_of zs"
2045     by (induct xs arbitrary: ys) (simp_all add: multiset_eq_iff)
2046   then show ?thesis by simp
2047 qed
2049 lemma [code_unfold]:
2050   "x \<in># multiset_of xs \<longleftrightarrow> x \<in> set xs"
2051   by (simp add: in_multiset_of)
2053 lemma [code]:
2054   "count (multiset_of xs) x = fold (\<lambda>y. if x = y then Suc else id) xs 0"
2055 proof -
2056   have "\<And>n. fold (\<lambda>y. if x = y then Suc else id) xs n = count (multiset_of xs) x + n"
2057     by (induct xs) simp_all
2058   then show ?thesis by simp
2059 qed
2061 lemma [code]:
2062   "set_of (multiset_of xs) = set xs"
2063   by simp
2065 lemma [code]:
2066   "sorted_list_of_multiset (multiset_of xs) = sort xs"
2067   by (induct xs) simp_all
2069 lemma [code]: -- {* not very efficient, but representation-ignorant! *}
2070   "multiset_of_set A = multiset_of (sorted_list_of_set A)"
2071   apply (cases "finite A")
2072   apply simp_all
2073   apply (induct A rule: finite_induct)
2074   apply (simp_all add: union_commute)
2075   done
2077 lemma [code]:
2078   "mcard (multiset_of xs) = length xs"
2079   by (simp add: mcard_multiset_of)
2081 lemma [code]:
2082   "A \<le> B \<longleftrightarrow> A #\<inter> B = A"
2083   by (auto simp add: inf.order_iff)
2085 instantiation multiset :: (equal) equal
2086 begin
2088 definition
2089   [code]: "HOL.equal A B \<longleftrightarrow> (A::'a multiset) \<le> B \<and> B \<le> A"
2091 instance
2092   by default (simp add: equal_multiset_def eq_iff)
2094 end
2096 lemma [code]:
2097   "(A::'a multiset) < B \<longleftrightarrow> A \<le> B \<and> A \<noteq> B"
2098   by auto
2100 lemma [code]:
2101   "msetsum (multiset_of xs) = listsum xs"
2102   by (induct xs) (simp_all add: add.commute)
2104 lemma [code]:
2105   "msetprod (multiset_of xs) = fold times xs 1"
2106 proof -
2107   have "\<And>x. fold times xs x = msetprod (multiset_of xs) * x"
2108     by (induct xs) (simp_all add: mult.assoc)
2109   then show ?thesis by simp
2110 qed
2112 lemma [code]:
2113   "size = mcard"
2114   by (fact size_eq_mcard)
2116 text {*
2117   Exercise for the casual reader: add implementations for @{const le_multiset}
2118   and @{const less_multiset} (multiset order).
2119 *}
2121 text {* Quickcheck generators *}
2123 definition (in term_syntax)
2124   msetify :: "'a\<Colon>typerep list \<times> (unit \<Rightarrow> Code_Evaluation.term)
2125     \<Rightarrow> 'a multiset \<times> (unit \<Rightarrow> Code_Evaluation.term)" where
2126   [code_unfold]: "msetify xs = Code_Evaluation.valtermify multiset_of {\<cdot>} xs"
2128 notation fcomp (infixl "\<circ>>" 60)
2129 notation scomp (infixl "\<circ>\<rightarrow>" 60)
2131 instantiation multiset :: (random) random
2132 begin
2134 definition
2135   "Quickcheck_Random.random i = Quickcheck_Random.random i \<circ>\<rightarrow> (\<lambda>xs. Pair (msetify xs))"
2137 instance ..
2139 end
2141 no_notation fcomp (infixl "\<circ>>" 60)
2142 no_notation scomp (infixl "\<circ>\<rightarrow>" 60)
2144 instantiation multiset :: (full_exhaustive) full_exhaustive
2145 begin
2147 definition full_exhaustive_multiset :: "('a multiset \<times> (unit \<Rightarrow> term) \<Rightarrow> (bool \<times> term list) option) \<Rightarrow> natural \<Rightarrow> (bool \<times> term list) option"
2148 where
2149   "full_exhaustive_multiset f i = Quickcheck_Exhaustive.full_exhaustive (\<lambda>xs. f (msetify xs)) i"
2151 instance ..
2153 end
2155 hide_const (open) msetify
2157 end