src/HOL/Library/Multiset.thy
 author haftmann Wed Apr 03 22:26:04 2013 +0200 (2013-04-03) changeset 51599 1559e9266280 parent 51548 757fa47af981 child 51600 197e25f13f0c permissions -rw-r--r--
optionalized very specific code setup for 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"
46 lemma only1_in_multiset:
47   "(\<lambda>b. if b = a then n else 0) \<in> multiset"
50 lemma union_preserves_multiset:
51   "M \<in> multiset \<Longrightarrow> N \<in> multiset \<Longrightarrow> (\<lambda>a. M a + N a) \<in> multiset"
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"
111 lemma count_single [simp]: "count {#b#} a = (if b = a then 1 else 0)"
115 subsection {* Basic operations *}
117 subsubsection {* Union *}
119 lemma count_union [simp]: "count (M + N) a = count M a + count N a"
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"
139 lemma diff_empty [simp]: "M - {#} = M \<and> {#} - M = {#}"
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)"
148 lemma diff_union_cancelL [simp]: "N + M - N = (M::'a multiset)"
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"
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#})"
176 subsubsection {* Equality of multisets *}
178 lemma single_not_empty [simp]: "{#a#} \<noteq> {#} \<and> {#} \<noteq> {#a#}"
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
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
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#}))"
261 subsubsection {* Pointwise ordering induced by count *}
263 instantiation multiset :: (type) ordered_ab_semigroup_add_imp_le
264 begin
266 lift_definition less_eq_multiset :: "'a multiset \<Rightarrow> 'a multiset \<Rightarrow> bool" is "\<lambda> A B. (\<forall>a. A a \<le> B a)"
267 by simp
268 lemmas mset_le_def = less_eq_multiset_def
270 definition less_multiset :: "'a multiset \<Rightarrow> 'a multiset \<Rightarrow> bool" where
271   mset_less_def: "(A::'a multiset) < B \<longleftrightarrow> A \<le> B \<and> A \<noteq> B"
273 instance
274   by default (auto simp add: mset_le_def mset_less_def multiset_eq_iff intro: order_trans antisym)
276 end
278 lemma mset_less_eqI:
279   "(\<And>x. count A x \<le> count B x) \<Longrightarrow> A \<le> B"
282 lemma mset_le_exists_conv:
283   "(A::'a multiset) \<le> B \<longleftrightarrow> (\<exists>C. B = A + C)"
284 apply (unfold mset_le_def, rule iffI, rule_tac x = "B - A" in exI)
285 apply (auto intro: multiset_eq_iff [THEN iffD2])
286 done
289   "(A::'a multiset) + C \<le> B + C \<longleftrightarrow> A \<le> B"
293   "C + (A::'a multiset) \<le> C + B \<longleftrightarrow> A \<le> B"
297   "(A::'a multiset) \<le> B \<Longrightarrow> C \<le> D \<Longrightarrow> A + C \<le> B + D"
301   "(A::'a multiset) \<le> A + B"
302   unfolding mset_le_def by auto
305   "B \<le> (A::'a multiset) + B"
306   unfolding mset_le_def by auto
308 lemma mset_le_single:
309   "a :# B \<Longrightarrow> {#a#} \<le> B"
312 lemma multiset_diff_union_assoc:
313   "C \<le> B \<Longrightarrow> (A::'a multiset) + B - C = A + (B - C)"
314   by (simp add: multiset_eq_iff mset_le_def)
316 lemma mset_le_multiset_union_diff_commute:
317   "B \<le> A \<Longrightarrow> (A::'a multiset) - B + C = A + C - B"
318 by (simp add: multiset_eq_iff mset_le_def)
320 lemma diff_le_self[simp]: "(M::'a multiset) - N \<le> M"
323 lemma mset_lessD: "A < B \<Longrightarrow> x \<in># A \<Longrightarrow> x \<in># B"
324 apply (clarsimp simp: mset_le_def mset_less_def)
325 apply (erule_tac x=x in allE)
326 apply auto
327 done
329 lemma mset_leD: "A \<le> B \<Longrightarrow> x \<in># A \<Longrightarrow> x \<in># B"
330 apply (clarsimp simp: mset_le_def mset_less_def)
331 apply (erule_tac x = x in allE)
332 apply auto
333 done
335 lemma mset_less_insertD: "(A + {#x#} < B) \<Longrightarrow> (x \<in># B \<and> A < B)"
336 apply (rule conjI)
338 apply (clarsimp simp: mset_le_def mset_less_def)
339 apply safe
340  apply (erule_tac x = a in allE)
341  apply (auto split: split_if_asm)
342 done
344 lemma mset_le_insertD: "(A + {#x#} \<le> B) \<Longrightarrow> (x \<in># B \<and> A \<le> B)"
345 apply (rule conjI)
347 apply (force simp: mset_le_def mset_less_def split: split_if_asm)
348 done
350 lemma mset_less_of_empty[simp]: "A < {#} \<longleftrightarrow> False"
351   by (auto simp add: mset_less_def mset_le_def multiset_eq_iff)
353 lemma multi_psub_of_add_self[simp]: "A < A + {#x#}"
354   by (auto simp: mset_le_def mset_less_def)
356 lemma multi_psub_self[simp]: "(A::'a multiset) < A = False"
357   by simp
360   "T + {#x#} < S + {#x#} \<Longrightarrow> T < S"
363 lemma mset_less_empty_nonempty:
364   "{#} < S \<longleftrightarrow> S \<noteq> {#}"
365   by (auto simp: mset_le_def mset_less_def)
367 lemma mset_less_diff_self:
368   "c \<in># B \<Longrightarrow> B - {#c#} < B"
369   by (auto simp: mset_le_def mset_less_def multiset_eq_iff)
372 subsubsection {* Intersection *}
374 instantiation multiset :: (type) semilattice_inf
375 begin
377 definition inf_multiset :: "'a multiset \<Rightarrow> 'a multiset \<Rightarrow> 'a multiset" where
378   multiset_inter_def: "inf_multiset A B = A - (A - B)"
380 instance
381 proof -
382   have aux: "\<And>m n q :: nat. m \<le> n \<Longrightarrow> m \<le> q \<Longrightarrow> m \<le> n - (n - q)" by arith
383   show "OFCLASS('a multiset, semilattice_inf_class)"
384     by default (auto simp add: multiset_inter_def mset_le_def aux)
385 qed
387 end
389 abbreviation multiset_inter :: "'a multiset \<Rightarrow> 'a multiset \<Rightarrow> 'a multiset" (infixl "#\<inter>" 70) where
390   "multiset_inter \<equiv> inf"
392 lemma multiset_inter_count [simp]:
393   "count (A #\<inter> B) x = min (count A x) (count B x)"
396 lemma multiset_inter_single: "a \<noteq> b \<Longrightarrow> {#a#} #\<inter> {#b#} = {#}"
397   by (rule multiset_eqI) auto
399 lemma multiset_union_diff_commute:
400   assumes "B #\<inter> C = {#}"
401   shows "A + B - C = A - C + B"
402 proof (rule multiset_eqI)
403   fix x
404   from assms have "min (count B x) (count C x) = 0"
405     by (auto simp add: multiset_eq_iff)
406   then have "count B x = 0 \<or> count C x = 0"
407     by auto
408   then show "count (A + B - C) x = count (A - C + B) x"
409     by auto
410 qed
413 subsubsection {* Filter (with comprehension syntax) *}
415 text {* Multiset comprehension *}
417 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"
418 by (rule filter_preserves_multiset)
420 hide_const (open) filter
422 lemma count_filter [simp]:
423   "count (Multiset.filter P M) a = (if P a then count M a else 0)"
426 lemma filter_empty [simp]:
427   "Multiset.filter P {#} = {#}"
428   by (rule multiset_eqI) simp
430 lemma filter_single [simp]:
431   "Multiset.filter P {#x#} = (if P x then {#x#} else {#})"
432   by (rule multiset_eqI) simp
434 lemma filter_union [simp]:
435   "Multiset.filter P (M + N) = Multiset.filter P M + Multiset.filter P N"
436   by (rule multiset_eqI) simp
438 lemma filter_diff [simp]:
439   "Multiset.filter P (M - N) = Multiset.filter P M - Multiset.filter P N"
440   by (rule multiset_eqI) simp
442 lemma filter_inter [simp]:
443   "Multiset.filter P (M #\<inter> N) = Multiset.filter P M #\<inter> Multiset.filter P N"
444   by (rule multiset_eqI) simp
446 syntax
447   "_MCollect" :: "pttrn \<Rightarrow> 'a multiset \<Rightarrow> bool \<Rightarrow> 'a multiset"    ("(1{# _ :# _./ _#})")
448 syntax (xsymbol)
449   "_MCollect" :: "pttrn \<Rightarrow> 'a multiset \<Rightarrow> bool \<Rightarrow> 'a multiset"    ("(1{# _ \<in># _./ _#})")
450 translations
451   "{#x \<in># M. P#}" == "CONST Multiset.filter (\<lambda>x. P) M"
454 subsubsection {* Set of elements *}
456 definition set_of :: "'a multiset => 'a set" where
457   "set_of M = {x. x :# M}"
459 lemma set_of_empty [simp]: "set_of {#} = {}"
462 lemma set_of_single [simp]: "set_of {#b#} = {b}"
465 lemma set_of_union [simp]: "set_of (M + N) = set_of M \<union> set_of N"
466 by (auto simp add: set_of_def)
468 lemma set_of_eq_empty_iff [simp]: "(set_of M = {}) = (M = {#})"
469 by (auto simp add: set_of_def multiset_eq_iff)
471 lemma mem_set_of_iff [simp]: "(x \<in> set_of M) = (x :# M)"
472 by (auto simp add: set_of_def)
474 lemma set_of_filter [simp]: "set_of {# x:#M. P x #} = set_of M \<inter> {x. P x}"
475 by (auto simp add: set_of_def)
477 lemma finite_set_of [iff]: "finite (set_of M)"
478   using count [of M] by (simp add: multiset_def set_of_def)
480 lemma finite_Collect_mem [iff]: "finite {x. x :# M}"
481   unfolding set_of_def[symmetric] by simp
483 subsubsection {* Size *}
485 instantiation multiset :: (type) size
486 begin
488 definition size_def:
489   "size M = setsum (count M) (set_of M)"
491 instance ..
493 end
495 lemma size_empty [simp]: "size {#} = 0"
498 lemma size_single [simp]: "size {#b#} = 1"
501 lemma setsum_count_Int:
502   "finite A ==> setsum (count N) (A \<inter> set_of N) = setsum (count N) A"
503 apply (induct rule: finite_induct)
504  apply simp
505 apply (simp add: Int_insert_left set_of_def)
506 done
508 lemma size_union [simp]: "size (M + N::'a multiset) = size M + size N"
509 apply (unfold size_def)
510 apply (subgoal_tac "count (M + N) = (\<lambda>a. count M a + count N a)")
511  prefer 2
512  apply (rule ext, simp)
514 apply (subst Int_commute)
515 apply (simp (no_asm_simp) add: setsum_count_Int)
516 done
518 lemma size_eq_0_iff_empty [iff]: "(size M = 0) = (M = {#})"
519 by (auto simp add: size_def multiset_eq_iff)
521 lemma nonempty_has_size: "(S \<noteq> {#}) = (0 < size S)"
522 by (metis gr0I gr_implies_not0 size_empty size_eq_0_iff_empty)
524 lemma size_eq_Suc_imp_elem: "size M = Suc n ==> \<exists>a. a :# M"
525 apply (unfold size_def)
526 apply (drule setsum_SucD)
527 apply auto
528 done
530 lemma size_eq_Suc_imp_eq_union:
531   assumes "size M = Suc n"
532   shows "\<exists>a N. M = N + {#a#}"
533 proof -
534   from assms obtain a where "a \<in># M"
535     by (erule size_eq_Suc_imp_elem [THEN exE])
536   then have "M = M - {#a#} + {#a#}" by simp
537   then show ?thesis by blast
538 qed
541 subsection {* Induction and case splits *}
543 theorem multiset_induct [case_names empty add, induct type: multiset]:
544   assumes empty: "P {#}"
545   assumes add: "\<And>M x. P M \<Longrightarrow> P (M + {#x#})"
546   shows "P M"
547 proof (induct n \<equiv> "size M" arbitrary: M)
548   case 0 thus "P M" by (simp add: empty)
549 next
550   case (Suc k)
551   obtain N x where "M = N + {#x#}"
552     using `Suc k = size M` [symmetric]
553     using size_eq_Suc_imp_eq_union by fast
554   with Suc add show "P M" by simp
555 qed
557 lemma multi_nonempty_split: "M \<noteq> {#} \<Longrightarrow> \<exists>A a. M = A + {#a#}"
558 by (induct M) auto
560 lemma multiset_cases [cases type, case_names empty add]:
561 assumes em:  "M = {#} \<Longrightarrow> P"
562 assumes add: "\<And>N x. M = N + {#x#} \<Longrightarrow> P"
563 shows "P"
564 using assms by (induct M) simp_all
566 lemma multi_member_split: "x \<in># M \<Longrightarrow> \<exists>A. M = A + {#x#}"
567 by (rule_tac x="M - {#x#}" in exI, simp)
569 lemma multi_drop_mem_not_eq: "c \<in># B \<Longrightarrow> B - {#c#} \<noteq> B"
570 by (cases "B = {#}") (auto dest: multi_member_split)
572 lemma multiset_partition: "M = {# x:#M. P x #} + {# x:#M. \<not> P x #}"
573 apply (subst multiset_eq_iff)
574 apply auto
575 done
577 lemma mset_less_size: "(A::'a multiset) < B \<Longrightarrow> size A < size B"
578 proof (induct A arbitrary: B)
579   case (empty M)
580   then have "M \<noteq> {#}" by (simp add: mset_less_empty_nonempty)
581   then obtain M' x where "M = M' + {#x#}"
582     by (blast dest: multi_nonempty_split)
583   then show ?case by simp
584 next
585   case (add S x T)
586   have IH: "\<And>B. S < B \<Longrightarrow> size S < size B" by fact
587   have SxsubT: "S + {#x#} < T" by fact
588   then have "x \<in># T" and "S < T" by (auto dest: mset_less_insertD)
589   then obtain T' where T: "T = T' + {#x#}"
590     by (blast dest: multi_member_split)
591   then have "S < T'" using SxsubT
593   then have "size S < size T'" using IH by simp
594   then show ?case using T by simp
595 qed
598 subsubsection {* Strong induction and subset induction for multisets *}
600 text {* Well-foundedness of proper subset operator: *}
602 text {* proper multiset subset *}
604 definition
605   mset_less_rel :: "('a multiset * 'a multiset) set" where
606   "mset_less_rel = {(A,B). A < B}"
609   assumes "c \<in># B" and "b \<noteq> c"
610   shows "B - {#c#} + {#b#} = B + {#b#} - {#c#}"
611 proof -
612   from `c \<in># B` obtain A where B: "B = A + {#c#}"
613     by (blast dest: multi_member_split)
614   have "A + {#b#} = A + {#b#} + {#c#} - {#c#}" by simp
615   then have "A + {#b#} = A + {#c#} + {#b#} - {#c#}"
617   then show ?thesis using B by simp
618 qed
620 lemma wf_mset_less_rel: "wf mset_less_rel"
621 apply (unfold mset_less_rel_def)
622 apply (rule wf_measure [THEN wf_subset, where f1=size])
623 apply (clarsimp simp: measure_def inv_image_def mset_less_size)
624 done
626 text {* The induction rules: *}
628 lemma full_multiset_induct [case_names less]:
629 assumes ih: "\<And>B. \<forall>(A::'a multiset). A < B \<longrightarrow> P A \<Longrightarrow> P B"
630 shows "P B"
631 apply (rule wf_mset_less_rel [THEN wf_induct])
632 apply (rule ih, auto simp: mset_less_rel_def)
633 done
635 lemma multi_subset_induct [consumes 2, case_names empty add]:
636 assumes "F \<le> A"
637   and empty: "P {#}"
638   and insert: "\<And>a F. a \<in># A \<Longrightarrow> P F \<Longrightarrow> P (F + {#a#})"
639 shows "P F"
640 proof -
641   from `F \<le> A`
642   show ?thesis
643   proof (induct F)
644     show "P {#}" by fact
645   next
646     fix x F
647     assume P: "F \<le> A \<Longrightarrow> P F" and i: "F + {#x#} \<le> A"
648     show "P (F + {#x#})"
649     proof (rule insert)
650       from i show "x \<in># A" by (auto dest: mset_le_insertD)
651       from i have "F \<le> A" by (auto dest: mset_le_insertD)
652       with P show "P F" .
653     qed
654   qed
655 qed
658 subsection {* The fold combinator *}
660 definition fold :: "('a \<Rightarrow> 'b \<Rightarrow> 'b) \<Rightarrow> 'b \<Rightarrow> 'a multiset \<Rightarrow> 'b"
661 where
662   "fold f s M = Finite_Set.fold (\<lambda>x. f x ^^ count M x) s (set_of M)"
664 lemma fold_mset_empty [simp]:
665   "fold f s {#} = s"
668 context comp_fun_commute
669 begin
671 lemma fold_mset_insert:
672   "fold f s (M + {#x#}) = f x (fold f s M)"
673 proof -
674   interpret mset: comp_fun_commute "\<lambda>y. f y ^^ count M y"
675     by (fact comp_fun_commute_funpow)
676   interpret mset_union: comp_fun_commute "\<lambda>y. f y ^^ count (M + {#x#}) y"
677     by (fact comp_fun_commute_funpow)
678   show ?thesis
679   proof (cases "x \<in> set_of M")
680     case False
681     then have *: "count (M + {#x#}) x = 1" by simp
682     from False have "Finite_Set.fold (\<lambda>y. f y ^^ count (M + {#x#}) y) s (set_of M) =
683       Finite_Set.fold (\<lambda>y. f y ^^ count M y) s (set_of M)"
684       by (auto intro!: Finite_Set.fold_cong comp_fun_commute_funpow)
685     with False * show ?thesis
686       by (simp add: fold_def del: count_union)
687   next
688     case True
689     def N \<equiv> "set_of M - {x}"
690     from N_def True have *: "set_of M = insert x N" "x \<notin> N" "finite N" by auto
691     then have "Finite_Set.fold (\<lambda>y. f y ^^ count (M + {#x#}) y) s N =
692       Finite_Set.fold (\<lambda>y. f y ^^ count M y) s N"
693       by (auto intro!: Finite_Set.fold_cong comp_fun_commute_funpow)
694     with * show ?thesis by (simp add: fold_def del: count_union) simp
695   qed
696 qed
698 corollary fold_mset_single [simp]:
699   "fold f s {#x#} = f x s"
700 proof -
701   have "fold f s ({#} + {#x#}) = f x s" by (simp only: fold_mset_insert) simp
702   then show ?thesis by simp
703 qed
705 lemma fold_mset_fun_left_comm:
706   "f x (fold f s M) = fold f (f x s) M"
707   by (induct M) (simp_all add: fold_mset_insert fun_left_comm)
709 lemma fold_mset_union [simp]:
710   "fold f s (M + N) = fold f (fold f s M) N"
711 proof (induct M)
712   case empty then show ?case by simp
713 next
715   have "M + {#x#} + N = (M + N) + {#x#}"
718 qed
720 lemma fold_mset_fusion:
721   assumes "comp_fun_commute g"
722   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")
723 proof -
724   interpret comp_fun_commute g by (fact assms)
725   show "PROP ?P" by (induct A) auto
726 qed
728 end
730 text {*
731   A note on code generation: When defining some function containing a
732   subterm @{term "fold F"}, code generation is not automatic. When
733   interpreting locale @{text left_commutative} with @{text F}, the
734   would be code thms for @{const fold} become thms like
735   @{term "fold F z {#} = z"} where @{text F} is not a pattern but
736   contains defined symbols, i.e.\ is not a code thm. Hence a separate
737   constant with its own code thms needs to be introduced for @{text
738   F}. See the image operator below.
739 *}
742 subsection {* Image *}
744 definition image_mset :: "('a \<Rightarrow> 'b) \<Rightarrow> 'a multiset \<Rightarrow> 'b multiset" where
745   "image_mset f = fold (plus o single o f) {#}"
747 lemma comp_fun_commute_mset_image:
748   "comp_fun_commute (plus o single o f)"
749 proof
752 lemma image_mset_empty [simp]: "image_mset f {#} = {#}"
755 lemma image_mset_single [simp]: "image_mset f {#x#} = {#f x#}"
756 proof -
757   interpret comp_fun_commute "plus o single o f"
758     by (fact comp_fun_commute_mset_image)
759   show ?thesis by (simp add: image_mset_def)
760 qed
762 lemma image_mset_union [simp]:
763   "image_mset f (M + N) = image_mset f M + image_mset f N"
764 proof -
765   interpret comp_fun_commute "plus o single o f"
766     by (fact comp_fun_commute_mset_image)
768 qed
770 corollary image_mset_insert:
771   "image_mset f (M + {#a#}) = image_mset f M + {#f a#}"
772   by simp
774 lemma set_of_image_mset [simp]:
775   "set_of (image_mset f M) = image f (set_of M)"
776   by (induct M) simp_all
778 lemma size_image_mset [simp]:
779   "size (image_mset f M) = size M"
780   by (induct M) simp_all
782 lemma image_mset_is_empty_iff [simp]:
783   "image_mset f M = {#} \<longleftrightarrow> M = {#}"
784   by (cases M) auto
786 syntax
787   "_comprehension1_mset" :: "'a \<Rightarrow> 'b \<Rightarrow> 'b multiset \<Rightarrow> 'a multiset"
788       ("({#_/. _ :# _#})")
789 translations
790   "{#e. x:#M#}" == "CONST image_mset (%x. e) M"
792 syntax
793   "_comprehension2_mset" :: "'a \<Rightarrow> 'b \<Rightarrow> 'b multiset \<Rightarrow> bool \<Rightarrow> 'a multiset"
794       ("({#_/ | _ :# _./ _#})")
795 translations
796   "{#e | x:#M. P#}" => "{#e. x :# {# x:#M. P#}#}"
798 text {*
799   This allows to write not just filters like @{term "{#x:#M. x<c#}"}
800   but also images like @{term "{#x+x. x:#M #}"} and @{term [source]
801   "{#x+x|x:#M. x<c#}"}, where the latter is currently displayed as
802   @{term "{#x+x|x:#M. x<c#}"}.
803 *}
805 enriched_type image_mset: image_mset
806 proof -
807   fix f g show "image_mset f \<circ> image_mset g = image_mset (f \<circ> g)"
808   proof
809     fix A
810     show "(image_mset f \<circ> image_mset g) A = image_mset (f \<circ> g) A"
811       by (induct A) simp_all
812   qed
813   show "image_mset id = id"
814   proof
815     fix A
816     show "image_mset id A = id A"
817       by (induct A) simp_all
818   qed
819 qed
821 declare image_mset.identity [simp]
824 subsection {* Further conversions *}
826 primrec multiset_of :: "'a list \<Rightarrow> 'a multiset" where
827   "multiset_of [] = {#}" |
828   "multiset_of (a # x) = multiset_of x + {# a #}"
830 lemma in_multiset_in_set:
831   "x \<in># multiset_of xs \<longleftrightarrow> x \<in> set xs"
832   by (induct xs) simp_all
834 lemma count_multiset_of:
835   "count (multiset_of xs) x = length (filter (\<lambda>y. x = y) xs)"
836   by (induct xs) simp_all
838 lemma multiset_of_zero_iff[simp]: "(multiset_of x = {#}) = (x = [])"
839 by (induct x) auto
841 lemma multiset_of_zero_iff_right[simp]: "({#} = multiset_of x) = (x = [])"
842 by (induct x) auto
844 lemma set_of_multiset_of[simp]: "set_of (multiset_of x) = set x"
845 by (induct x) auto
847 lemma mem_set_multiset_eq: "x \<in> set xs = (x :# multiset_of xs)"
848 by (induct xs) auto
850 lemma size_multiset_of [simp]: "size (multiset_of xs) = length xs"
851   by (induct xs) simp_all
853 lemma multiset_of_append [simp]:
854   "multiset_of (xs @ ys) = multiset_of xs + multiset_of ys"
855   by (induct xs arbitrary: ys) (auto simp: add_ac)
857 lemma multiset_of_filter:
858   "multiset_of (filter P xs) = {#x :# multiset_of xs. P x #}"
859   by (induct xs) simp_all
861 lemma multiset_of_rev [simp]:
862   "multiset_of (rev xs) = multiset_of xs"
863   by (induct xs) simp_all
865 lemma surj_multiset_of: "surj multiset_of"
866 apply (unfold surj_def)
867 apply (rule allI)
868 apply (rule_tac M = y in multiset_induct)
869  apply auto
870 apply (rule_tac x = "x # xa" in exI)
871 apply auto
872 done
874 lemma set_count_greater_0: "set x = {a. count (multiset_of x) a > 0}"
875 by (induct x) auto
877 lemma distinct_count_atmost_1:
878   "distinct x = (! a. count (multiset_of x) a = (if a \<in> set x then 1 else 0))"
879 apply (induct x, simp, rule iffI, simp_all)
880 apply (rule conjI)
881 apply (simp_all add: set_of_multiset_of [THEN sym] del: set_of_multiset_of)
882 apply (erule_tac x = a in allE, simp, clarify)
883 apply (erule_tac x = aa in allE, simp)
884 done
886 lemma multiset_of_eq_setD:
887   "multiset_of xs = multiset_of ys \<Longrightarrow> set xs = set ys"
888 by (rule) (auto simp add:multiset_eq_iff set_count_greater_0)
890 lemma set_eq_iff_multiset_of_eq_distinct:
891   "distinct x \<Longrightarrow> distinct y \<Longrightarrow>
892     (set x = set y) = (multiset_of x = multiset_of y)"
893 by (auto simp: multiset_eq_iff distinct_count_atmost_1)
895 lemma set_eq_iff_multiset_of_remdups_eq:
896    "(set x = set y) = (multiset_of (remdups x) = multiset_of (remdups y))"
897 apply (rule iffI)
898 apply (simp add: set_eq_iff_multiset_of_eq_distinct[THEN iffD1])
899 apply (drule distinct_remdups [THEN distinct_remdups
900       [THEN set_eq_iff_multiset_of_eq_distinct [THEN iffD2]]])
901 apply simp
902 done
904 lemma multiset_of_compl_union [simp]:
905   "multiset_of [x\<leftarrow>xs. P x] + multiset_of [x\<leftarrow>xs. \<not>P x] = multiset_of xs"
906   by (induct xs) (auto simp: add_ac)
908 lemma count_multiset_of_length_filter:
909   "count (multiset_of xs) x = length (filter (\<lambda>y. x = y) xs)"
910   by (induct xs) auto
912 lemma nth_mem_multiset_of: "i < length ls \<Longrightarrow> (ls ! i) :# multiset_of ls"
913 apply (induct ls arbitrary: i)
914  apply simp
915 apply (case_tac i)
916  apply auto
917 done
919 lemma multiset_of_remove1[simp]:
920   "multiset_of (remove1 a xs) = multiset_of xs - {#a#}"
921 by (induct xs) (auto simp add: multiset_eq_iff)
923 lemma multiset_of_eq_length:
924   assumes "multiset_of xs = multiset_of ys"
925   shows "length xs = length ys"
926   using assms by (metis size_multiset_of)
928 lemma multiset_of_eq_length_filter:
929   assumes "multiset_of xs = multiset_of ys"
930   shows "length (filter (\<lambda>x. z = x) xs) = length (filter (\<lambda>y. z = y) ys)"
931   using assms by (metis count_multiset_of)
933 lemma fold_multiset_equiv:
934   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"
935     and equiv: "multiset_of xs = multiset_of ys"
936   shows "List.fold f xs = List.fold f ys"
937 using f equiv [symmetric]
938 proof (induct xs arbitrary: ys)
939   case Nil then show ?case by simp
940 next
941   case (Cons x xs)
942   then have *: "set ys = set (x # xs)" by (blast dest: multiset_of_eq_setD)
943   have "\<And>x y. x \<in> set ys \<Longrightarrow> y \<in> set ys \<Longrightarrow> f x \<circ> f y = f y \<circ> f x"
944     by (rule Cons.prems(1)) (simp_all add: *)
945   moreover from * have "x \<in> set ys" by simp
946   ultimately have "List.fold f ys = List.fold f (remove1 x ys) \<circ> f x" by (fact fold_remove1_split)
947   moreover from Cons.prems have "List.fold f xs = List.fold f (remove1 x ys)" by (auto intro: Cons.hyps)
948   ultimately show ?case by simp
949 qed
951 lemma multiset_of_insort [simp]:
952   "multiset_of (insort x xs) = multiset_of xs + {#x#}"
953   by (induct xs) (simp_all add: ac_simps)
955 definition multiset_of_set :: "'a set \<Rightarrow> 'a multiset"
956 where
957   "multiset_of_set = folding.F (\<lambda>x M. {#x#} + M) {#}"
959 interpretation multiset_of_set!: folding "\<lambda>x M. {#x#} + M" "{#}"
960 where
961   "folding.F (\<lambda>x M. {#x#} + M) {#} = multiset_of_set"
962 proof -
963   interpret comp_fun_commute "\<lambda>x M. {#x#} + M" by default (simp add: fun_eq_iff ac_simps)
964   show "folding (\<lambda>x M. {#x#} + M)" by default (fact comp_fun_commute)
965   from multiset_of_set_def show "folding.F (\<lambda>x M. {#x#} + M) {#} = multiset_of_set" ..
966 qed
968 context linorder
969 begin
971 definition sorted_list_of_multiset :: "'a multiset \<Rightarrow> 'a list"
972 where
973   "sorted_list_of_multiset M = fold insort [] M"
975 lemma sorted_list_of_multiset_empty [simp]:
976   "sorted_list_of_multiset {#} = []"
979 lemma sorted_list_of_multiset_singleton [simp]:
980   "sorted_list_of_multiset {#x#} = [x]"
981 proof -
982   interpret comp_fun_commute insort by (fact comp_fun_commute_insort)
983   show ?thesis by (simp add: sorted_list_of_multiset_def)
984 qed
986 lemma sorted_list_of_multiset_insert [simp]:
987   "sorted_list_of_multiset (M + {#x#}) = List.insort x (sorted_list_of_multiset M)"
988 proof -
989   interpret comp_fun_commute insort by (fact comp_fun_commute_insort)
990   show ?thesis by (simp add: sorted_list_of_multiset_def)
991 qed
993 end
995 lemma multiset_of_sorted_list_of_multiset [simp]:
996   "multiset_of (sorted_list_of_multiset M) = M"
997   by (induct M) simp_all
999 lemma sorted_list_of_multiset_multiset_of [simp]:
1000   "sorted_list_of_multiset (multiset_of xs) = sort xs"
1001   by (induct xs) simp_all
1003 lemma finite_set_of_multiset_of_set:
1004   assumes "finite A"
1005   shows "set_of (multiset_of_set A) = A"
1006   using assms by (induct A) simp_all
1008 lemma infinite_set_of_multiset_of_set:
1009   assumes "\<not> finite A"
1010   shows "set_of (multiset_of_set A) = {}"
1011   using assms by simp
1013 lemma set_sorted_list_of_multiset [simp]:
1014   "set (sorted_list_of_multiset M) = set_of M"
1015   by (induct M) (simp_all add: set_insort)
1017 lemma sorted_list_of_multiset_of_set [simp]:
1018   "sorted_list_of_multiset (multiset_of_set A) = sorted_list_of_set A"
1019   by (cases "finite A") (induct A rule: finite_induct, simp_all add: ac_simps)
1022 subsection {* Big operators *}
1024 no_notation times (infixl "*" 70)
1025 no_notation Groups.one ("1")
1027 locale comm_monoid_mset = comm_monoid
1028 begin
1030 definition F :: "'a multiset \<Rightarrow> 'a"
1031 where
1032   eq_fold: "F M = Multiset.fold f 1 M"
1034 lemma empty [simp]:
1035   "F {#} = 1"
1038 lemma singleton [simp]:
1039   "F {#x#} = x"
1040 proof -
1041   interpret comp_fun_commute
1042     by default (simp add: fun_eq_iff left_commute)
1043   show ?thesis by (simp add: eq_fold)
1044 qed
1046 lemma union [simp]:
1047   "F (M + N) = F M * F N"
1048 proof -
1049   interpret comp_fun_commute f
1050     by default (simp add: fun_eq_iff left_commute)
1051   show ?thesis by (induct N) (simp_all add: left_commute eq_fold)
1052 qed
1054 end
1056 notation times (infixl "*" 70)
1057 notation Groups.one ("1")
1059 definition (in comm_monoid_add) msetsum :: "'a multiset \<Rightarrow> 'a"
1060 where
1061   "msetsum = comm_monoid_mset.F plus 0"
1063 definition (in comm_monoid_mult) msetprod :: "'a multiset \<Rightarrow> 'a"
1064 where
1065   "msetprod = comm_monoid_mset.F times 1"
1067 sublocale comm_monoid_add < msetsum!: comm_monoid_mset plus 0
1068 where
1069   "comm_monoid_mset.F plus 0 = msetsum"
1070 proof -
1071   show "comm_monoid_mset plus 0" ..
1072   from msetsum_def show "comm_monoid_mset.F plus 0 = msetsum" ..
1073 qed
1076 begin
1078 lemma setsum_unfold_msetsum:
1079   "setsum f A = msetsum (image_mset f (multiset_of_set A))"
1080   by (cases "finite A") (induct A rule: finite_induct, simp_all)
1082 abbreviation msetsum_image :: "('b \<Rightarrow> 'a) \<Rightarrow> 'b multiset \<Rightarrow> 'a"
1083 where
1084   "msetsum_image f M \<equiv> msetsum (image_mset f M)"
1086 end
1088 syntax
1089   "_msetsum_image" :: "pttrn \<Rightarrow> 'b set \<Rightarrow> 'a \<Rightarrow> 'a::comm_monoid_add"
1090       ("(3SUM _:#_. _)" [0, 51, 10] 10)
1092 syntax (xsymbols)
1093   "_msetsum_image" :: "pttrn \<Rightarrow> 'b set \<Rightarrow> 'a \<Rightarrow> 'a::comm_monoid_add"
1094       ("(3\<Sum>_:#_. _)" [0, 51, 10] 10)
1096 syntax (HTML output)
1097   "_msetsum_image" :: "pttrn \<Rightarrow> 'b set \<Rightarrow> 'a \<Rightarrow> 'a::comm_monoid_add"
1098       ("(3\<Sum>_\<in>#_. _)" [0, 51, 10] 10)
1100 translations
1101   "SUM i :# A. b" == "CONST msetsum_image (\<lambda>i. b) A"
1103 sublocale comm_monoid_mult < msetprod!: comm_monoid_mset times 1
1104 where
1105   "comm_monoid_mset.F times 1 = msetprod"
1106 proof -
1107   show "comm_monoid_mset times 1" ..
1108   from msetprod_def show "comm_monoid_mset.F times 1 = msetprod" ..
1109 qed
1111 context comm_monoid_mult
1112 begin
1114 lemma msetprod_empty:
1115   "msetprod {#} = 1"
1116   by (fact msetprod.empty)
1118 lemma msetprod_singleton:
1119   "msetprod {#x#} = x"
1120   by (fact msetprod.singleton)
1122 lemma msetprod_Un:
1123   "msetprod (A + B) = msetprod A * msetprod B"
1124   by (fact msetprod.union)
1126 lemma setprod_unfold_msetprod:
1127   "setprod f A = msetprod (image_mset f (multiset_of_set A))"
1128   by (cases "finite A") (induct A rule: finite_induct, simp_all)
1130 lemma msetprod_multiplicity:
1131   "msetprod M = setprod (\<lambda>x. x ^ count M x) (set_of M)"
1132   by (simp add: Multiset.fold_def setprod.eq_fold msetprod.eq_fold funpow_times_power comp_def)
1134 abbreviation msetprod_image :: "('b \<Rightarrow> 'a) \<Rightarrow> 'b multiset \<Rightarrow> 'a"
1135 where
1136   "msetprod_image f M \<equiv> msetprod (image_mset f M)"
1138 end
1140 syntax
1141   "_msetprod_image" :: "pttrn \<Rightarrow> 'b set \<Rightarrow> 'a \<Rightarrow> 'a::comm_monoid_mult"
1142       ("(3PROD _:#_. _)" [0, 51, 10] 10)
1144 syntax (xsymbols)
1145   "_msetprod_image" :: "pttrn \<Rightarrow> 'b set \<Rightarrow> 'a \<Rightarrow> 'a::comm_monoid_mult"
1146       ("(3\<Prod>_\<in>#_. _)" [0, 51, 10] 10)
1148 syntax (HTML output)
1149   "_msetprod_image" :: "pttrn \<Rightarrow> 'b set \<Rightarrow> 'a \<Rightarrow> 'a::comm_monoid_mult"
1150       ("(3\<Prod>_\<in>#_. _)" [0, 51, 10] 10)
1152 translations
1153   "PROD i :# A. b" == "CONST msetprod_image (\<lambda>i. b) A"
1155 lemma (in comm_semiring_1) dvd_msetprod:
1156   assumes "x \<in># A"
1157   shows "x dvd msetprod A"
1158 proof -
1159   from assms have "A = (A - {#x#}) + {#x#}" by simp
1160   then obtain B where "A = B + {#x#}" ..
1161   then show ?thesis by simp
1162 qed
1165 subsection {* Cardinality *}
1167 definition mcard :: "'a multiset \<Rightarrow> nat"
1168 where
1169   "mcard = msetsum \<circ> image_mset (\<lambda>_. 1)"
1171 lemma mcard_empty [simp]:
1172   "mcard {#} = 0"
1175 lemma mcard_singleton [simp]:
1176   "mcard {#a#} = Suc 0"
1179 lemma mcard_plus [simp]:
1180   "mcard (M + N) = mcard M + mcard N"
1183 lemma mcard_empty_iff [simp]:
1184   "mcard M = 0 \<longleftrightarrow> M = {#}"
1185   by (induct M) simp_all
1187 lemma mcard_unfold_setsum:
1188   "mcard M = setsum (count M) (set_of M)"
1189 proof (induct M)
1190   case empty then show ?case by simp
1191 next
1192   case (add M x) then show ?case
1193     by (cases "x \<in> set_of M")
1194       (simp_all del: mem_set_of_iff add: setsum.distrib setsum.delta' insert_absorb, simp)
1195 qed
1198 subsection {* Alternative representations *}
1200 subsubsection {* Lists *}
1202 context linorder
1203 begin
1205 lemma multiset_of_insort [simp]:
1206   "multiset_of (insort_key k x xs) = {#x#} + multiset_of xs"
1207   by (induct xs) (simp_all add: ac_simps)
1209 lemma multiset_of_sort [simp]:
1210   "multiset_of (sort_key k xs) = multiset_of xs"
1211   by (induct xs) (simp_all add: ac_simps)
1213 text {*
1214   This lemma shows which properties suffice to show that a function
1215   @{text "f"} with @{text "f xs = ys"} behaves like sort.
1216 *}
1218 lemma properties_for_sort_key:
1219   assumes "multiset_of ys = multiset_of xs"
1220   and "\<And>k. k \<in> set ys \<Longrightarrow> filter (\<lambda>x. f k = f x) ys = filter (\<lambda>x. f k = f x) xs"
1221   and "sorted (map f ys)"
1222   shows "sort_key f xs = ys"
1223 using assms
1224 proof (induct xs arbitrary: ys)
1225   case Nil then show ?case by simp
1226 next
1227   case (Cons x xs)
1228   from Cons.prems(2) have
1229     "\<forall>k \<in> set ys. filter (\<lambda>x. f k = f x) (remove1 x ys) = filter (\<lambda>x. f k = f x) xs"
1231   with Cons.prems have "sort_key f xs = remove1 x ys"
1232     by (auto intro!: Cons.hyps simp add: sorted_map_remove1)
1233   moreover from Cons.prems have "x \<in> set ys"
1234     by (auto simp add: mem_set_multiset_eq intro!: ccontr)
1235   ultimately show ?case using Cons.prems by (simp add: insort_key_remove1)
1236 qed
1238 lemma properties_for_sort:
1239   assumes multiset: "multiset_of ys = multiset_of xs"
1240   and "sorted ys"
1241   shows "sort xs = ys"
1242 proof (rule properties_for_sort_key)
1243   from multiset show "multiset_of ys = multiset_of xs" .
1244   from `sorted ys` show "sorted (map (\<lambda>x. x) ys)" by simp
1245   from multiset have "\<And>k. length (filter (\<lambda>y. k = y) ys) = length (filter (\<lambda>x. k = x) xs)"
1246     by (rule multiset_of_eq_length_filter)
1247   then have "\<And>k. replicate (length (filter (\<lambda>y. k = y) ys)) k = replicate (length (filter (\<lambda>x. k = x) xs)) k"
1248     by simp
1249   then show "\<And>k. k \<in> set ys \<Longrightarrow> filter (\<lambda>y. k = y) ys = filter (\<lambda>x. k = x) xs"
1251 qed
1253 lemma sort_key_by_quicksort:
1254   "sort_key f xs = sort_key f [x\<leftarrow>xs. f x < f (xs ! (length xs div 2))]
1255     @ [x\<leftarrow>xs. f x = f (xs ! (length xs div 2))]
1256     @ sort_key f [x\<leftarrow>xs. f x > f (xs ! (length xs div 2))]" (is "sort_key f ?lhs = ?rhs")
1257 proof (rule properties_for_sort_key)
1258   show "multiset_of ?rhs = multiset_of ?lhs"
1259     by (rule multiset_eqI) (auto simp add: multiset_of_filter)
1260 next
1261   show "sorted (map f ?rhs)"
1262     by (auto simp add: sorted_append intro: sorted_map_same)
1263 next
1264   fix l
1265   assume "l \<in> set ?rhs"
1266   let ?pivot = "f (xs ! (length xs div 2))"
1267   have *: "\<And>x. f l = f x \<longleftrightarrow> f x = f l" by auto
1268   have "[x \<leftarrow> sort_key f xs . f x = f l] = [x \<leftarrow> xs. f x = f l]"
1269     unfolding filter_sort by (rule properties_for_sort_key) (auto intro: sorted_map_same)
1270   with * have **: "[x \<leftarrow> sort_key f xs . f l = f x] = [x \<leftarrow> xs. f l = f x]" by simp
1271   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
1272   then have "\<And>P. [x \<leftarrow> sort_key f xs . P (f x) ?pivot \<and> f l = f x] =
1273     [x \<leftarrow> sort_key f xs. P (f l) ?pivot \<and> f l = f x]" by simp
1274   note *** = this [of "op <"] this [of "op >"] this [of "op ="]
1275   show "[x \<leftarrow> ?rhs. f l = f x] = [x \<leftarrow> ?lhs. f l = f x]"
1276   proof (cases "f l" ?pivot rule: linorder_cases)
1277     case less
1278     then have "f l \<noteq> ?pivot" and "\<not> f l > ?pivot" by auto
1279     with less show ?thesis
1280       by (simp add: filter_sort [symmetric] ** ***)
1281   next
1282     case equal then show ?thesis
1283       by (simp add: * less_le)
1284   next
1285     case greater
1286     then have "f l \<noteq> ?pivot" and "\<not> f l < ?pivot" by auto
1287     with greater show ?thesis
1288       by (simp add: filter_sort [symmetric] ** ***)
1289   qed
1290 qed
1292 lemma sort_by_quicksort:
1293   "sort xs = sort [x\<leftarrow>xs. x < xs ! (length xs div 2)]
1294     @ [x\<leftarrow>xs. x = xs ! (length xs div 2)]
1295     @ sort [x\<leftarrow>xs. x > xs ! (length xs div 2)]" (is "sort ?lhs = ?rhs")
1296   using sort_key_by_quicksort [of "\<lambda>x. x", symmetric] by simp
1298 text {* A stable parametrized quicksort *}
1300 definition part :: "('b \<Rightarrow> 'a) \<Rightarrow> 'a \<Rightarrow> 'b list \<Rightarrow> 'b list \<times> 'b list \<times> 'b list" where
1301   "part f pivot xs = ([x \<leftarrow> xs. f x < pivot], [x \<leftarrow> xs. f x = pivot], [x \<leftarrow> xs. pivot < f x])"
1303 lemma part_code [code]:
1304   "part f pivot [] = ([], [], [])"
1305   "part f pivot (x # xs) = (let (lts, eqs, gts) = part f pivot xs; x' = f x in
1306      if x' < pivot then (x # lts, eqs, gts)
1307      else if x' > pivot then (lts, eqs, x # gts)
1308      else (lts, x # eqs, gts))"
1309   by (auto simp add: part_def Let_def split_def)
1311 lemma sort_key_by_quicksort_code [code]:
1312   "sort_key f xs = (case xs of [] \<Rightarrow> []
1313     | [x] \<Rightarrow> xs
1314     | [x, y] \<Rightarrow> (if f x \<le> f y then xs else [y, x])
1315     | _ \<Rightarrow> (let (lts, eqs, gts) = part f (f (xs ! (length xs div 2))) xs
1316        in sort_key f lts @ eqs @ sort_key f gts))"
1317 proof (cases xs)
1318   case Nil then show ?thesis by simp
1319 next
1320   case (Cons _ ys) note hyps = Cons show ?thesis
1321   proof (cases ys)
1322     case Nil with hyps show ?thesis by simp
1323   next
1324     case (Cons _ zs) note hyps = hyps Cons show ?thesis
1325     proof (cases zs)
1326       case Nil with hyps show ?thesis by auto
1327     next
1328       case Cons
1329       from sort_key_by_quicksort [of f xs]
1330       have "sort_key f xs = (let (lts, eqs, gts) = part f (f (xs ! (length xs div 2))) xs
1331         in sort_key f lts @ eqs @ sort_key f gts)"
1332       by (simp only: split_def Let_def part_def fst_conv snd_conv)
1333       with hyps Cons show ?thesis by (simp only: list.cases)
1334     qed
1335   qed
1336 qed
1338 end
1340 hide_const (open) part
1342 lemma multiset_of_remdups_le: "multiset_of (remdups xs) \<le> multiset_of xs"
1343   by (induct xs) (auto intro: order_trans)
1345 lemma multiset_of_update:
1346   "i < length ls \<Longrightarrow> multiset_of (ls[i := v]) = multiset_of ls - {#ls ! i#} + {#v#}"
1347 proof (induct ls arbitrary: i)
1348   case Nil then show ?case by simp
1349 next
1350   case (Cons x xs)
1351   show ?case
1352   proof (cases i)
1353     case 0 then show ?thesis by simp
1354   next
1355     case (Suc i')
1356     with Cons show ?thesis
1357       apply simp
1359       apply (subst add_commute [of "{#v#}" "{#x#}"])
1361       apply simp
1362       apply (rule mset_le_multiset_union_diff_commute)
1363       apply (simp add: mset_le_single nth_mem_multiset_of)
1364       done
1365   qed
1366 qed
1368 lemma multiset_of_swap:
1369   "i < length ls \<Longrightarrow> j < length ls \<Longrightarrow>
1370     multiset_of (ls[j := ls ! i, i := ls ! j]) = multiset_of ls"
1371   by (cases "i = j") (simp_all add: multiset_of_update nth_mem_multiset_of)
1374 subsection {* The multiset order *}
1376 subsubsection {* Well-foundedness *}
1378 definition mult1 :: "('a \<times> 'a) set => ('a multiset \<times> 'a multiset) set" where
1379   "mult1 r = {(N, M). \<exists>a M0 K. M = M0 + {#a#} \<and> N = M0 + K \<and>
1380       (\<forall>b. b :# K --> (b, a) \<in> r)}"
1382 definition mult :: "('a \<times> 'a) set => ('a multiset \<times> 'a multiset) set" where
1383   "mult r = (mult1 r)\<^sup>+"
1385 lemma not_less_empty [iff]: "(M, {#}) \<notin> mult1 r"
1388 lemma less_add: "(N, M0 + {#a#}) \<in> mult1 r ==>
1389     (\<exists>M. (M, M0) \<in> mult1 r \<and> N = M + {#a#}) \<or>
1390     (\<exists>K. (\<forall>b. b :# K --> (b, a) \<in> r) \<and> N = M0 + K)"
1391   (is "_ \<Longrightarrow> ?case1 (mult1 r) \<or> ?case2")
1392 proof (unfold mult1_def)
1393   let ?r = "\<lambda>K a. \<forall>b. b :# K --> (b, a) \<in> r"
1394   let ?R = "\<lambda>N M. \<exists>a M0 K. M = M0 + {#a#} \<and> N = M0 + K \<and> ?r K a"
1395   let ?case1 = "?case1 {(N, M). ?R N M}"
1397   assume "(N, M0 + {#a#}) \<in> {(N, M). ?R N M}"
1398   then have "\<exists>a' M0' K.
1399       M0 + {#a#} = M0' + {#a'#} \<and> N = M0' + K \<and> ?r K a'" by simp
1400   then show "?case1 \<or> ?case2"
1401   proof (elim exE conjE)
1402     fix a' M0' K
1403     assume N: "N = M0' + K" and r: "?r K a'"
1404     assume "M0 + {#a#} = M0' + {#a'#}"
1405     then have "M0 = M0' \<and> a = a' \<or>
1406         (\<exists>K'. M0 = K' + {#a'#} \<and> M0' = K' + {#a#})"
1408     then show ?thesis
1409     proof (elim disjE conjE exE)
1410       assume "M0 = M0'" "a = a'"
1411       with N r have "?r K a \<and> N = M0 + K" by simp
1412       then have ?case2 .. then show ?thesis ..
1413     next
1414       fix K'
1415       assume "M0' = K' + {#a#}"
1416       with N have n: "N = K' + K + {#a#}" by (simp add: add_ac)
1418       assume "M0 = K' + {#a'#}"
1419       with r have "?R (K' + K) M0" by blast
1420       with n have ?case1 by simp then show ?thesis ..
1421     qed
1422   qed
1423 qed
1425 lemma all_accessible: "wf r ==> \<forall>M. M \<in> acc (mult1 r)"
1426 proof
1427   let ?R = "mult1 r"
1428   let ?W = "acc ?R"
1429   {
1430     fix M M0 a
1431     assume M0: "M0 \<in> ?W"
1432       and wf_hyp: "!!b. (b, a) \<in> r ==> (\<forall>M \<in> ?W. M + {#b#} \<in> ?W)"
1433       and acc_hyp: "\<forall>M. (M, M0) \<in> ?R --> M + {#a#} \<in> ?W"
1434     have "M0 + {#a#} \<in> ?W"
1435     proof (rule accI [of "M0 + {#a#}"])
1436       fix N
1437       assume "(N, M0 + {#a#}) \<in> ?R"
1438       then have "((\<exists>M. (M, M0) \<in> ?R \<and> N = M + {#a#}) \<or>
1439           (\<exists>K. (\<forall>b. b :# K --> (b, a) \<in> r) \<and> N = M0 + K))"
1441       then show "N \<in> ?W"
1442       proof (elim exE disjE conjE)
1443         fix M assume "(M, M0) \<in> ?R" and N: "N = M + {#a#}"
1444         from acc_hyp have "(M, M0) \<in> ?R --> M + {#a#} \<in> ?W" ..
1445         from this and `(M, M0) \<in> ?R` have "M + {#a#} \<in> ?W" ..
1446         then show "N \<in> ?W" by (simp only: N)
1447       next
1448         fix K
1449         assume N: "N = M0 + K"
1450         assume "\<forall>b. b :# K --> (b, a) \<in> r"
1451         then have "M0 + K \<in> ?W"
1452         proof (induct K)
1453           case empty
1454           from M0 show "M0 + {#} \<in> ?W" by simp
1455         next
1457           from add.prems have "(x, a) \<in> r" by simp
1458           with wf_hyp have "\<forall>M \<in> ?W. M + {#x#} \<in> ?W" by blast
1459           moreover from add have "M0 + K \<in> ?W" by simp
1460           ultimately have "(M0 + K) + {#x#} \<in> ?W" ..
1461           then show "M0 + (K + {#x#}) \<in> ?W" by (simp only: add_assoc)
1462         qed
1463         then show "N \<in> ?W" by (simp only: N)
1464       qed
1465     qed
1466   } note tedious_reasoning = this
1468   assume wf: "wf r"
1469   fix M
1470   show "M \<in> ?W"
1471   proof (induct M)
1472     show "{#} \<in> ?W"
1473     proof (rule accI)
1474       fix b assume "(b, {#}) \<in> ?R"
1475       with not_less_empty show "b \<in> ?W" by contradiction
1476     qed
1478     fix M a assume "M \<in> ?W"
1479     from wf have "\<forall>M \<in> ?W. M + {#a#} \<in> ?W"
1480     proof induct
1481       fix a
1482       assume r: "!!b. (b, a) \<in> r ==> (\<forall>M \<in> ?W. M + {#b#} \<in> ?W)"
1483       show "\<forall>M \<in> ?W. M + {#a#} \<in> ?W"
1484       proof
1485         fix M assume "M \<in> ?W"
1486         then show "M + {#a#} \<in> ?W"
1487           by (rule acc_induct) (rule tedious_reasoning [OF _ r])
1488       qed
1489     qed
1490     from this and `M \<in> ?W` show "M + {#a#} \<in> ?W" ..
1491   qed
1492 qed
1494 theorem wf_mult1: "wf r ==> wf (mult1 r)"
1495 by (rule acc_wfI) (rule all_accessible)
1497 theorem wf_mult: "wf r ==> wf (mult r)"
1498 unfolding mult_def by (rule wf_trancl) (rule wf_mult1)
1501 subsubsection {* Closure-free presentation *}
1503 text {* One direction. *}
1505 lemma mult_implies_one_step:
1506   "trans r ==> (M, N) \<in> mult r ==>
1507     \<exists>I J K. N = I + J \<and> M = I + K \<and> J \<noteq> {#} \<and>
1508     (\<forall>k \<in> set_of K. \<exists>j \<in> set_of J. (k, j) \<in> r)"
1509 apply (unfold mult_def mult1_def set_of_def)
1510 apply (erule converse_trancl_induct, clarify)
1511  apply (rule_tac x = M0 in exI, simp, clarify)
1512 apply (case_tac "a :# K")
1513  apply (rule_tac x = I in exI)
1514  apply (simp (no_asm))
1515  apply (rule_tac x = "(K - {#a#}) + Ka" in exI)
1517  apply (drule_tac f = "\<lambda>M. M - {#a#}" in arg_cong)
1519  apply (simp (no_asm_use) add: trans_def)
1520  apply blast
1521 apply (subgoal_tac "a :# I")
1522  apply (rule_tac x = "I - {#a#}" in exI)
1523  apply (rule_tac x = "J + {#a#}" in exI)
1524  apply (rule_tac x = "K + Ka" in exI)
1525  apply (rule conjI)
1526   apply (simp add: multiset_eq_iff split: nat_diff_split)
1527  apply (rule conjI)
1528   apply (drule_tac f = "\<lambda>M. M - {#a#}" in arg_cong, simp)
1529   apply (simp add: multiset_eq_iff split: nat_diff_split)
1530  apply (simp (no_asm_use) add: trans_def)
1531  apply blast
1532 apply (subgoal_tac "a :# (M0 + {#a#})")
1533  apply simp
1534 apply (simp (no_asm))
1535 done
1537 lemma one_step_implies_mult_aux:
1538   "trans r ==>
1539     \<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))
1540       --> (I + K, I + J) \<in> mult r"
1541 apply (induct_tac n, auto)
1542 apply (frule size_eq_Suc_imp_eq_union, clarify)
1543 apply (rename_tac "J'", simp)
1544 apply (erule notE, auto)
1545 apply (case_tac "J' = {#}")
1547  apply (rule r_into_trancl)
1548  apply (simp add: mult1_def set_of_def, blast)
1549 txt {* Now we know @{term "J' \<noteq> {#}"}. *}
1550 apply (cut_tac M = K and P = "\<lambda>x. (x, a) \<in> r" in multiset_partition)
1551 apply (erule_tac P = "\<forall>k \<in> set_of K. ?P k" in rev_mp)
1552 apply (erule ssubst)
1553 apply (simp add: Ball_def, auto)
1554 apply (subgoal_tac
1555   "((I + {# x :# K. (x, a) \<in> r #}) + {# x :# K. (x, a) \<notin> r #},
1556     (I + {# x :# K. (x, a) \<in> r #}) + J') \<in> mult r")
1557  prefer 2
1558  apply force
1560 apply (erule trancl_trans)
1561 apply (rule r_into_trancl)
1562 apply (simp add: mult1_def set_of_def)
1563 apply (rule_tac x = a in exI)
1564 apply (rule_tac x = "I + J'" in exI)
1566 done
1568 lemma one_step_implies_mult:
1569   "trans r ==> J \<noteq> {#} ==> \<forall>k \<in> set_of K. \<exists>j \<in> set_of J. (k, j) \<in> r
1570     ==> (I + K, I + J) \<in> mult r"
1571 using one_step_implies_mult_aux by blast
1574 subsubsection {* Partial-order properties *}
1576 definition less_multiset :: "'a\<Colon>order multiset \<Rightarrow> 'a multiset \<Rightarrow> bool" (infix "<#" 50) where
1577   "M' <# M \<longleftrightarrow> (M', M) \<in> mult {(x', x). x' < x}"
1579 definition le_multiset :: "'a\<Colon>order multiset \<Rightarrow> 'a multiset \<Rightarrow> bool" (infix "<=#" 50) where
1580   "M' <=# M \<longleftrightarrow> M' <# M \<or> M' = M"
1582 notation (xsymbols) less_multiset (infix "\<subset>#" 50)
1583 notation (xsymbols) le_multiset (infix "\<subseteq>#" 50)
1585 interpretation multiset_order: order le_multiset less_multiset
1586 proof -
1587   have irrefl: "\<And>M :: 'a multiset. \<not> M \<subset># M"
1588   proof
1589     fix M :: "'a multiset"
1590     assume "M \<subset># M"
1591     then have MM: "(M, M) \<in> mult {(x, y). x < y}" by (simp add: less_multiset_def)
1592     have "trans {(x'::'a, x). x' < x}"
1593       by (rule transI) simp
1594     moreover note MM
1595     ultimately have "\<exists>I J K. M = I + J \<and> M = I + K
1596       \<and> J \<noteq> {#} \<and> (\<forall>k\<in>set_of K. \<exists>j\<in>set_of J. (k, j) \<in> {(x, y). x < y})"
1597       by (rule mult_implies_one_step)
1598     then obtain I J K where "M = I + J" and "M = I + K"
1599       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
1600     then have aux1: "K \<noteq> {#}" and aux2: "\<forall>k\<in>set_of K. \<exists>j\<in>set_of K. k < j" by auto
1601     have "finite (set_of K)" by simp
1602     moreover note aux2
1603     ultimately have "set_of K = {}"
1604       by (induct rule: finite_induct) (auto intro: order_less_trans)
1605     with aux1 show False by simp
1606   qed
1607   have trans: "\<And>K M N :: 'a multiset. K \<subset># M \<Longrightarrow> M \<subset># N \<Longrightarrow> K \<subset># N"
1608     unfolding less_multiset_def mult_def by (blast intro: trancl_trans)
1609   show "class.order (le_multiset :: 'a multiset \<Rightarrow> _) less_multiset"
1610     by default (auto simp add: le_multiset_def irrefl dest: trans)
1611 qed
1613 lemma mult_less_irrefl [elim!]: "M \<subset># (M::'a::order multiset) ==> R"
1614   by simp
1617 subsubsection {* Monotonicity of multiset union *}
1619 lemma mult1_union: "(B, D) \<in> mult1 r ==> (C + B, C + D) \<in> mult1 r"
1620 apply (unfold mult1_def)
1621 apply auto
1622 apply (rule_tac x = a in exI)
1623 apply (rule_tac x = "C + M0" in exI)
1625 done
1627 lemma union_less_mono2: "B \<subset># D ==> C + B \<subset># C + (D::'a::order multiset)"
1628 apply (unfold less_multiset_def mult_def)
1629 apply (erule trancl_induct)
1630  apply (blast intro: mult1_union)
1631 apply (blast intro: mult1_union trancl_trans)
1632 done
1634 lemma union_less_mono1: "B \<subset># D ==> B + C \<subset># D + (C::'a::order multiset)"
1635 apply (subst add_commute [of B C])
1636 apply (subst add_commute [of D C])
1637 apply (erule union_less_mono2)
1638 done
1640 lemma union_less_mono:
1641   "A \<subset># C ==> B \<subset># D ==> A + B \<subset># C + (D::'a::order multiset)"
1642   by (blast intro!: union_less_mono1 union_less_mono2 multiset_order.less_trans)
1644 interpretation multiset_order: ordered_ab_semigroup_add plus le_multiset less_multiset
1645 proof
1646 qed (auto simp add: le_multiset_def intro: union_less_mono2)
1649 subsection {* Termination proofs with multiset orders *}
1651 lemma multi_member_skip: "x \<in># XS \<Longrightarrow> x \<in># {# y #} + XS"
1652   and multi_member_this: "x \<in># {# x #} + XS"
1653   and multi_member_last: "x \<in># {# x #}"
1654   by auto
1656 definition "ms_strict = mult pair_less"
1657 definition "ms_weak = ms_strict \<union> Id"
1659 lemma ms_reduction_pair: "reduction_pair (ms_strict, ms_weak)"
1660 unfolding reduction_pair_def ms_strict_def ms_weak_def pair_less_def
1661 by (auto intro: wf_mult1 wf_trancl simp: mult_def)
1663 lemma smsI:
1664   "(set_of A, set_of B) \<in> max_strict \<Longrightarrow> (Z + A, Z + B) \<in> ms_strict"
1665   unfolding ms_strict_def
1666 by (rule one_step_implies_mult) (auto simp add: max_strict_def pair_less_def elim!:max_ext.cases)
1668 lemma wmsI:
1669   "(set_of A, set_of B) \<in> max_strict \<or> A = {#} \<and> B = {#}
1670   \<Longrightarrow> (Z + A, Z + B) \<in> ms_weak"
1671 unfolding ms_weak_def ms_strict_def
1672 by (auto simp add: pair_less_def max_strict_def elim!:max_ext.cases intro: one_step_implies_mult)
1674 inductive pw_leq
1675 where
1676   pw_leq_empty: "pw_leq {#} {#}"
1677 | pw_leq_step:  "\<lbrakk>(x,y) \<in> pair_leq; pw_leq X Y \<rbrakk> \<Longrightarrow> pw_leq ({#x#} + X) ({#y#} + Y)"
1679 lemma pw_leq_lstep:
1680   "(x, y) \<in> pair_leq \<Longrightarrow> pw_leq {#x#} {#y#}"
1681 by (drule pw_leq_step) (rule pw_leq_empty, simp)
1683 lemma pw_leq_split:
1684   assumes "pw_leq X Y"
1685   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 = {#}))"
1686   using assms
1687 proof (induct)
1688   case pw_leq_empty thus ?case by auto
1689 next
1690   case (pw_leq_step x y X Y)
1691   then obtain A B Z where
1692     [simp]: "X = A + Z" "Y = B + Z"
1693       and 1[simp]: "(set_of A, set_of B) \<in> max_strict \<or> (B = {#} \<and> A = {#})"
1694     by auto
1695   from pw_leq_step have "x = y \<or> (x, y) \<in> pair_less"
1696     unfolding pair_leq_def by auto
1697   thus ?case
1698   proof
1699     assume [simp]: "x = y"
1700     have
1701       "{#x#} + X = A + ({#y#}+Z)
1702       \<and> {#y#} + Y = B + ({#y#}+Z)
1703       \<and> ((set_of A, set_of B) \<in> max_strict \<or> (B = {#} \<and> A = {#}))"
1705     thus ?case by (intro exI)
1706   next
1707     assume A: "(x, y) \<in> pair_less"
1708     let ?A' = "{#x#} + A" and ?B' = "{#y#} + B"
1709     have "{#x#} + X = ?A' + Z"
1710       "{#y#} + Y = ?B' + Z"
1712     moreover have
1713       "(set_of ?A', set_of ?B') \<in> max_strict"
1714       using 1 A unfolding max_strict_def
1715       by (auto elim!: max_ext.cases)
1716     ultimately show ?thesis by blast
1717   qed
1718 qed
1720 lemma
1721   assumes pwleq: "pw_leq Z Z'"
1722   shows ms_strictI: "(set_of A, set_of B) \<in> max_strict \<Longrightarrow> (Z + A, Z' + B) \<in> ms_strict"
1723   and   ms_weakI1:  "(set_of A, set_of B) \<in> max_strict \<Longrightarrow> (Z + A, Z' + B) \<in> ms_weak"
1724   and   ms_weakI2:  "(Z + {#}, Z' + {#}) \<in> ms_weak"
1725 proof -
1726   from pw_leq_split[OF pwleq]
1727   obtain A' B' Z''
1728     where [simp]: "Z = A' + Z''" "Z' = B' + Z''"
1729     and mx_or_empty: "(set_of A', set_of B') \<in> max_strict \<or> (A' = {#} \<and> B' = {#})"
1730     by blast
1731   {
1732     assume max: "(set_of A, set_of B) \<in> max_strict"
1733     from mx_or_empty
1734     have "(Z'' + (A + A'), Z'' + (B + B')) \<in> ms_strict"
1735     proof
1736       assume max': "(set_of A', set_of B') \<in> max_strict"
1737       with max have "(set_of (A + A'), set_of (B + B')) \<in> max_strict"
1738         by (auto simp: max_strict_def intro: max_ext_additive)
1739       thus ?thesis by (rule smsI)
1740     next
1741       assume [simp]: "A' = {#} \<and> B' = {#}"
1742       show ?thesis by (rule smsI) (auto intro: max)
1743     qed
1744     thus "(Z + A, Z' + B) \<in> ms_strict" by (simp add:add_ac)
1745     thus "(Z + A, Z' + B) \<in> ms_weak" by (simp add: ms_weak_def)
1746   }
1747   from mx_or_empty
1748   have "(Z'' + A', Z'' + B') \<in> ms_weak" by (rule wmsI)
1749   thus "(Z + {#}, Z' + {#}) \<in> ms_weak" by (simp add:add_ac)
1750 qed
1752 lemma empty_neutral: "{#} + x = x" "x + {#} = x"
1753 and nonempty_plus: "{# x #} + rs \<noteq> {#}"
1754 and nonempty_single: "{# x #} \<noteq> {#}"
1755 by auto
1757 setup {*
1758 let
1759   fun msetT T = Type (@{type_name multiset}, [T]);
1761   fun mk_mset T [] = Const (@{const_abbrev Mempty}, msetT T)
1762     | mk_mset T [x] = Const (@{const_name single}, T --> msetT T) \$ x
1763     | mk_mset T (x :: xs) =
1764           Const (@{const_name plus}, msetT T --> msetT T --> msetT T) \$
1765                 mk_mset T [x] \$ mk_mset T xs
1767   fun mset_member_tac m i =
1768       (if m <= 0 then
1769            rtac @{thm multi_member_this} i ORELSE rtac @{thm multi_member_last} i
1770        else
1771            rtac @{thm multi_member_skip} i THEN mset_member_tac (m - 1) i)
1773   val mset_nonempty_tac =
1774       rtac @{thm nonempty_plus} ORELSE' rtac @{thm nonempty_single}
1776   val regroup_munion_conv =
1777       Function_Lib.regroup_conv @{const_abbrev Mempty} @{const_name plus}
1778         (map (fn t => t RS eq_reflection) (@{thms add_ac} @ @{thms empty_neutral}))
1780   fun unfold_pwleq_tac i =
1781     (rtac @{thm pw_leq_step} i THEN (fn st => unfold_pwleq_tac (i + 1) st))
1782       ORELSE (rtac @{thm pw_leq_lstep} i)
1783       ORELSE (rtac @{thm pw_leq_empty} i)
1785   val set_of_simps = [@{thm set_of_empty}, @{thm set_of_single}, @{thm set_of_union},
1786                       @{thm Un_insert_left}, @{thm Un_empty_left}]
1787 in
1788   ScnpReconstruct.multiset_setup (ScnpReconstruct.Multiset
1789   {
1790     msetT=msetT, mk_mset=mk_mset, mset_regroup_conv=regroup_munion_conv,
1791     mset_member_tac=mset_member_tac, mset_nonempty_tac=mset_nonempty_tac,
1792     mset_pwleq_tac=unfold_pwleq_tac, set_of_simps=set_of_simps,
1793     smsI'= @{thm ms_strictI}, wmsI2''= @{thm ms_weakI2}, wmsI1= @{thm ms_weakI1},
1794     reduction_pair= @{thm ms_reduction_pair}
1795   })
1796 end
1797 *}
1800 subsection {* Legacy theorem bindings *}
1802 lemmas multi_count_eq = multiset_eq_iff [symmetric]
1804 lemma union_commute: "M + N = N + (M::'a multiset)"
1807 lemma union_assoc: "(M + N) + K = M + (N + (K::'a multiset))"
1810 lemma union_lcomm: "M + (N + K) = N + (M + (K::'a multiset))"
1813 lemmas union_ac = union_assoc union_commute union_lcomm
1815 lemma union_right_cancel: "M + K = N + K \<longleftrightarrow> M = (N::'a multiset)"
1818 lemma union_left_cancel: "K + M = K + N \<longleftrightarrow> M = (N::'a multiset)"
1821 lemma multi_union_self_other_eq: "(A::'a multiset) + X = A + Y \<Longrightarrow> X = Y"
1824 lemma mset_less_trans: "(M::'a multiset) < K \<Longrightarrow> K < N \<Longrightarrow> M < N"
1825   by (fact order_less_trans)
1827 lemma multiset_inter_commute: "A #\<inter> B = B #\<inter> A"
1828   by (fact inf.commute)
1830 lemma multiset_inter_assoc: "A #\<inter> (B #\<inter> C) = A #\<inter> B #\<inter> C"
1831   by (fact inf.assoc [symmetric])
1833 lemma multiset_inter_left_commute: "A #\<inter> (B #\<inter> C) = B #\<inter> (A #\<inter> C)"
1834   by (fact inf.left_commute)
1836 lemmas multiset_inter_ac =
1837   multiset_inter_commute
1838   multiset_inter_assoc
1839   multiset_inter_left_commute
1841 lemma mult_less_not_refl:
1842   "\<not> M \<subset># (M::'a::order multiset)"
1843   by (fact multiset_order.less_irrefl)
1845 lemma mult_less_trans:
1846   "K \<subset># M ==> M \<subset># N ==> K \<subset># (N::'a::order multiset)"
1847   by (fact multiset_order.less_trans)
1849 lemma mult_less_not_sym:
1850   "M \<subset># N ==> \<not> N \<subset># (M::'a::order multiset)"
1851   by (fact multiset_order.less_not_sym)
1853 lemma mult_less_asym:
1854   "M \<subset># N ==> (\<not> P ==> N \<subset># (M::'a::order multiset)) ==> P"
1855   by (fact multiset_order.less_asym)
1857 ML {*
1858 fun multiset_postproc _ maybe_name all_values (T as Type (_, [elem_T]))
1859                       (Const _ \$ t') =
1860     let
1861       val (maybe_opt, ps) =
1862         Nitpick_Model.dest_plain_fun t' ||> op ~~
1863         ||> map (apsnd (snd o HOLogic.dest_number))
1864       fun elems_for t =
1865         case AList.lookup (op =) ps t of
1866           SOME n => replicate n t
1867         | NONE => [Const (maybe_name, elem_T --> elem_T) \$ t]
1868     in
1869       case maps elems_for (all_values elem_T) @
1870            (if maybe_opt then [Const (Nitpick_Model.unrep (), elem_T)]
1871             else []) of
1872         [] => Const (@{const_name zero_class.zero}, T)
1873       | ts => foldl1 (fn (t1, t2) =>
1874                          Const (@{const_name plus_class.plus}, T --> T --> T)
1875                          \$ t1 \$ t2)
1876                      (map (curry (op \$) (Const (@{const_name single},
1877                                                 elem_T --> T))) ts)
1878     end
1879   | multiset_postproc _ _ _ _ t = t
1880 *}
1882 declaration {*
1883 Nitpick_Model.register_term_postprocessor @{typ "'a multiset"}
1884     multiset_postproc
1885 *}
1887 hide_const (open) fold
1889 end