src/HOL/Library/Multiset.thy
 author blanchet Fri Aug 22 17:35:48 2014 +0200 (2014-08-22) changeset 58035 177eeda93a8c parent 57966 6fab7e95587d child 58098 ff478d85129b permissions -rw-r--r--
added lemmas contributed by Rene Thiemann
1 (*  Title:      HOL/Library/Multiset.thy
2     Author:     Tobias Nipkow, Markus Wenzel, Lawrence C Paulson, Norbert Voelker
3     Author:     Andrei Popescu, TU Muenchen
4 *)
6 header {* (Finite) multisets *}
8 theory Multiset
9 imports Main
10 begin
12 subsection {* The type of multisets *}
14 definition "multiset = {f :: 'a => nat. finite {x. f x > 0}}"
16 typedef 'a multiset = "multiset :: ('a => nat) set"
17   morphisms count Abs_multiset
18   unfolding multiset_def
19 proof
20   show "(\<lambda>x. 0::nat) \<in> {f. finite {x. f x > 0}}" by simp
21 qed
23 setup_lifting type_definition_multiset
25 abbreviation Melem :: "'a => 'a multiset => bool"  ("(_/ :# _)" [50, 51] 50) where
26   "a :# M == 0 < count M a"
28 notation (xsymbols)
29   Melem (infix "\<in>#" 50)
31 lemma multiset_eq_iff:
32   "M = N \<longleftrightarrow> (\<forall>a. count M a = count N a)"
33   by (simp only: count_inject [symmetric] fun_eq_iff)
35 lemma multiset_eqI:
36   "(\<And>x. count A x = count B x) \<Longrightarrow> A = B"
37   using multiset_eq_iff by auto
39 text {*
40  \medskip Preservation of the representing set @{term multiset}.
41 *}
43 lemma const0_in_multiset:
44   "(\<lambda>a. 0) \<in> multiset"
45   by (simp add: multiset_def)
47 lemma only1_in_multiset:
48   "(\<lambda>b. if b = a then n else 0) \<in> multiset"
49   by (simp add: multiset_def)
51 lemma union_preserves_multiset:
52   "M \<in> multiset \<Longrightarrow> N \<in> multiset \<Longrightarrow> (\<lambda>a. M a + N a) \<in> multiset"
53   by (simp add: multiset_def)
55 lemma diff_preserves_multiset:
56   assumes "M \<in> multiset"
57   shows "(\<lambda>a. M a - N a) \<in> multiset"
58 proof -
59   have "{x. N x < M x} \<subseteq> {x. 0 < M x}"
60     by auto
61   with assms show ?thesis
62     by (auto simp add: multiset_def intro: finite_subset)
63 qed
65 lemma filter_preserves_multiset:
66   assumes "M \<in> multiset"
67   shows "(\<lambda>x. if P x then M x else 0) \<in> multiset"
68 proof -
69   have "{x. (P x \<longrightarrow> 0 < M x) \<and> P x} \<subseteq> {x. 0 < M x}"
70     by auto
71   with assms show ?thesis
72     by (auto simp add: multiset_def intro: finite_subset)
73 qed
75 lemmas in_multiset = const0_in_multiset only1_in_multiset
76   union_preserves_multiset diff_preserves_multiset filter_preserves_multiset
79 subsection {* Representing multisets *}
81 text {* Multiset enumeration *}
83 instantiation multiset :: (type) cancel_comm_monoid_add
84 begin
86 lift_definition zero_multiset :: "'a multiset" is "\<lambda>a. 0"
87 by (rule const0_in_multiset)
89 abbreviation Mempty :: "'a multiset" ("{#}") where
90   "Mempty \<equiv> 0"
92 lift_definition plus_multiset :: "'a multiset => 'a multiset => 'a multiset" is "\<lambda>M N. (\<lambda>a. M a + N a)"
93 by (rule union_preserves_multiset)
95 instance
96 by default (transfer, simp add: fun_eq_iff)+
98 end
100 lift_definition single :: "'a => 'a multiset" is "\<lambda>a b. if b = a then 1 else 0"
101 by (rule only1_in_multiset)
103 syntax
104   "_multiset" :: "args => 'a multiset"    ("{#(_)#}")
105 translations
106   "{#x, xs#}" == "{#x#} + {#xs#}"
107   "{#x#}" == "CONST single x"
109 lemma count_empty [simp]: "count {#} a = 0"
110   by (simp add: zero_multiset.rep_eq)
112 lemma count_single [simp]: "count {#b#} a = (if b = a then 1 else 0)"
113   by (simp add: single.rep_eq)
116 subsection {* Basic operations *}
118 subsubsection {* Union *}
120 lemma count_union [simp]: "count (M + N) a = count M a + count N a"
121   by (simp add: plus_multiset.rep_eq)
124 subsubsection {* Difference *}
126 instantiation multiset :: (type) comm_monoid_diff
127 begin
129 lift_definition minus_multiset :: "'a multiset => 'a multiset => 'a multiset" is "\<lambda> M N. \<lambda>a. M a - N a"
130 by (rule diff_preserves_multiset)
132 instance
133 by default (transfer, simp add: fun_eq_iff)+
135 end
137 lemma count_diff [simp]: "count (M - N) a = count M a - count N a"
138   by (simp add: minus_multiset.rep_eq)
140 lemma diff_empty [simp]: "M - {#} = M \<and> {#} - M = {#}"
141   by rule (fact Groups.diff_zero, fact Groups.zero_diff)
143 lemma diff_cancel[simp]: "A - A = {#}"
144   by (fact Groups.diff_cancel)
146 lemma diff_union_cancelR [simp]: "M + N - N = (M::'a multiset)"
147   by (fact add_diff_cancel_right')
149 lemma diff_union_cancelL [simp]: "N + M - N = (M::'a multiset)"
150   by (fact add_diff_cancel_left')
152 lemma diff_right_commute:
153   "(M::'a multiset) - N - Q = M - Q - N"
154   by (fact diff_right_commute)
157   "(M::'a multiset) - (N + Q) = M - N - Q"
158   by (rule sym) (fact diff_diff_add)
160 lemma insert_DiffM:
161   "x \<in># M \<Longrightarrow> {#x#} + (M - {#x#}) = M"
162   by (clarsimp simp: multiset_eq_iff)
164 lemma insert_DiffM2 [simp]:
165   "x \<in># M \<Longrightarrow> M - {#x#} + {#x#} = M"
166   by (clarsimp simp: multiset_eq_iff)
168 lemma diff_union_swap:
169   "a \<noteq> b \<Longrightarrow> M - {#a#} + {#b#} = M + {#b#} - {#a#}"
170   by (auto simp add: multiset_eq_iff)
172 lemma diff_union_single_conv:
173   "a \<in># J \<Longrightarrow> I + J - {#a#} = I + (J - {#a#})"
174   by (simp add: multiset_eq_iff)
177 subsubsection {* Equality of multisets *}
179 lemma single_not_empty [simp]: "{#a#} \<noteq> {#} \<and> {#} \<noteq> {#a#}"
180   by (simp add: multiset_eq_iff)
182 lemma single_eq_single [simp]: "{#a#} = {#b#} \<longleftrightarrow> a = b"
183   by (auto simp add: multiset_eq_iff)
185 lemma union_eq_empty [iff]: "M + N = {#} \<longleftrightarrow> M = {#} \<and> N = {#}"
186   by (auto simp add: multiset_eq_iff)
188 lemma empty_eq_union [iff]: "{#} = M + N \<longleftrightarrow> M = {#} \<and> N = {#}"
189   by (auto simp add: multiset_eq_iff)
191 lemma multi_self_add_other_not_self [simp]: "M = M + {#x#} \<longleftrightarrow> False"
192   by (auto simp add: multiset_eq_iff)
194 lemma diff_single_trivial:
195   "\<not> x \<in># M \<Longrightarrow> M - {#x#} = M"
196   by (auto simp add: multiset_eq_iff)
198 lemma diff_single_eq_union:
199   "x \<in># M \<Longrightarrow> M - {#x#} = N \<longleftrightarrow> M = N + {#x#}"
200   by auto
202 lemma union_single_eq_diff:
203   "M + {#x#} = N \<Longrightarrow> M = N - {#x#}"
204   by (auto dest: sym)
206 lemma union_single_eq_member:
207   "M + {#x#} = N \<Longrightarrow> x \<in># N"
208   by auto
210 lemma union_is_single:
211   "M + N = {#a#} \<longleftrightarrow> M = {#a#} \<and> N={#} \<or> M = {#} \<and> N = {#a#}" (is "?lhs = ?rhs")
212 proof
213   assume ?rhs then show ?lhs by auto
214 next
215   assume ?lhs then show ?rhs
216     by (simp add: multiset_eq_iff split:if_splits) (metis add_is_1)
217 qed
219 lemma single_is_union:
220   "{#a#} = M + N \<longleftrightarrow> {#a#} = M \<and> N = {#} \<or> M = {#} \<and> {#a#} = N"
221   by (auto simp add: eq_commute [of "{#a#}" "M + N"] union_is_single)
224   "M + {#a#} = N + {#b#} \<longleftrightarrow> M = N \<and> a = b \<or> M = N - {#a#} + {#b#} \<and> N = M - {#b#} + {#a#}"  (is "?lhs = ?rhs")
225 (* shorter: by (simp add: multiset_eq_iff) fastforce *)
226 proof
227   assume ?rhs then show ?lhs
229     (drule sym, simp add: add.assoc [symmetric])
230 next
231   assume ?lhs
232   show ?rhs
233   proof (cases "a = b")
234     case True with `?lhs` show ?thesis by simp
235   next
236     case False
237     from `?lhs` have "a \<in># N + {#b#}" by (rule union_single_eq_member)
238     with False have "a \<in># N" by auto
239     moreover from `?lhs` have "M = N + {#b#} - {#a#}" by (rule union_single_eq_diff)
240     moreover note False
241     ultimately show ?thesis by (auto simp add: diff_right_commute [of _ "{#a#}"] diff_union_swap)
242   qed
243 qed
245 lemma insert_noteq_member:
246   assumes BC: "B + {#b#} = C + {#c#}"
247    and bnotc: "b \<noteq> c"
248   shows "c \<in># B"
249 proof -
250   have "c \<in># C + {#c#}" by simp
251   have nc: "\<not> c \<in># {#b#}" using bnotc by simp
252   then have "c \<in># B + {#b#}" using BC by simp
253   then show "c \<in># B" using nc by simp
254 qed
257   "(M + {#a#} = N + {#b#}) =
258     (M = N \<and> a = b \<or> (\<exists>K. M = K + {#b#} \<and> N = K + {#a#}))"
261 lemma multi_member_split:
262   "x \<in># M \<Longrightarrow> \<exists>A. M = A + {#x#}"
263   by (rule_tac x = "M - {#x#}" in exI, simp)
266 subsubsection {* Pointwise ordering induced by count *}
268 instantiation multiset :: (type) ordered_ab_semigroup_add_imp_le
269 begin
271 lift_definition less_eq_multiset :: "'a multiset \<Rightarrow> 'a multiset \<Rightarrow> bool" is "\<lambda> A B. (\<forall>a. A a \<le> B a)" .
273 lemmas mset_le_def = less_eq_multiset_def
275 definition less_multiset :: "'a multiset \<Rightarrow> 'a multiset \<Rightarrow> bool" where
276   mset_less_def: "(A::'a multiset) < B \<longleftrightarrow> A \<le> B \<and> A \<noteq> B"
278 instance
279   by default (auto simp add: mset_le_def mset_less_def multiset_eq_iff intro: order_trans antisym)
281 end
283 lemma mset_less_eqI:
284   "(\<And>x. count A x \<le> count B x) \<Longrightarrow> A \<le> B"
285   by (simp add: mset_le_def)
287 lemma mset_le_exists_conv:
288   "(A::'a multiset) \<le> B \<longleftrightarrow> (\<exists>C. B = A + C)"
289 apply (unfold mset_le_def, rule iffI, rule_tac x = "B - A" in exI)
290 apply (auto intro: multiset_eq_iff [THEN iffD2])
291 done
293 instance multiset :: (type) ordered_cancel_comm_monoid_diff
294   by default (simp, fact mset_le_exists_conv)
296 lemma mset_le_mono_add_right_cancel [simp]:
297   "(A::'a multiset) + C \<le> B + C \<longleftrightarrow> A \<le> B"
298   by (fact add_le_cancel_right)
300 lemma mset_le_mono_add_left_cancel [simp]:
301   "C + (A::'a multiset) \<le> C + B \<longleftrightarrow> A \<le> B"
302   by (fact add_le_cancel_left)
305   "(A::'a multiset) \<le> B \<Longrightarrow> C \<le> D \<Longrightarrow> A + C \<le> B + D"
306   by (fact add_mono)
308 lemma mset_le_add_left [simp]:
309   "(A::'a multiset) \<le> A + B"
310   unfolding mset_le_def by auto
312 lemma mset_le_add_right [simp]:
313   "B \<le> (A::'a multiset) + B"
314   unfolding mset_le_def by auto
316 lemma mset_le_single:
317   "a :# B \<Longrightarrow> {#a#} \<le> B"
318   by (simp add: mset_le_def)
320 lemma multiset_diff_union_assoc:
321   "C \<le> B \<Longrightarrow> (A::'a multiset) + B - C = A + (B - C)"
322   by (simp add: multiset_eq_iff mset_le_def)
324 lemma mset_le_multiset_union_diff_commute:
325   "B \<le> A \<Longrightarrow> (A::'a multiset) - B + C = A + C - B"
326 by (simp add: multiset_eq_iff mset_le_def)
328 lemma diff_le_self[simp]: "(M::'a multiset) - N \<le> M"
329 by(simp add: mset_le_def)
331 lemma mset_lessD: "A < B \<Longrightarrow> x \<in># A \<Longrightarrow> x \<in># B"
332 apply (clarsimp simp: mset_le_def mset_less_def)
333 apply (erule_tac x=x in allE)
334 apply auto
335 done
337 lemma mset_leD: "A \<le> B \<Longrightarrow> x \<in># A \<Longrightarrow> x \<in># B"
338 apply (clarsimp simp: mset_le_def mset_less_def)
339 apply (erule_tac x = x in allE)
340 apply auto
341 done
343 lemma mset_less_insertD: "(A + {#x#} < B) \<Longrightarrow> (x \<in># B \<and> A < B)"
344 apply (rule conjI)
345  apply (simp add: mset_lessD)
346 apply (clarsimp simp: mset_le_def mset_less_def)
347 apply safe
348  apply (erule_tac x = a in allE)
349  apply (auto split: split_if_asm)
350 done
352 lemma mset_le_insertD: "(A + {#x#} \<le> B) \<Longrightarrow> (x \<in># B \<and> A \<le> B)"
353 apply (rule conjI)
354  apply (simp add: mset_leD)
355 apply (force simp: mset_le_def mset_less_def split: split_if_asm)
356 done
358 lemma mset_less_of_empty[simp]: "A < {#} \<longleftrightarrow> False"
359   by (auto simp add: mset_less_def mset_le_def multiset_eq_iff)
361 lemma empty_le[simp]: "{#} \<le> A"
362   unfolding mset_le_exists_conv by auto
364 lemma le_empty[simp]: "(M \<le> {#}) = (M = {#})"
365   unfolding mset_le_exists_conv by auto
367 lemma multi_psub_of_add_self[simp]: "A < A + {#x#}"
368   by (auto simp: mset_le_def mset_less_def)
370 lemma multi_psub_self[simp]: "(A::'a multiset) < A = False"
371   by simp
374   "T + {#x#} < S + {#x#} \<Longrightarrow> T < S"
375   by (fact add_less_imp_less_right)
377 lemma mset_less_empty_nonempty:
378   "{#} < S \<longleftrightarrow> S \<noteq> {#}"
379   by (auto simp: mset_le_def mset_less_def)
381 lemma mset_less_diff_self:
382   "c \<in># B \<Longrightarrow> B - {#c#} < B"
383   by (auto simp: mset_le_def mset_less_def multiset_eq_iff)
386 subsubsection {* Intersection *}
388 instantiation multiset :: (type) semilattice_inf
389 begin
391 definition inf_multiset :: "'a multiset \<Rightarrow> 'a multiset \<Rightarrow> 'a multiset" where
392   multiset_inter_def: "inf_multiset A B = A - (A - B)"
394 instance
395 proof -
396   have aux: "\<And>m n q :: nat. m \<le> n \<Longrightarrow> m \<le> q \<Longrightarrow> m \<le> n - (n - q)" by arith
397   show "OFCLASS('a multiset, semilattice_inf_class)"
398     by default (auto simp add: multiset_inter_def mset_le_def aux)
399 qed
401 end
403 abbreviation multiset_inter :: "'a multiset \<Rightarrow> 'a multiset \<Rightarrow> 'a multiset" (infixl "#\<inter>" 70) where
404   "multiset_inter \<equiv> inf"
406 lemma multiset_inter_count [simp]:
407   "count (A #\<inter> B) x = min (count A x) (count B x)"
408   by (simp add: multiset_inter_def)
410 lemma multiset_inter_single: "a \<noteq> b \<Longrightarrow> {#a#} #\<inter> {#b#} = {#}"
411   by (rule multiset_eqI) auto
413 lemma multiset_union_diff_commute:
414   assumes "B #\<inter> C = {#}"
415   shows "A + B - C = A - C + B"
416 proof (rule multiset_eqI)
417   fix x
418   from assms have "min (count B x) (count C x) = 0"
419     by (auto simp add: multiset_eq_iff)
420   then have "count B x = 0 \<or> count C x = 0"
421     by auto
422   then show "count (A + B - C) x = count (A - C + B) x"
423     by auto
424 qed
426 lemma empty_inter [simp]:
427   "{#} #\<inter> M = {#}"
428   by (simp add: multiset_eq_iff)
430 lemma inter_empty [simp]:
431   "M #\<inter> {#} = {#}"
432   by (simp add: multiset_eq_iff)
435   "\<not> x \<in># N \<Longrightarrow> (M + {#x#}) #\<inter> N = M #\<inter> N"
436   by (simp add: multiset_eq_iff)
439   "x \<in># N \<Longrightarrow> (M + {#x#}) #\<inter> N = (M #\<inter> (N - {#x#})) + {#x#}"
440   by (simp add: multiset_eq_iff)
443   "\<not> x \<in># N \<Longrightarrow> N #\<inter> (M + {#x#}) = N #\<inter> M"
444   by (simp add: multiset_eq_iff)
447   "x \<in># N \<Longrightarrow> N #\<inter> (M + {#x#}) = ((N - {#x#}) #\<inter> M) + {#x#}"
448   by (simp add: multiset_eq_iff)
451 subsubsection {* Bounded union *}
453 instantiation multiset :: (type) semilattice_sup
454 begin
456 definition sup_multiset :: "'a multiset \<Rightarrow> 'a multiset \<Rightarrow> 'a multiset" where
457   "sup_multiset A B = A + (B - A)"
459 instance
460 proof -
461   have aux: "\<And>m n q :: nat. m \<le> n \<Longrightarrow> q \<le> n \<Longrightarrow> m + (q - m) \<le> n" by arith
462   show "OFCLASS('a multiset, semilattice_sup_class)"
463     by default (auto simp add: sup_multiset_def mset_le_def aux)
464 qed
466 end
468 abbreviation sup_multiset :: "'a multiset \<Rightarrow> 'a multiset \<Rightarrow> 'a multiset" (infixl "#\<union>" 70) where
469   "sup_multiset \<equiv> sup"
471 lemma sup_multiset_count [simp]:
472   "count (A #\<union> B) x = max (count A x) (count B x)"
473   by (simp add: sup_multiset_def)
475 lemma empty_sup [simp]:
476   "{#} #\<union> M = M"
477   by (simp add: multiset_eq_iff)
479 lemma sup_empty [simp]:
480   "M #\<union> {#} = M"
481   by (simp add: multiset_eq_iff)
484   "\<not> x \<in># N \<Longrightarrow> (M + {#x#}) #\<union> N = (M #\<union> N) + {#x#}"
485   by (simp add: multiset_eq_iff)
488   "x \<in># N \<Longrightarrow> (M + {#x#}) #\<union> N = (M #\<union> (N - {#x#})) + {#x#}"
489   by (simp add: multiset_eq_iff)
492   "\<not> x \<in># N \<Longrightarrow> N #\<union> (M + {#x#}) = (N #\<union> M) + {#x#}"
493   by (simp add: multiset_eq_iff)
496   "x \<in># N \<Longrightarrow> N #\<union> (M + {#x#}) = ((N - {#x#}) #\<union> M) + {#x#}"
497   by (simp add: multiset_eq_iff)
500 subsubsection {* Filter (with comprehension syntax) *}
502 text {* Multiset comprehension *}
504 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"
505 by (rule filter_preserves_multiset)
507 hide_const (open) filter
509 lemma count_filter [simp]:
510   "count (Multiset.filter P M) a = (if P a then count M a else 0)"
511   by (simp add: filter.rep_eq)
513 lemma filter_empty [simp]:
514   "Multiset.filter P {#} = {#}"
515   by (rule multiset_eqI) simp
517 lemma filter_single [simp]:
518   "Multiset.filter P {#x#} = (if P x then {#x#} else {#})"
519   by (rule multiset_eqI) simp
521 lemma filter_union [simp]:
522   "Multiset.filter P (M + N) = Multiset.filter P M + Multiset.filter P N"
523   by (rule multiset_eqI) simp
525 lemma filter_diff [simp]:
526   "Multiset.filter P (M - N) = Multiset.filter P M - Multiset.filter P N"
527   by (rule multiset_eqI) simp
529 lemma filter_inter [simp]:
530   "Multiset.filter P (M #\<inter> N) = Multiset.filter P M #\<inter> Multiset.filter P N"
531   by (rule multiset_eqI) simp
533 lemma multiset_filter_subset[simp]: "Multiset.filter f M \<le> M"
534   unfolding less_eq_multiset.rep_eq by auto
536 lemma multiset_filter_mono: assumes "A \<le> B"
537   shows "Multiset.filter f A \<le> Multiset.filter f B"
538 proof -
539   from assms[unfolded mset_le_exists_conv]
540   obtain C where B: "B = A + C" by auto
541   show ?thesis unfolding B by auto
542 qed
544 syntax
545   "_MCollect" :: "pttrn \<Rightarrow> 'a multiset \<Rightarrow> bool \<Rightarrow> 'a multiset"    ("(1{# _ :# _./ _#})")
546 syntax (xsymbol)
547   "_MCollect" :: "pttrn \<Rightarrow> 'a multiset \<Rightarrow> bool \<Rightarrow> 'a multiset"    ("(1{# _ \<in># _./ _#})")
548 translations
549   "{#x \<in># M. P#}" == "CONST Multiset.filter (\<lambda>x. P) M"
552 subsubsection {* Set of elements *}
554 definition set_of :: "'a multiset => 'a set" where
555   "set_of M = {x. x :# M}"
557 lemma set_of_empty [simp]: "set_of {#} = {}"
558 by (simp add: set_of_def)
560 lemma set_of_single [simp]: "set_of {#b#} = {b}"
561 by (simp add: set_of_def)
563 lemma set_of_union [simp]: "set_of (M + N) = set_of M \<union> set_of N"
564 by (auto simp add: set_of_def)
566 lemma set_of_eq_empty_iff [simp]: "(set_of M = {}) = (M = {#})"
567 by (auto simp add: set_of_def multiset_eq_iff)
569 lemma mem_set_of_iff [simp]: "(x \<in> set_of M) = (x :# M)"
570 by (auto simp add: set_of_def)
572 lemma set_of_filter [simp]: "set_of {# x:#M. P x #} = set_of M \<inter> {x. P x}"
573 by (auto simp add: set_of_def)
575 lemma finite_set_of [iff]: "finite (set_of M)"
576   using count [of M] by (simp add: multiset_def set_of_def)
578 lemma finite_Collect_mem [iff]: "finite {x. x :# M}"
579   unfolding set_of_def[symmetric] by simp
581 lemma set_of_mono: "A \<le> B \<Longrightarrow> set_of A \<subseteq> set_of B"
582   by (metis mset_leD subsetI mem_set_of_iff)
584 subsubsection {* Size *}
586 definition wcount where "wcount f M = (\<lambda>x. count M x * Suc (f x))"
588 lemma wcount_union: "wcount f (M + N) a = wcount f M a + wcount f N a"
589   by (auto simp: wcount_def add_mult_distrib)
591 definition size_multiset :: "('a \<Rightarrow> nat) \<Rightarrow> 'a multiset \<Rightarrow> nat" where
592   "size_multiset f M = setsum (wcount f M) (set_of M)"
594 lemmas size_multiset_eq = size_multiset_def[unfolded wcount_def]
596 instantiation multiset :: (type) size begin
597 definition size_multiset where
598   size_multiset_overloaded_def: "size_multiset = Multiset.size_multiset (\<lambda>_. 0)"
599 instance ..
600 end
602 lemmas size_multiset_overloaded_eq =
603   size_multiset_overloaded_def[THEN fun_cong, unfolded size_multiset_eq, simplified]
605 lemma size_multiset_empty [simp]: "size_multiset f {#} = 0"
606 by (simp add: size_multiset_def)
608 lemma size_empty [simp]: "size {#} = 0"
611 lemma size_multiset_single [simp]: "size_multiset f {#b#} = Suc (f b)"
612 by (simp add: size_multiset_eq)
614 lemma size_single [simp]: "size {#b#} = 1"
617 lemma setsum_wcount_Int:
618   "finite A \<Longrightarrow> setsum (wcount f N) (A \<inter> set_of N) = setsum (wcount f N) A"
619 apply (induct rule: finite_induct)
620  apply simp
621 apply (simp add: Int_insert_left set_of_def wcount_def)
622 done
624 lemma size_multiset_union [simp]:
625   "size_multiset f (M + N::'a multiset) = size_multiset f M + size_multiset f N"
626 apply (simp add: size_multiset_def setsum_Un_nat setsum.distrib setsum_wcount_Int wcount_union)
627 apply (subst Int_commute)
628 apply (simp add: setsum_wcount_Int)
629 done
631 lemma size_union [simp]: "size (M + N::'a multiset) = size M + size N"
634 lemma size_multiset_eq_0_iff_empty [iff]: "(size_multiset f M = 0) = (M = {#})"
635 by (auto simp add: size_multiset_eq multiset_eq_iff)
637 lemma size_eq_0_iff_empty [iff]: "(size M = 0) = (M = {#})"
640 lemma nonempty_has_size: "(S \<noteq> {#}) = (0 < size S)"
641 by (metis gr0I gr_implies_not0 size_empty size_eq_0_iff_empty)
643 lemma size_eq_Suc_imp_elem: "size M = Suc n ==> \<exists>a. a :# M"
644 apply (unfold size_multiset_overloaded_eq)
645 apply (drule setsum_SucD)
646 apply auto
647 done
649 lemma size_eq_Suc_imp_eq_union:
650   assumes "size M = Suc n"
651   shows "\<exists>a N. M = N + {#a#}"
652 proof -
653   from assms obtain a where "a \<in># M"
654     by (erule size_eq_Suc_imp_elem [THEN exE])
655   then have "M = M - {#a#} + {#a#}" by simp
656   then show ?thesis by blast
657 qed
660 subsection {* Induction and case splits *}
662 theorem multiset_induct [case_names empty add, induct type: multiset]:
663   assumes empty: "P {#}"
664   assumes add: "\<And>M x. P M \<Longrightarrow> P (M + {#x#})"
665   shows "P M"
666 proof (induct n \<equiv> "size M" arbitrary: M)
667   case 0 thus "P M" by (simp add: empty)
668 next
669   case (Suc k)
670   obtain N x where "M = N + {#x#}"
671     using `Suc k = size M` [symmetric]
672     using size_eq_Suc_imp_eq_union by fast
673   with Suc add show "P M" by simp
674 qed
676 lemma multi_nonempty_split: "M \<noteq> {#} \<Longrightarrow> \<exists>A a. M = A + {#a#}"
677 by (induct M) auto
679 lemma multiset_cases [cases type]:
680   obtains (empty) "M = {#}"
681     | (add) N x where "M = N + {#x#}"
682   using assms by (induct M) simp_all
684 lemma multi_drop_mem_not_eq: "c \<in># B \<Longrightarrow> B - {#c#} \<noteq> B"
685 by (cases "B = {#}") (auto dest: multi_member_split)
687 lemma multiset_partition: "M = {# x:#M. P x #} + {# x:#M. \<not> P x #}"
688 apply (subst multiset_eq_iff)
689 apply auto
690 done
692 lemma mset_less_size: "(A::'a multiset) < B \<Longrightarrow> size A < size B"
693 proof (induct A arbitrary: B)
694   case (empty M)
695   then have "M \<noteq> {#}" by (simp add: mset_less_empty_nonempty)
696   then obtain M' x where "M = M' + {#x#}"
697     by (blast dest: multi_nonempty_split)
698   then show ?case by simp
699 next
700   case (add S x T)
701   have IH: "\<And>B. S < B \<Longrightarrow> size S < size B" by fact
702   have SxsubT: "S + {#x#} < T" by fact
703   then have "x \<in># T" and "S < T" by (auto dest: mset_less_insertD)
704   then obtain T' where T: "T = T' + {#x#}"
705     by (blast dest: multi_member_split)
706   then have "S < T'" using SxsubT
707     by (blast intro: mset_less_add_bothsides)
708   then have "size S < size T'" using IH by simp
709   then show ?case using T by simp
710 qed
713 subsubsection {* Strong induction and subset induction for multisets *}
715 text {* Well-foundedness of proper subset operator: *}
717 text {* proper multiset subset *}
719 definition
720   mset_less_rel :: "('a multiset * 'a multiset) set" where
721   "mset_less_rel = {(A,B). A < B}"
724   assumes "c \<in># B" and "b \<noteq> c"
725   shows "B - {#c#} + {#b#} = B + {#b#} - {#c#}"
726 proof -
727   from `c \<in># B` obtain A where B: "B = A + {#c#}"
728     by (blast dest: multi_member_split)
729   have "A + {#b#} = A + {#b#} + {#c#} - {#c#}" by simp
730   then have "A + {#b#} = A + {#c#} + {#b#} - {#c#}"
731     by (simp add: ac_simps)
732   then show ?thesis using B by simp
733 qed
735 lemma wf_mset_less_rel: "wf mset_less_rel"
736 apply (unfold mset_less_rel_def)
737 apply (rule wf_measure [THEN wf_subset, where f1=size])
738 apply (clarsimp simp: measure_def inv_image_def mset_less_size)
739 done
741 text {* The induction rules: *}
743 lemma full_multiset_induct [case_names less]:
744 assumes ih: "\<And>B. \<forall>(A::'a multiset). A < B \<longrightarrow> P A \<Longrightarrow> P B"
745 shows "P B"
746 apply (rule wf_mset_less_rel [THEN wf_induct])
747 apply (rule ih, auto simp: mset_less_rel_def)
748 done
750 lemma multi_subset_induct [consumes 2, case_names empty add]:
751 assumes "F \<le> A"
752   and empty: "P {#}"
753   and insert: "\<And>a F. a \<in># A \<Longrightarrow> P F \<Longrightarrow> P (F + {#a#})"
754 shows "P F"
755 proof -
756   from `F \<le> A`
757   show ?thesis
758   proof (induct F)
759     show "P {#}" by fact
760   next
761     fix x F
762     assume P: "F \<le> A \<Longrightarrow> P F" and i: "F + {#x#} \<le> A"
763     show "P (F + {#x#})"
764     proof (rule insert)
765       from i show "x \<in># A" by (auto dest: mset_le_insertD)
766       from i have "F \<le> A" by (auto dest: mset_le_insertD)
767       with P show "P F" .
768     qed
769   qed
770 qed
773 subsection {* The fold combinator *}
775 definition fold :: "('a \<Rightarrow> 'b \<Rightarrow> 'b) \<Rightarrow> 'b \<Rightarrow> 'a multiset \<Rightarrow> 'b"
776 where
777   "fold f s M = Finite_Set.fold (\<lambda>x. f x ^^ count M x) s (set_of M)"
779 lemma fold_mset_empty [simp]:
780   "fold f s {#} = s"
781   by (simp add: fold_def)
783 context comp_fun_commute
784 begin
786 lemma fold_mset_insert:
787   "fold f s (M + {#x#}) = f x (fold f s M)"
788 proof -
789   interpret mset: comp_fun_commute "\<lambda>y. f y ^^ count M y"
790     by (fact comp_fun_commute_funpow)
791   interpret mset_union: comp_fun_commute "\<lambda>y. f y ^^ count (M + {#x#}) y"
792     by (fact comp_fun_commute_funpow)
793   show ?thesis
794   proof (cases "x \<in> set_of M")
795     case False
796     then have *: "count (M + {#x#}) x = 1" by simp
797     from False have "Finite_Set.fold (\<lambda>y. f y ^^ count (M + {#x#}) y) s (set_of M) =
798       Finite_Set.fold (\<lambda>y. f y ^^ count M y) s (set_of M)"
799       by (auto intro!: Finite_Set.fold_cong comp_fun_commute_funpow)
800     with False * show ?thesis
801       by (simp add: fold_def del: count_union)
802   next
803     case True
804     def N \<equiv> "set_of M - {x}"
805     from N_def True have *: "set_of M = insert x N" "x \<notin> N" "finite N" by auto
806     then have "Finite_Set.fold (\<lambda>y. f y ^^ count (M + {#x#}) y) s N =
807       Finite_Set.fold (\<lambda>y. f y ^^ count M y) s N"
808       by (auto intro!: Finite_Set.fold_cong comp_fun_commute_funpow)
809     with * show ?thesis by (simp add: fold_def del: count_union) simp
810   qed
811 qed
813 corollary fold_mset_single [simp]:
814   "fold f s {#x#} = f x s"
815 proof -
816   have "fold f s ({#} + {#x#}) = f x s" by (simp only: fold_mset_insert) simp
817   then show ?thesis by simp
818 qed
820 lemma fold_mset_fun_left_comm:
821   "f x (fold f s M) = fold f (f x s) M"
822   by (induct M) (simp_all add: fold_mset_insert fun_left_comm)
824 lemma fold_mset_union [simp]:
825   "fold f s (M + N) = fold f (fold f s M) N"
826 proof (induct M)
827   case empty then show ?case by simp
828 next
829   case (add M x)
830   have "M + {#x#} + N = (M + N) + {#x#}"
831     by (simp add: ac_simps)
832   with add show ?case by (simp add: fold_mset_insert fold_mset_fun_left_comm)
833 qed
835 lemma fold_mset_fusion:
836   assumes "comp_fun_commute g"
837   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")
838 proof -
839   interpret comp_fun_commute g by (fact assms)
840   show "PROP ?P" by (induct A) auto
841 qed
843 end
845 text {*
846   A note on code generation: When defining some function containing a
847   subterm @{term "fold F"}, code generation is not automatic. When
848   interpreting locale @{text left_commutative} with @{text F}, the
849   would be code thms for @{const fold} become thms like
850   @{term "fold F z {#} = z"} where @{text F} is not a pattern but
851   contains defined symbols, i.e.\ is not a code thm. Hence a separate
852   constant with its own code thms needs to be introduced for @{text
853   F}. See the image operator below.
854 *}
857 subsection {* Image *}
859 definition image_mset :: "('a \<Rightarrow> 'b) \<Rightarrow> 'a multiset \<Rightarrow> 'b multiset" where
860   "image_mset f = fold (plus o single o f) {#}"
862 lemma comp_fun_commute_mset_image:
863   "comp_fun_commute (plus o single o f)"
864 proof
865 qed (simp add: ac_simps fun_eq_iff)
867 lemma image_mset_empty [simp]: "image_mset f {#} = {#}"
868   by (simp add: image_mset_def)
870 lemma image_mset_single [simp]: "image_mset f {#x#} = {#f x#}"
871 proof -
872   interpret comp_fun_commute "plus o single o f"
873     by (fact comp_fun_commute_mset_image)
874   show ?thesis by (simp add: image_mset_def)
875 qed
877 lemma image_mset_union [simp]:
878   "image_mset f (M + N) = image_mset f M + image_mset f N"
879 proof -
880   interpret comp_fun_commute "plus o single o f"
881     by (fact comp_fun_commute_mset_image)
882   show ?thesis by (induct N) (simp_all add: image_mset_def ac_simps)
883 qed
885 corollary image_mset_insert:
886   "image_mset f (M + {#a#}) = image_mset f M + {#f a#}"
887   by simp
889 lemma set_of_image_mset [simp]:
890   "set_of (image_mset f M) = image f (set_of M)"
891   by (induct M) simp_all
893 lemma size_image_mset [simp]:
894   "size (image_mset f M) = size M"
895   by (induct M) simp_all
897 lemma image_mset_is_empty_iff [simp]:
898   "image_mset f M = {#} \<longleftrightarrow> M = {#}"
899   by (cases M) auto
901 syntax
902   "_comprehension1_mset" :: "'a \<Rightarrow> 'b \<Rightarrow> 'b multiset \<Rightarrow> 'a multiset"
903       ("({#_/. _ :# _#})")
904 translations
905   "{#e. x:#M#}" == "CONST image_mset (%x. e) M"
907 syntax
908   "_comprehension2_mset" :: "'a \<Rightarrow> 'b \<Rightarrow> 'b multiset \<Rightarrow> bool \<Rightarrow> 'a multiset"
909       ("({#_/ | _ :# _./ _#})")
910 translations
911   "{#e | x:#M. P#}" => "{#e. x :# {# x:#M. P#}#}"
913 text {*
914   This allows to write not just filters like @{term "{#x:#M. x<c#}"}
915   but also images like @{term "{#x+x. x:#M #}"} and @{term [source]
916   "{#x+x|x:#M. x<c#}"}, where the latter is currently displayed as
917   @{term "{#x+x|x:#M. x<c#}"}.
918 *}
920 functor image_mset: image_mset
921 proof -
922   fix f g show "image_mset f \<circ> image_mset g = image_mset (f \<circ> g)"
923   proof
924     fix A
925     show "(image_mset f \<circ> image_mset g) A = image_mset (f \<circ> g) A"
926       by (induct A) simp_all
927   qed
928   show "image_mset id = id"
929   proof
930     fix A
931     show "image_mset id A = id A"
932       by (induct A) simp_all
933   qed
934 qed
936 declare image_mset.identity [simp]
939 subsection {* Further conversions *}
941 primrec multiset_of :: "'a list \<Rightarrow> 'a multiset" where
942   "multiset_of [] = {#}" |
943   "multiset_of (a # x) = multiset_of x + {# a #}"
945 lemma in_multiset_in_set:
946   "x \<in># multiset_of xs \<longleftrightarrow> x \<in> set xs"
947   by (induct xs) simp_all
949 lemma count_multiset_of:
950   "count (multiset_of xs) x = length (filter (\<lambda>y. x = y) xs)"
951   by (induct xs) simp_all
953 lemma multiset_of_zero_iff[simp]: "(multiset_of x = {#}) = (x = [])"
954 by (induct x) auto
956 lemma multiset_of_zero_iff_right[simp]: "({#} = multiset_of x) = (x = [])"
957 by (induct x) auto
959 lemma set_of_multiset_of[simp]: "set_of (multiset_of x) = set x"
960 by (induct x) auto
962 lemma mem_set_multiset_eq: "x \<in> set xs = (x :# multiset_of xs)"
963 by (induct xs) auto
965 lemma size_multiset_of [simp]: "size (multiset_of xs) = length xs"
966   by (induct xs) simp_all
968 lemma multiset_of_append [simp]:
969   "multiset_of (xs @ ys) = multiset_of xs + multiset_of ys"
970   by (induct xs arbitrary: ys) (auto simp: ac_simps)
972 lemma multiset_of_filter:
973   "multiset_of (filter P xs) = {#x :# multiset_of xs. P x #}"
974   by (induct xs) simp_all
976 lemma multiset_of_rev [simp]:
977   "multiset_of (rev xs) = multiset_of xs"
978   by (induct xs) simp_all
980 lemma surj_multiset_of: "surj multiset_of"
981 apply (unfold surj_def)
982 apply (rule allI)
983 apply (rule_tac M = y in multiset_induct)
984  apply auto
985 apply (rule_tac x = "x # xa" in exI)
986 apply auto
987 done
989 lemma set_count_greater_0: "set x = {a. count (multiset_of x) a > 0}"
990 by (induct x) auto
992 lemma distinct_count_atmost_1:
993   "distinct x = (! a. count (multiset_of x) a = (if a \<in> set x then 1 else 0))"
994 apply (induct x, simp, rule iffI, simp_all)
995 apply (rename_tac a b)
996 apply (rule conjI)
997 apply (simp_all add: set_of_multiset_of [THEN sym] del: set_of_multiset_of)
998 apply (erule_tac x = a in allE, simp, clarify)
999 apply (erule_tac x = aa in allE, simp)
1000 done
1002 lemma multiset_of_eq_setD:
1003   "multiset_of xs = multiset_of ys \<Longrightarrow> set xs = set ys"
1004 by (rule) (auto simp add:multiset_eq_iff set_count_greater_0)
1006 lemma set_eq_iff_multiset_of_eq_distinct:
1007   "distinct x \<Longrightarrow> distinct y \<Longrightarrow>
1008     (set x = set y) = (multiset_of x = multiset_of y)"
1009 by (auto simp: multiset_eq_iff distinct_count_atmost_1)
1011 lemma set_eq_iff_multiset_of_remdups_eq:
1012    "(set x = set y) = (multiset_of (remdups x) = multiset_of (remdups y))"
1013 apply (rule iffI)
1014 apply (simp add: set_eq_iff_multiset_of_eq_distinct[THEN iffD1])
1015 apply (drule distinct_remdups [THEN distinct_remdups
1016       [THEN set_eq_iff_multiset_of_eq_distinct [THEN iffD2]]])
1017 apply simp
1018 done
1020 lemma multiset_of_compl_union [simp]:
1021   "multiset_of [x\<leftarrow>xs. P x] + multiset_of [x\<leftarrow>xs. \<not>P x] = multiset_of xs"
1022   by (induct xs) (auto simp: ac_simps)
1024 lemma count_multiset_of_length_filter:
1025   "count (multiset_of xs) x = length (filter (\<lambda>y. x = y) xs)"
1026   by (induct xs) auto
1028 lemma nth_mem_multiset_of: "i < length ls \<Longrightarrow> (ls ! i) :# multiset_of ls"
1029 apply (induct ls arbitrary: i)
1030  apply simp
1031 apply (case_tac i)
1032  apply auto
1033 done
1035 lemma multiset_of_remove1[simp]:
1036   "multiset_of (remove1 a xs) = multiset_of xs - {#a#}"
1037 by (induct xs) (auto simp add: multiset_eq_iff)
1039 lemma multiset_of_eq_length:
1040   assumes "multiset_of xs = multiset_of ys"
1041   shows "length xs = length ys"
1042   using assms by (metis size_multiset_of)
1044 lemma multiset_of_eq_length_filter:
1045   assumes "multiset_of xs = multiset_of ys"
1046   shows "length (filter (\<lambda>x. z = x) xs) = length (filter (\<lambda>y. z = y) ys)"
1047   using assms by (metis count_multiset_of)
1049 lemma fold_multiset_equiv:
1050   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"
1051     and equiv: "multiset_of xs = multiset_of ys"
1052   shows "List.fold f xs = List.fold f ys"
1053 using f equiv [symmetric]
1054 proof (induct xs arbitrary: ys)
1055   case Nil then show ?case by simp
1056 next
1057   case (Cons x xs)
1058   then have *: "set ys = set (x # xs)" by (blast dest: multiset_of_eq_setD)
1059   have "\<And>x y. x \<in> set ys \<Longrightarrow> y \<in> set ys \<Longrightarrow> f x \<circ> f y = f y \<circ> f x"
1060     by (rule Cons.prems(1)) (simp_all add: *)
1061   moreover from * have "x \<in> set ys" by simp
1062   ultimately have "List.fold f ys = List.fold f (remove1 x ys) \<circ> f x" by (fact fold_remove1_split)
1063   moreover from Cons.prems have "List.fold f xs = List.fold f (remove1 x ys)" by (auto intro: Cons.hyps)
1064   ultimately show ?case by simp
1065 qed
1067 lemma multiset_of_insort [simp]:
1068   "multiset_of (insort x xs) = multiset_of xs + {#x#}"
1069   by (induct xs) (simp_all add: ac_simps)
1071 lemma in_multiset_of:
1072   "x \<in># multiset_of xs \<longleftrightarrow> x \<in> set xs"
1073   by (induct xs) simp_all
1075 lemma multiset_of_map:
1076   "multiset_of (map f xs) = image_mset f (multiset_of xs)"
1077   by (induct xs) simp_all
1079 definition multiset_of_set :: "'a set \<Rightarrow> 'a multiset"
1080 where
1081   "multiset_of_set = folding.F (\<lambda>x M. {#x#} + M) {#}"
1083 interpretation multiset_of_set!: folding "\<lambda>x M. {#x#} + M" "{#}"
1084 where
1085   "folding.F (\<lambda>x M. {#x#} + M) {#} = multiset_of_set"
1086 proof -
1087   interpret comp_fun_commute "\<lambda>x M. {#x#} + M" by default (simp add: fun_eq_iff ac_simps)
1088   show "folding (\<lambda>x M. {#x#} + M)" by default (fact comp_fun_commute)
1089   from multiset_of_set_def show "folding.F (\<lambda>x M. {#x#} + M) {#} = multiset_of_set" ..
1090 qed
1092 lemma count_multiset_of_set [simp]:
1093   "finite A \<Longrightarrow> x \<in> A \<Longrightarrow> count (multiset_of_set A) x = 1" (is "PROP ?P")
1094   "\<not> finite A \<Longrightarrow> count (multiset_of_set A) x = 0" (is "PROP ?Q")
1095   "x \<notin> A \<Longrightarrow> count (multiset_of_set A) x = 0" (is "PROP ?R")
1096 proof -
1097   { fix A
1098     assume "x \<notin> A"
1099     have "count (multiset_of_set A) x = 0"
1100     proof (cases "finite A")
1101       case False then show ?thesis by simp
1102     next
1103       case True from True `x \<notin> A` show ?thesis by (induct A) auto
1104     qed
1105   } note * = this
1106   then show "PROP ?P" "PROP ?Q" "PROP ?R"
1107   by (auto elim!: Set.set_insert)
1108 qed -- {* TODO: maybe define @{const multiset_of_set} also in terms of @{const Abs_multiset} *}
1110 context linorder
1111 begin
1113 definition sorted_list_of_multiset :: "'a multiset \<Rightarrow> 'a list"
1114 where
1115   "sorted_list_of_multiset M = fold insort [] M"
1117 lemma sorted_list_of_multiset_empty [simp]:
1118   "sorted_list_of_multiset {#} = []"
1119   by (simp add: sorted_list_of_multiset_def)
1121 lemma sorted_list_of_multiset_singleton [simp]:
1122   "sorted_list_of_multiset {#x#} = [x]"
1123 proof -
1124   interpret comp_fun_commute insort by (fact comp_fun_commute_insort)
1125   show ?thesis by (simp add: sorted_list_of_multiset_def)
1126 qed
1128 lemma sorted_list_of_multiset_insert [simp]:
1129   "sorted_list_of_multiset (M + {#x#}) = List.insort x (sorted_list_of_multiset M)"
1130 proof -
1131   interpret comp_fun_commute insort by (fact comp_fun_commute_insort)
1132   show ?thesis by (simp add: sorted_list_of_multiset_def)
1133 qed
1135 end
1137 lemma multiset_of_sorted_list_of_multiset [simp]:
1138   "multiset_of (sorted_list_of_multiset M) = M"
1139   by (induct M) simp_all
1141 lemma sorted_list_of_multiset_multiset_of [simp]:
1142   "sorted_list_of_multiset (multiset_of xs) = sort xs"
1143   by (induct xs) simp_all
1145 lemma finite_set_of_multiset_of_set:
1146   assumes "finite A"
1147   shows "set_of (multiset_of_set A) = A"
1148   using assms by (induct A) simp_all
1150 lemma infinite_set_of_multiset_of_set:
1151   assumes "\<not> finite A"
1152   shows "set_of (multiset_of_set A) = {}"
1153   using assms by simp
1155 lemma set_sorted_list_of_multiset [simp]:
1156   "set (sorted_list_of_multiset M) = set_of M"
1157   by (induct M) (simp_all add: set_insort)
1159 lemma sorted_list_of_multiset_of_set [simp]:
1160   "sorted_list_of_multiset (multiset_of_set A) = sorted_list_of_set A"
1161   by (cases "finite A") (induct A rule: finite_induct, simp_all add: ac_simps)
1164 subsection {* Big operators *}
1166 no_notation times (infixl "*" 70)
1167 no_notation Groups.one ("1")
1169 locale comm_monoid_mset = comm_monoid
1170 begin
1172 definition F :: "'a multiset \<Rightarrow> 'a"
1173 where
1174   eq_fold: "F M = Multiset.fold f 1 M"
1176 lemma empty [simp]:
1177   "F {#} = 1"
1178   by (simp add: eq_fold)
1180 lemma singleton [simp]:
1181   "F {#x#} = x"
1182 proof -
1183   interpret comp_fun_commute
1184     by default (simp add: fun_eq_iff left_commute)
1185   show ?thesis by (simp add: eq_fold)
1186 qed
1188 lemma union [simp]:
1189   "F (M + N) = F M * F N"
1190 proof -
1191   interpret comp_fun_commute f
1192     by default (simp add: fun_eq_iff left_commute)
1193   show ?thesis by (induct N) (simp_all add: left_commute eq_fold)
1194 qed
1196 end
1198 notation times (infixl "*" 70)
1199 notation Groups.one ("1")
1202 begin
1204 definition msetsum :: "'a multiset \<Rightarrow> 'a"
1205 where
1206   "msetsum = comm_monoid_mset.F plus 0"
1208 sublocale msetsum!: comm_monoid_mset plus 0
1209 where
1210   "comm_monoid_mset.F plus 0 = msetsum"
1211 proof -
1212   show "comm_monoid_mset plus 0" ..
1213   from msetsum_def show "comm_monoid_mset.F plus 0 = msetsum" ..
1214 qed
1216 lemma setsum_unfold_msetsum:
1217   "setsum f A = msetsum (image_mset f (multiset_of_set A))"
1218   by (cases "finite A") (induct A rule: finite_induct, simp_all)
1220 end
1222 syntax
1223   "_msetsum_image" :: "pttrn \<Rightarrow> 'b set \<Rightarrow> 'a \<Rightarrow> 'a::comm_monoid_add"
1224       ("(3SUM _:#_. _)" [0, 51, 10] 10)
1226 syntax (xsymbols)
1227   "_msetsum_image" :: "pttrn \<Rightarrow> 'b set \<Rightarrow> 'a \<Rightarrow> 'a::comm_monoid_add"
1228       ("(3\<Sum>_\<in>#_. _)" [0, 51, 10] 10)
1230 syntax (HTML output)
1231   "_msetsum_image" :: "pttrn \<Rightarrow> 'b set \<Rightarrow> 'a \<Rightarrow> 'a::comm_monoid_add"
1232       ("(3\<Sum>_\<in>#_. _)" [0, 51, 10] 10)
1234 translations
1235   "SUM i :# A. b" == "CONST msetsum (CONST image_mset (\<lambda>i. b) A)"
1237 context comm_monoid_mult
1238 begin
1240 definition msetprod :: "'a multiset \<Rightarrow> 'a"
1241 where
1242   "msetprod = comm_monoid_mset.F times 1"
1244 sublocale msetprod!: comm_monoid_mset times 1
1245 where
1246   "comm_monoid_mset.F times 1 = msetprod"
1247 proof -
1248   show "comm_monoid_mset times 1" ..
1249   from msetprod_def show "comm_monoid_mset.F times 1 = msetprod" ..
1250 qed
1252 lemma msetprod_empty:
1253   "msetprod {#} = 1"
1254   by (fact msetprod.empty)
1256 lemma msetprod_singleton:
1257   "msetprod {#x#} = x"
1258   by (fact msetprod.singleton)
1260 lemma msetprod_Un:
1261   "msetprod (A + B) = msetprod A * msetprod B"
1262   by (fact msetprod.union)
1264 lemma setprod_unfold_msetprod:
1265   "setprod f A = msetprod (image_mset f (multiset_of_set A))"
1266   by (cases "finite A") (induct A rule: finite_induct, simp_all)
1268 lemma msetprod_multiplicity:
1269   "msetprod M = setprod (\<lambda>x. x ^ count M x) (set_of M)"
1270   by (simp add: Multiset.fold_def setprod.eq_fold msetprod.eq_fold funpow_times_power comp_def)
1272 end
1274 syntax
1275   "_msetprod_image" :: "pttrn \<Rightarrow> 'b set \<Rightarrow> 'a \<Rightarrow> 'a::comm_monoid_mult"
1276       ("(3PROD _:#_. _)" [0, 51, 10] 10)
1278 syntax (xsymbols)
1279   "_msetprod_image" :: "pttrn \<Rightarrow> 'b set \<Rightarrow> 'a \<Rightarrow> 'a::comm_monoid_mult"
1280       ("(3\<Prod>_\<in>#_. _)" [0, 51, 10] 10)
1282 syntax (HTML output)
1283   "_msetprod_image" :: "pttrn \<Rightarrow> 'b set \<Rightarrow> 'a \<Rightarrow> 'a::comm_monoid_mult"
1284       ("(3\<Prod>_\<in>#_. _)" [0, 51, 10] 10)
1286 translations
1287   "PROD i :# A. b" == "CONST msetprod (CONST image_mset (\<lambda>i. b) A)"
1289 lemma (in comm_semiring_1) dvd_msetprod:
1290   assumes "x \<in># A"
1291   shows "x dvd msetprod A"
1292 proof -
1293   from assms have "A = (A - {#x#}) + {#x#}" by simp
1294   then obtain B where "A = B + {#x#}" ..
1295   then show ?thesis by simp
1296 qed
1299 subsection {* Cardinality *}
1301 definition mcard :: "'a multiset \<Rightarrow> nat"
1302 where
1303   "mcard = msetsum \<circ> image_mset (\<lambda>_. 1)"
1305 lemma mcard_empty [simp]:
1306   "mcard {#} = 0"
1307   by (simp add: mcard_def)
1309 lemma mcard_singleton [simp]:
1310   "mcard {#a#} = Suc 0"
1311   by (simp add: mcard_def)
1313 lemma mcard_plus [simp]:
1314   "mcard (M + N) = mcard M + mcard N"
1315   by (simp add: mcard_def)
1317 lemma mcard_empty_iff [simp]:
1318   "mcard M = 0 \<longleftrightarrow> M = {#}"
1319   by (induct M) simp_all
1321 lemma mcard_unfold_setsum:
1322   "mcard M = setsum (count M) (set_of M)"
1323 proof (induct M)
1324   case empty then show ?case by simp
1325 next
1326   case (add M x) then show ?case
1327     by (cases "x \<in> set_of M")
1328       (simp_all del: mem_set_of_iff add: setsum.distrib setsum.delta' insert_absorb, simp)
1329 qed
1331 lemma size_eq_mcard:
1332   "size = mcard"
1333   by (simp add: fun_eq_iff size_multiset_overloaded_eq mcard_unfold_setsum)
1335 lemma mcard_multiset_of:
1336   "mcard (multiset_of xs) = length xs"
1337   by (induct xs) simp_all
1339 lemma mcard_mono: assumes "A \<le> B"
1340   shows "mcard A \<le> mcard B"
1341 proof -
1342   from assms[unfolded mset_le_exists_conv]
1343   obtain C where B: "B = A + C" by auto
1344   show ?thesis unfolding B by (induct C, auto)
1345 qed
1347 lemma mcard_filter_lesseq[simp]: "mcard (Multiset.filter f M) \<le> mcard M"
1348   by (rule mcard_mono[OF multiset_filter_subset])
1351 subsection {* Alternative representations *}
1353 subsubsection {* Lists *}
1355 context linorder
1356 begin
1358 lemma multiset_of_insort [simp]:
1359   "multiset_of (insort_key k x xs) = {#x#} + multiset_of xs"
1360   by (induct xs) (simp_all add: ac_simps)
1362 lemma multiset_of_sort [simp]:
1363   "multiset_of (sort_key k xs) = multiset_of xs"
1364   by (induct xs) (simp_all add: ac_simps)
1366 text {*
1367   This lemma shows which properties suffice to show that a function
1368   @{text "f"} with @{text "f xs = ys"} behaves like sort.
1369 *}
1371 lemma properties_for_sort_key:
1372   assumes "multiset_of ys = multiset_of xs"
1373   and "\<And>k. k \<in> set ys \<Longrightarrow> filter (\<lambda>x. f k = f x) ys = filter (\<lambda>x. f k = f x) xs"
1374   and "sorted (map f ys)"
1375   shows "sort_key f xs = ys"
1376 using assms
1377 proof (induct xs arbitrary: ys)
1378   case Nil then show ?case by simp
1379 next
1380   case (Cons x xs)
1381   from Cons.prems(2) have
1382     "\<forall>k \<in> set ys. filter (\<lambda>x. f k = f x) (remove1 x ys) = filter (\<lambda>x. f k = f x) xs"
1383     by (simp add: filter_remove1)
1384   with Cons.prems have "sort_key f xs = remove1 x ys"
1385     by (auto intro!: Cons.hyps simp add: sorted_map_remove1)
1386   moreover from Cons.prems have "x \<in> set ys"
1387     by (auto simp add: mem_set_multiset_eq intro!: ccontr)
1388   ultimately show ?case using Cons.prems by (simp add: insort_key_remove1)
1389 qed
1391 lemma properties_for_sort:
1392   assumes multiset: "multiset_of ys = multiset_of xs"
1393   and "sorted ys"
1394   shows "sort xs = ys"
1395 proof (rule properties_for_sort_key)
1396   from multiset show "multiset_of ys = multiset_of xs" .
1397   from `sorted ys` show "sorted (map (\<lambda>x. x) ys)" by simp
1398   from multiset have "\<And>k. length (filter (\<lambda>y. k = y) ys) = length (filter (\<lambda>x. k = x) xs)"
1399     by (rule multiset_of_eq_length_filter)
1400   then have "\<And>k. replicate (length (filter (\<lambda>y. k = y) ys)) k = replicate (length (filter (\<lambda>x. k = x) xs)) k"
1401     by simp
1402   then show "\<And>k. k \<in> set ys \<Longrightarrow> filter (\<lambda>y. k = y) ys = filter (\<lambda>x. k = x) xs"
1403     by (simp add: replicate_length_filter)
1404 qed
1406 lemma sort_key_by_quicksort:
1407   "sort_key f xs = sort_key f [x\<leftarrow>xs. f x < f (xs ! (length xs div 2))]
1408     @ [x\<leftarrow>xs. f x = f (xs ! (length xs div 2))]
1409     @ sort_key f [x\<leftarrow>xs. f x > f (xs ! (length xs div 2))]" (is "sort_key f ?lhs = ?rhs")
1410 proof (rule properties_for_sort_key)
1411   show "multiset_of ?rhs = multiset_of ?lhs"
1412     by (rule multiset_eqI) (auto simp add: multiset_of_filter)
1413 next
1414   show "sorted (map f ?rhs)"
1415     by (auto simp add: sorted_append intro: sorted_map_same)
1416 next
1417   fix l
1418   assume "l \<in> set ?rhs"
1419   let ?pivot = "f (xs ! (length xs div 2))"
1420   have *: "\<And>x. f l = f x \<longleftrightarrow> f x = f l" by auto
1421   have "[x \<leftarrow> sort_key f xs . f x = f l] = [x \<leftarrow> xs. f x = f l]"
1422     unfolding filter_sort by (rule properties_for_sort_key) (auto intro: sorted_map_same)
1423   with * have **: "[x \<leftarrow> sort_key f xs . f l = f x] = [x \<leftarrow> xs. f l = f x]" by simp
1424   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
1425   then have "\<And>P. [x \<leftarrow> sort_key f xs . P (f x) ?pivot \<and> f l = f x] =
1426     [x \<leftarrow> sort_key f xs. P (f l) ?pivot \<and> f l = f x]" by simp
1427   note *** = this [of "op <"] this [of "op >"] this [of "op ="]
1428   show "[x \<leftarrow> ?rhs. f l = f x] = [x \<leftarrow> ?lhs. f l = f x]"
1429   proof (cases "f l" ?pivot rule: linorder_cases)
1430     case less
1431     then have "f l \<noteq> ?pivot" and "\<not> f l > ?pivot" by auto
1432     with less show ?thesis
1433       by (simp add: filter_sort [symmetric] ** ***)
1434   next
1435     case equal then show ?thesis
1436       by (simp add: * less_le)
1437   next
1438     case greater
1439     then have "f l \<noteq> ?pivot" and "\<not> f l < ?pivot" by auto
1440     with greater show ?thesis
1441       by (simp add: filter_sort [symmetric] ** ***)
1442   qed
1443 qed
1445 lemma sort_by_quicksort:
1446   "sort xs = sort [x\<leftarrow>xs. x < xs ! (length xs div 2)]
1447     @ [x\<leftarrow>xs. x = xs ! (length xs div 2)]
1448     @ sort [x\<leftarrow>xs. x > xs ! (length xs div 2)]" (is "sort ?lhs = ?rhs")
1449   using sort_key_by_quicksort [of "\<lambda>x. x", symmetric] by simp
1451 text {* A stable parametrized quicksort *}
1453 definition part :: "('b \<Rightarrow> 'a) \<Rightarrow> 'a \<Rightarrow> 'b list \<Rightarrow> 'b list \<times> 'b list \<times> 'b list" where
1454   "part f pivot xs = ([x \<leftarrow> xs. f x < pivot], [x \<leftarrow> xs. f x = pivot], [x \<leftarrow> xs. pivot < f x])"
1456 lemma part_code [code]:
1457   "part f pivot [] = ([], [], [])"
1458   "part f pivot (x # xs) = (let (lts, eqs, gts) = part f pivot xs; x' = f x in
1459      if x' < pivot then (x # lts, eqs, gts)
1460      else if x' > pivot then (lts, eqs, x # gts)
1461      else (lts, x # eqs, gts))"
1462   by (auto simp add: part_def Let_def split_def)
1464 lemma sort_key_by_quicksort_code [code]:
1465   "sort_key f xs = (case xs of [] \<Rightarrow> []
1466     | [x] \<Rightarrow> xs
1467     | [x, y] \<Rightarrow> (if f x \<le> f y then xs else [y, x])
1468     | _ \<Rightarrow> (let (lts, eqs, gts) = part f (f (xs ! (length xs div 2))) xs
1469        in sort_key f lts @ eqs @ sort_key f gts))"
1470 proof (cases xs)
1471   case Nil then show ?thesis by simp
1472 next
1473   case (Cons _ ys) note hyps = Cons show ?thesis
1474   proof (cases ys)
1475     case Nil with hyps show ?thesis by simp
1476   next
1477     case (Cons _ zs) note hyps = hyps Cons show ?thesis
1478     proof (cases zs)
1479       case Nil with hyps show ?thesis by auto
1480     next
1481       case Cons
1482       from sort_key_by_quicksort [of f xs]
1483       have "sort_key f xs = (let (lts, eqs, gts) = part f (f (xs ! (length xs div 2))) xs
1484         in sort_key f lts @ eqs @ sort_key f gts)"
1485       by (simp only: split_def Let_def part_def fst_conv snd_conv)
1486       with hyps Cons show ?thesis by (simp only: list.cases)
1487     qed
1488   qed
1489 qed
1491 end
1493 hide_const (open) part
1495 lemma multiset_of_remdups_le: "multiset_of (remdups xs) \<le> multiset_of xs"
1496   by (induct xs) (auto intro: order_trans)
1498 lemma multiset_of_update:
1499   "i < length ls \<Longrightarrow> multiset_of (ls[i := v]) = multiset_of ls - {#ls ! i#} + {#v#}"
1500 proof (induct ls arbitrary: i)
1501   case Nil then show ?case by simp
1502 next
1503   case (Cons x xs)
1504   show ?case
1505   proof (cases i)
1506     case 0 then show ?thesis by simp
1507   next
1508     case (Suc i')
1509     with Cons show ?thesis
1510       apply simp
1511       apply (subst add.assoc)
1512       apply (subst add.commute [of "{#v#}" "{#x#}"])
1513       apply (subst add.assoc [symmetric])
1514       apply simp
1515       apply (rule mset_le_multiset_union_diff_commute)
1516       apply (simp add: mset_le_single nth_mem_multiset_of)
1517       done
1518   qed
1519 qed
1521 lemma multiset_of_swap:
1522   "i < length ls \<Longrightarrow> j < length ls \<Longrightarrow>
1523     multiset_of (ls[j := ls ! i, i := ls ! j]) = multiset_of ls"
1524   by (cases "i = j") (simp_all add: multiset_of_update nth_mem_multiset_of)
1527 subsection {* The multiset order *}
1529 subsubsection {* Well-foundedness *}
1531 definition mult1 :: "('a \<times> 'a) set => ('a multiset \<times> 'a multiset) set" where
1532   "mult1 r = {(N, M). \<exists>a M0 K. M = M0 + {#a#} \<and> N = M0 + K \<and>
1533       (\<forall>b. b :# K --> (b, a) \<in> r)}"
1535 definition mult :: "('a \<times> 'a) set => ('a multiset \<times> 'a multiset) set" where
1536   "mult r = (mult1 r)\<^sup>+"
1538 lemma not_less_empty [iff]: "(M, {#}) \<notin> mult1 r"
1539 by (simp add: mult1_def)
1541 lemma less_add: "(N, M0 + {#a#}) \<in> mult1 r ==>
1542     (\<exists>M. (M, M0) \<in> mult1 r \<and> N = M + {#a#}) \<or>
1543     (\<exists>K. (\<forall>b. b :# K --> (b, a) \<in> r) \<and> N = M0 + K)"
1544   (is "_ \<Longrightarrow> ?case1 (mult1 r) \<or> ?case2")
1545 proof (unfold mult1_def)
1546   let ?r = "\<lambda>K a. \<forall>b. b :# K --> (b, a) \<in> r"
1547   let ?R = "\<lambda>N M. \<exists>a M0 K. M = M0 + {#a#} \<and> N = M0 + K \<and> ?r K a"
1548   let ?case1 = "?case1 {(N, M). ?R N M}"
1550   assume "(N, M0 + {#a#}) \<in> {(N, M). ?R N M}"
1551   then have "\<exists>a' M0' K.
1552       M0 + {#a#} = M0' + {#a'#} \<and> N = M0' + K \<and> ?r K a'" by simp
1553   then show "?case1 \<or> ?case2"
1554   proof (elim exE conjE)
1555     fix a' M0' K
1556     assume N: "N = M0' + K" and r: "?r K a'"
1557     assume "M0 + {#a#} = M0' + {#a'#}"
1558     then have "M0 = M0' \<and> a = a' \<or>
1559         (\<exists>K'. M0 = K' + {#a'#} \<and> M0' = K' + {#a#})"
1560       by (simp only: add_eq_conv_ex)
1561     then show ?thesis
1562     proof (elim disjE conjE exE)
1563       assume "M0 = M0'" "a = a'"
1564       with N r have "?r K a \<and> N = M0 + K" by simp
1565       then have ?case2 .. then show ?thesis ..
1566     next
1567       fix K'
1568       assume "M0' = K' + {#a#}"
1569       with N have n: "N = K' + K + {#a#}" by (simp add: ac_simps)
1571       assume "M0 = K' + {#a'#}"
1572       with r have "?R (K' + K) M0" by blast
1573       with n have ?case1 by simp then show ?thesis ..
1574     qed
1575   qed
1576 qed
1578 lemma all_accessible: "wf r ==> \<forall>M. M \<in> Wellfounded.acc (mult1 r)"
1579 proof
1580   let ?R = "mult1 r"
1581   let ?W = "Wellfounded.acc ?R"
1582   {
1583     fix M M0 a
1584     assume M0: "M0 \<in> ?W"
1585       and wf_hyp: "!!b. (b, a) \<in> r ==> (\<forall>M \<in> ?W. M + {#b#} \<in> ?W)"
1586       and acc_hyp: "\<forall>M. (M, M0) \<in> ?R --> M + {#a#} \<in> ?W"
1587     have "M0 + {#a#} \<in> ?W"
1588     proof (rule accI [of "M0 + {#a#}"])
1589       fix N
1590       assume "(N, M0 + {#a#}) \<in> ?R"
1591       then have "((\<exists>M. (M, M0) \<in> ?R \<and> N = M + {#a#}) \<or>
1592           (\<exists>K. (\<forall>b. b :# K --> (b, a) \<in> r) \<and> N = M0 + K))"
1593         by (rule less_add)
1594       then show "N \<in> ?W"
1595       proof (elim exE disjE conjE)
1596         fix M assume "(M, M0) \<in> ?R" and N: "N = M + {#a#}"
1597         from acc_hyp have "(M, M0) \<in> ?R --> M + {#a#} \<in> ?W" ..
1598         from this and `(M, M0) \<in> ?R` have "M + {#a#} \<in> ?W" ..
1599         then show "N \<in> ?W" by (simp only: N)
1600       next
1601         fix K
1602         assume N: "N = M0 + K"
1603         assume "\<forall>b. b :# K --> (b, a) \<in> r"
1604         then have "M0 + K \<in> ?W"
1605         proof (induct K)
1606           case empty
1607           from M0 show "M0 + {#} \<in> ?W" by simp
1608         next
1609           case (add K x)
1610           from add.prems have "(x, a) \<in> r" by simp
1611           with wf_hyp have "\<forall>M \<in> ?W. M + {#x#} \<in> ?W" by blast
1612           moreover from add have "M0 + K \<in> ?W" by simp
1613           ultimately have "(M0 + K) + {#x#} \<in> ?W" ..
1614           then show "M0 + (K + {#x#}) \<in> ?W" by (simp only: add.assoc)
1615         qed
1616         then show "N \<in> ?W" by (simp only: N)
1617       qed
1618     qed
1619   } note tedious_reasoning = this
1621   assume wf: "wf r"
1622   fix M
1623   show "M \<in> ?W"
1624   proof (induct M)
1625     show "{#} \<in> ?W"
1626     proof (rule accI)
1627       fix b assume "(b, {#}) \<in> ?R"
1628       with not_less_empty show "b \<in> ?W" by contradiction
1629     qed
1631     fix M a assume "M \<in> ?W"
1632     from wf have "\<forall>M \<in> ?W. M + {#a#} \<in> ?W"
1633     proof induct
1634       fix a
1635       assume r: "!!b. (b, a) \<in> r ==> (\<forall>M \<in> ?W. M + {#b#} \<in> ?W)"
1636       show "\<forall>M \<in> ?W. M + {#a#} \<in> ?W"
1637       proof
1638         fix M assume "M \<in> ?W"
1639         then show "M + {#a#} \<in> ?W"
1640           by (rule acc_induct) (rule tedious_reasoning [OF _ r])
1641       qed
1642     qed
1643     from this and `M \<in> ?W` show "M + {#a#} \<in> ?W" ..
1644   qed
1645 qed
1647 theorem wf_mult1: "wf r ==> wf (mult1 r)"
1648 by (rule acc_wfI) (rule all_accessible)
1650 theorem wf_mult: "wf r ==> wf (mult r)"
1651 unfolding mult_def by (rule wf_trancl) (rule wf_mult1)
1654 subsubsection {* Closure-free presentation *}
1656 text {* One direction. *}
1658 lemma mult_implies_one_step:
1659   "trans r ==> (M, N) \<in> mult r ==>
1660     \<exists>I J K. N = I + J \<and> M = I + K \<and> J \<noteq> {#} \<and>
1661     (\<forall>k \<in> set_of K. \<exists>j \<in> set_of J. (k, j) \<in> r)"
1662 apply (unfold mult_def mult1_def set_of_def)
1663 apply (erule converse_trancl_induct, clarify)
1664  apply (rule_tac x = M0 in exI, simp, clarify)
1665 apply (case_tac "a :# K")
1666  apply (rule_tac x = I in exI)
1667  apply (simp (no_asm))
1668  apply (rule_tac x = "(K - {#a#}) + Ka" in exI)
1669  apply (simp (no_asm_simp) add: add.assoc [symmetric])
1670  apply (drule_tac f = "\<lambda>M. M - {#a#}" and x="?S + ?T" in arg_cong)
1671  apply (simp add: diff_union_single_conv)
1672  apply (simp (no_asm_use) add: trans_def)
1673  apply blast
1674 apply (subgoal_tac "a :# I")
1675  apply (rule_tac x = "I - {#a#}" in exI)
1676  apply (rule_tac x = "J + {#a#}" in exI)
1677  apply (rule_tac x = "K + Ka" in exI)
1678  apply (rule conjI)
1679   apply (simp add: multiset_eq_iff split: nat_diff_split)
1680  apply (rule conjI)
1681   apply (drule_tac f = "\<lambda>M. M - {#a#}" and x="?S + ?T" in arg_cong, simp)
1682   apply (simp add: multiset_eq_iff split: nat_diff_split)
1683  apply (simp (no_asm_use) add: trans_def)
1684  apply blast
1685 apply (subgoal_tac "a :# (M0 + {#a#})")
1686  apply simp
1687 apply (simp (no_asm))
1688 done
1690 lemma one_step_implies_mult_aux:
1691   "trans r ==>
1692     \<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))
1693       --> (I + K, I + J) \<in> mult r"
1694 apply (induct_tac n, auto)
1695 apply (frule size_eq_Suc_imp_eq_union, clarify)
1696 apply (rename_tac "J'", simp)
1697 apply (erule notE, auto)
1698 apply (case_tac "J' = {#}")
1699  apply (simp add: mult_def)
1700  apply (rule r_into_trancl)
1701  apply (simp add: mult1_def set_of_def, blast)
1702 txt {* Now we know @{term "J' \<noteq> {#}"}. *}
1703 apply (cut_tac M = K and P = "\<lambda>x. (x, a) \<in> r" in multiset_partition)
1704 apply (erule_tac P = "\<forall>k \<in> set_of K. ?P k" in rev_mp)
1705 apply (erule ssubst)
1706 apply (simp add: Ball_def, auto)
1707 apply (subgoal_tac
1708   "((I + {# x :# K. (x, a) \<in> r #}) + {# x :# K. (x, a) \<notin> r #},
1709     (I + {# x :# K. (x, a) \<in> r #}) + J') \<in> mult r")
1710  prefer 2
1711  apply force
1712 apply (simp (no_asm_use) add: add.assoc [symmetric] mult_def)
1713 apply (erule trancl_trans)
1714 apply (rule r_into_trancl)
1715 apply (simp add: mult1_def set_of_def)
1716 apply (rule_tac x = a in exI)
1717 apply (rule_tac x = "I + J'" in exI)
1718 apply (simp add: ac_simps)
1719 done
1721 lemma one_step_implies_mult:
1722   "trans r ==> J \<noteq> {#} ==> \<forall>k \<in> set_of K. \<exists>j \<in> set_of J. (k, j) \<in> r
1723     ==> (I + K, I + J) \<in> mult r"
1724 using one_step_implies_mult_aux by blast
1727 subsubsection {* Partial-order properties *}
1729 definition less_multiset :: "'a\<Colon>order multiset \<Rightarrow> 'a multiset \<Rightarrow> bool" (infix "<#" 50) where
1730   "M' <# M \<longleftrightarrow> (M', M) \<in> mult {(x', x). x' < x}"
1732 definition le_multiset :: "'a\<Colon>order multiset \<Rightarrow> 'a multiset \<Rightarrow> bool" (infix "<=#" 50) where
1733   "M' <=# M \<longleftrightarrow> M' <# M \<or> M' = M"
1735 notation (xsymbols) less_multiset (infix "\<subset>#" 50)
1736 notation (xsymbols) le_multiset (infix "\<subseteq>#" 50)
1738 interpretation multiset_order: order le_multiset less_multiset
1739 proof -
1740   have irrefl: "\<And>M :: 'a multiset. \<not> M \<subset># M"
1741   proof
1742     fix M :: "'a multiset"
1743     assume "M \<subset># M"
1744     then have MM: "(M, M) \<in> mult {(x, y). x < y}" by (simp add: less_multiset_def)
1745     have "trans {(x'::'a, x). x' < x}"
1746       by (rule transI) simp
1747     moreover note MM
1748     ultimately have "\<exists>I J K. M = I + J \<and> M = I + K
1749       \<and> J \<noteq> {#} \<and> (\<forall>k\<in>set_of K. \<exists>j\<in>set_of J. (k, j) \<in> {(x, y). x < y})"
1750       by (rule mult_implies_one_step)
1751     then obtain I J K where "M = I + J" and "M = I + K"
1752       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
1753     then have aux1: "K \<noteq> {#}" and aux2: "\<forall>k\<in>set_of K. \<exists>j\<in>set_of K. k < j" by auto
1754     have "finite (set_of K)" by simp
1755     moreover note aux2
1756     ultimately have "set_of K = {}"
1757       by (induct rule: finite_induct) (auto intro: order_less_trans)
1758     with aux1 show False by simp
1759   qed
1760   have trans: "\<And>K M N :: 'a multiset. K \<subset># M \<Longrightarrow> M \<subset># N \<Longrightarrow> K \<subset># N"
1761     unfolding less_multiset_def mult_def by (blast intro: trancl_trans)
1762   show "class.order (le_multiset :: 'a multiset \<Rightarrow> _) less_multiset"
1763     by default (auto simp add: le_multiset_def irrefl dest: trans)
1764 qed
1766 lemma mult_less_irrefl [elim!]: "M \<subset># (M::'a::order multiset) ==> R"
1767   by simp
1770 subsubsection {* Monotonicity of multiset union *}
1772 lemma mult1_union: "(B, D) \<in> mult1 r ==> (C + B, C + D) \<in> mult1 r"
1773 apply (unfold mult1_def)
1774 apply auto
1775 apply (rule_tac x = a in exI)
1776 apply (rule_tac x = "C + M0" in exI)
1778 done
1780 lemma union_less_mono2: "B \<subset># D ==> C + B \<subset># C + (D::'a::order multiset)"
1781 apply (unfold less_multiset_def mult_def)
1782 apply (erule trancl_induct)
1783  apply (blast intro: mult1_union)
1784 apply (blast intro: mult1_union trancl_trans)
1785 done
1787 lemma union_less_mono1: "B \<subset># D ==> B + C \<subset># D + (C::'a::order multiset)"
1788 apply (subst add.commute [of B C])
1789 apply (subst add.commute [of D C])
1790 apply (erule union_less_mono2)
1791 done
1793 lemma union_less_mono:
1794   "A \<subset># C ==> B \<subset># D ==> A + B \<subset># C + (D::'a::order multiset)"
1795   by (blast intro!: union_less_mono1 union_less_mono2 multiset_order.less_trans)
1797 interpretation multiset_order: ordered_ab_semigroup_add plus le_multiset less_multiset
1798 proof
1799 qed (auto simp add: le_multiset_def intro: union_less_mono2)
1802 subsection {* Termination proofs with multiset orders *}
1804 lemma multi_member_skip: "x \<in># XS \<Longrightarrow> x \<in># {# y #} + XS"
1805   and multi_member_this: "x \<in># {# x #} + XS"
1806   and multi_member_last: "x \<in># {# x #}"
1807   by auto
1809 definition "ms_strict = mult pair_less"
1810 definition "ms_weak = ms_strict \<union> Id"
1812 lemma ms_reduction_pair: "reduction_pair (ms_strict, ms_weak)"
1813 unfolding reduction_pair_def ms_strict_def ms_weak_def pair_less_def
1814 by (auto intro: wf_mult1 wf_trancl simp: mult_def)
1816 lemma smsI:
1817   "(set_of A, set_of B) \<in> max_strict \<Longrightarrow> (Z + A, Z + B) \<in> ms_strict"
1818   unfolding ms_strict_def
1819 by (rule one_step_implies_mult) (auto simp add: max_strict_def pair_less_def elim!:max_ext.cases)
1821 lemma wmsI:
1822   "(set_of A, set_of B) \<in> max_strict \<or> A = {#} \<and> B = {#}
1823   \<Longrightarrow> (Z + A, Z + B) \<in> ms_weak"
1824 unfolding ms_weak_def ms_strict_def
1825 by (auto simp add: pair_less_def max_strict_def elim!:max_ext.cases intro: one_step_implies_mult)
1827 inductive pw_leq
1828 where
1829   pw_leq_empty: "pw_leq {#} {#}"
1830 | pw_leq_step:  "\<lbrakk>(x,y) \<in> pair_leq; pw_leq X Y \<rbrakk> \<Longrightarrow> pw_leq ({#x#} + X) ({#y#} + Y)"
1832 lemma pw_leq_lstep:
1833   "(x, y) \<in> pair_leq \<Longrightarrow> pw_leq {#x#} {#y#}"
1834 by (drule pw_leq_step) (rule pw_leq_empty, simp)
1836 lemma pw_leq_split:
1837   assumes "pw_leq X Y"
1838   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 = {#}))"
1839   using assms
1840 proof (induct)
1841   case pw_leq_empty thus ?case by auto
1842 next
1843   case (pw_leq_step x y X Y)
1844   then obtain A B Z where
1845     [simp]: "X = A + Z" "Y = B + Z"
1846       and 1[simp]: "(set_of A, set_of B) \<in> max_strict \<or> (B = {#} \<and> A = {#})"
1847     by auto
1848   from pw_leq_step have "x = y \<or> (x, y) \<in> pair_less"
1849     unfolding pair_leq_def by auto
1850   thus ?case
1851   proof
1852     assume [simp]: "x = y"
1853     have
1854       "{#x#} + X = A + ({#y#}+Z)
1855       \<and> {#y#} + Y = B + ({#y#}+Z)
1856       \<and> ((set_of A, set_of B) \<in> max_strict \<or> (B = {#} \<and> A = {#}))"
1857       by (auto simp: ac_simps)
1858     thus ?case by (intro exI)
1859   next
1860     assume A: "(x, y) \<in> pair_less"
1861     let ?A' = "{#x#} + A" and ?B' = "{#y#} + B"
1862     have "{#x#} + X = ?A' + Z"
1863       "{#y#} + Y = ?B' + Z"
1864       by (auto simp add: ac_simps)
1865     moreover have
1866       "(set_of ?A', set_of ?B') \<in> max_strict"
1867       using 1 A unfolding max_strict_def
1868       by (auto elim!: max_ext.cases)
1869     ultimately show ?thesis by blast
1870   qed
1871 qed
1873 lemma
1874   assumes pwleq: "pw_leq Z Z'"
1875   shows ms_strictI: "(set_of A, set_of B) \<in> max_strict \<Longrightarrow> (Z + A, Z' + B) \<in> ms_strict"
1876   and   ms_weakI1:  "(set_of A, set_of B) \<in> max_strict \<Longrightarrow> (Z + A, Z' + B) \<in> ms_weak"
1877   and   ms_weakI2:  "(Z + {#}, Z' + {#}) \<in> ms_weak"
1878 proof -
1879   from pw_leq_split[OF pwleq]
1880   obtain A' B' Z''
1881     where [simp]: "Z = A' + Z''" "Z' = B' + Z''"
1882     and mx_or_empty: "(set_of A', set_of B') \<in> max_strict \<or> (A' = {#} \<and> B' = {#})"
1883     by blast
1884   {
1885     assume max: "(set_of A, set_of B) \<in> max_strict"
1886     from mx_or_empty
1887     have "(Z'' + (A + A'), Z'' + (B + B')) \<in> ms_strict"
1888     proof
1889       assume max': "(set_of A', set_of B') \<in> max_strict"
1890       with max have "(set_of (A + A'), set_of (B + B')) \<in> max_strict"
1891         by (auto simp: max_strict_def intro: max_ext_additive)
1892       thus ?thesis by (rule smsI)
1893     next
1894       assume [simp]: "A' = {#} \<and> B' = {#}"
1895       show ?thesis by (rule smsI) (auto intro: max)
1896     qed
1897     thus "(Z + A, Z' + B) \<in> ms_strict" by (simp add:ac_simps)
1898     thus "(Z + A, Z' + B) \<in> ms_weak" by (simp add: ms_weak_def)
1899   }
1900   from mx_or_empty
1901   have "(Z'' + A', Z'' + B') \<in> ms_weak" by (rule wmsI)
1902   thus "(Z + {#}, Z' + {#}) \<in> ms_weak" by (simp add:ac_simps)
1903 qed
1905 lemma empty_neutral: "{#} + x = x" "x + {#} = x"
1906 and nonempty_plus: "{# x #} + rs \<noteq> {#}"
1907 and nonempty_single: "{# x #} \<noteq> {#}"
1908 by auto
1910 setup {*
1911 let
1912   fun msetT T = Type (@{type_name multiset}, [T]);
1914   fun mk_mset T [] = Const (@{const_abbrev Mempty}, msetT T)
1915     | mk_mset T [x] = Const (@{const_name single}, T --> msetT T) \$ x
1916     | mk_mset T (x :: xs) =
1917           Const (@{const_name plus}, msetT T --> msetT T --> msetT T) \$
1918                 mk_mset T [x] \$ mk_mset T xs
1920   fun mset_member_tac m i =
1921       (if m <= 0 then
1922            rtac @{thm multi_member_this} i ORELSE rtac @{thm multi_member_last} i
1923        else
1924            rtac @{thm multi_member_skip} i THEN mset_member_tac (m - 1) i)
1926   val mset_nonempty_tac =
1927       rtac @{thm nonempty_plus} ORELSE' rtac @{thm nonempty_single}
1929   val regroup_munion_conv =
1930       Function_Lib.regroup_conv @{const_abbrev Mempty} @{const_name plus}
1931         (map (fn t => t RS eq_reflection) (@{thms ac_simps} @ @{thms empty_neutral}))
1933   fun unfold_pwleq_tac i =
1934     (rtac @{thm pw_leq_step} i THEN (fn st => unfold_pwleq_tac (i + 1) st))
1935       ORELSE (rtac @{thm pw_leq_lstep} i)
1936       ORELSE (rtac @{thm pw_leq_empty} i)
1938   val set_of_simps = [@{thm set_of_empty}, @{thm set_of_single}, @{thm set_of_union},
1939                       @{thm Un_insert_left}, @{thm Un_empty_left}]
1940 in
1941   ScnpReconstruct.multiset_setup (ScnpReconstruct.Multiset
1942   {
1943     msetT=msetT, mk_mset=mk_mset, mset_regroup_conv=regroup_munion_conv,
1944     mset_member_tac=mset_member_tac, mset_nonempty_tac=mset_nonempty_tac,
1945     mset_pwleq_tac=unfold_pwleq_tac, set_of_simps=set_of_simps,
1946     smsI'= @{thm ms_strictI}, wmsI2''= @{thm ms_weakI2}, wmsI1= @{thm ms_weakI1},
1947     reduction_pair= @{thm ms_reduction_pair}
1948   })
1949 end
1950 *}
1953 subsection {* Legacy theorem bindings *}
1955 lemmas multi_count_eq = multiset_eq_iff [symmetric]
1957 lemma union_commute: "M + N = N + (M::'a multiset)"
1958   by (fact add.commute)
1960 lemma union_assoc: "(M + N) + K = M + (N + (K::'a multiset))"
1961   by (fact add.assoc)
1963 lemma union_lcomm: "M + (N + K) = N + (M + (K::'a multiset))"
1964   by (fact add.left_commute)
1966 lemmas union_ac = union_assoc union_commute union_lcomm
1968 lemma union_right_cancel: "M + K = N + K \<longleftrightarrow> M = (N::'a multiset)"
1969   by (fact add_right_cancel)
1971 lemma union_left_cancel: "K + M = K + N \<longleftrightarrow> M = (N::'a multiset)"
1972   by (fact add_left_cancel)
1974 lemma multi_union_self_other_eq: "(A::'a multiset) + X = A + Y \<Longrightarrow> X = Y"
1975   by (fact add_imp_eq)
1977 lemma mset_less_trans: "(M::'a multiset) < K \<Longrightarrow> K < N \<Longrightarrow> M < N"
1978   by (fact order_less_trans)
1980 lemma multiset_inter_commute: "A #\<inter> B = B #\<inter> A"
1981   by (fact inf.commute)
1983 lemma multiset_inter_assoc: "A #\<inter> (B #\<inter> C) = A #\<inter> B #\<inter> C"
1984   by (fact inf.assoc [symmetric])
1986 lemma multiset_inter_left_commute: "A #\<inter> (B #\<inter> C) = B #\<inter> (A #\<inter> C)"
1987   by (fact inf.left_commute)
1989 lemmas multiset_inter_ac =
1990   multiset_inter_commute
1991   multiset_inter_assoc
1992   multiset_inter_left_commute
1994 lemma mult_less_not_refl:
1995   "\<not> M \<subset># (M::'a::order multiset)"
1996   by (fact multiset_order.less_irrefl)
1998 lemma mult_less_trans:
1999   "K \<subset># M ==> M \<subset># N ==> K \<subset># (N::'a::order multiset)"
2000   by (fact multiset_order.less_trans)
2002 lemma mult_less_not_sym:
2003   "M \<subset># N ==> \<not> N \<subset># (M::'a::order multiset)"
2004   by (fact multiset_order.less_not_sym)
2006 lemma mult_less_asym:
2007   "M \<subset># N ==> (\<not> P ==> N \<subset># (M::'a::order multiset)) ==> P"
2008   by (fact multiset_order.less_asym)
2010 ML {*
2011 fun multiset_postproc _ maybe_name all_values (T as Type (_, [elem_T]))
2012                       (Const _ \$ t') =
2013     let
2014       val (maybe_opt, ps) =
2015         Nitpick_Model.dest_plain_fun t' ||> op ~~
2016         ||> map (apsnd (snd o HOLogic.dest_number))
2017       fun elems_for t =
2018         case AList.lookup (op =) ps t of
2019           SOME n => replicate n t
2020         | NONE => [Const (maybe_name, elem_T --> elem_T) \$ t]
2021     in
2022       case maps elems_for (all_values elem_T) @
2023            (if maybe_opt then [Const (Nitpick_Model.unrep (), elem_T)]
2024             else []) of
2025         [] => Const (@{const_name zero_class.zero}, T)
2026       | ts => foldl1 (fn (t1, t2) =>
2027                          Const (@{const_name plus_class.plus}, T --> T --> T)
2028                          \$ t1 \$ t2)
2029                      (map (curry (op \$) (Const (@{const_name single},
2030                                                 elem_T --> T))) ts)
2031     end
2032   | multiset_postproc _ _ _ _ t = t
2033 *}
2035 declaration {*
2036 Nitpick_Model.register_term_postprocessor @{typ "'a multiset"}
2037     multiset_postproc
2038 *}
2040 hide_const (open) fold
2043 subsection {* Naive implementation using lists *}
2045 code_datatype multiset_of
2047 lemma [code]:
2048   "{#} = multiset_of []"
2049   by simp
2051 lemma [code]:
2052   "{#x#} = multiset_of [x]"
2053   by simp
2055 lemma union_code [code]:
2056   "multiset_of xs + multiset_of ys = multiset_of (xs @ ys)"
2057   by simp
2059 lemma [code]:
2060   "image_mset f (multiset_of xs) = multiset_of (map f xs)"
2061   by (simp add: multiset_of_map)
2063 lemma [code]:
2064   "Multiset.filter f (multiset_of xs) = multiset_of (filter f xs)"
2065   by (simp add: multiset_of_filter)
2067 lemma [code]:
2068   "multiset_of xs - multiset_of ys = multiset_of (fold remove1 ys xs)"
2069   by (rule sym, induct ys arbitrary: xs) (simp_all add: diff_add diff_right_commute)
2071 lemma [code]:
2072   "multiset_of xs #\<inter> multiset_of ys =
2073     multiset_of (snd (fold (\<lambda>x (ys, zs).
2074       if x \<in> set ys then (remove1 x ys, x # zs) else (ys, zs)) xs (ys, [])))"
2075 proof -
2076   have "\<And>zs. multiset_of (snd (fold (\<lambda>x (ys, zs).
2077     if x \<in> set ys then (remove1 x ys, x # zs) else (ys, zs)) xs (ys, zs))) =
2078       (multiset_of xs #\<inter> multiset_of ys) + multiset_of zs"
2079     by (induct xs arbitrary: ys)
2081   then show ?thesis by simp
2082 qed
2084 lemma [code]:
2085   "multiset_of xs #\<union> multiset_of ys =
2086     multiset_of (split append (fold (\<lambda>x (ys, zs). (remove1 x ys, x # zs)) xs (ys, [])))"
2087 proof -
2088   have "\<And>zs. multiset_of (split append (fold (\<lambda>x (ys, zs). (remove1 x ys, x # zs)) xs (ys, zs))) =
2089       (multiset_of xs #\<union> multiset_of ys) + multiset_of zs"
2090     by (induct xs arbitrary: ys) (simp_all add: multiset_eq_iff)
2091   then show ?thesis by simp
2092 qed
2094 lemma [code_unfold]:
2095   "x \<in># multiset_of xs \<longleftrightarrow> x \<in> set xs"
2096   by (simp add: in_multiset_of)
2098 lemma [code]:
2099   "count (multiset_of xs) x = fold (\<lambda>y. if x = y then Suc else id) xs 0"
2100 proof -
2101   have "\<And>n. fold (\<lambda>y. if x = y then Suc else id) xs n = count (multiset_of xs) x + n"
2102     by (induct xs) simp_all
2103   then show ?thesis by simp
2104 qed
2106 lemma [code]:
2107   "set_of (multiset_of xs) = set xs"
2108   by simp
2110 lemma [code]:
2111   "sorted_list_of_multiset (multiset_of xs) = sort xs"
2112   by (induct xs) simp_all
2114 lemma [code]: -- {* not very efficient, but representation-ignorant! *}
2115   "multiset_of_set A = multiset_of (sorted_list_of_set A)"
2116   apply (cases "finite A")
2117   apply simp_all
2118   apply (induct A rule: finite_induct)
2119   apply (simp_all add: union_commute)
2120   done
2122 lemma [code]:
2123   "mcard (multiset_of xs) = length xs"
2124   by (simp add: mcard_multiset_of)
2126 fun ms_lesseq_impl :: "'a list \<Rightarrow> 'a list \<Rightarrow> bool option" where
2127   "ms_lesseq_impl [] ys = Some (ys \<noteq> [])"
2128 | "ms_lesseq_impl (Cons x xs) ys = (case List.extract (op = x) ys of
2129      None \<Rightarrow> None
2130    | Some (ys1,_,ys2) \<Rightarrow> ms_lesseq_impl xs (ys1 @ ys2))"
2132 lemma ms_lesseq_impl: "(ms_lesseq_impl xs ys = None \<longleftrightarrow> \<not> multiset_of xs \<le> multiset_of ys) \<and>
2133   (ms_lesseq_impl xs ys = Some True \<longleftrightarrow> multiset_of xs < multiset_of ys) \<and>
2134   (ms_lesseq_impl xs ys = Some False \<longrightarrow> multiset_of xs = multiset_of ys)"
2135 proof (induct xs arbitrary: ys)
2136   case (Nil ys)
2137   show ?case by (auto simp: mset_less_empty_nonempty)
2138 next
2139   case (Cons x xs ys)
2140   show ?case
2141   proof (cases "List.extract (op = x) ys")
2142     case None
2143     hence x: "x \<notin> set ys" by (simp add: extract_None_iff)
2144     {
2145       assume "multiset_of (x # xs) \<le> multiset_of ys"
2146       from set_of_mono[OF this] x have False by simp
2147     } note nle = this
2148     moreover
2149     {
2150       assume "multiset_of (x # xs) < multiset_of ys"
2151       hence "multiset_of (x # xs) \<le> multiset_of ys" by auto
2152       from nle[OF this] have False .
2153     }
2154     ultimately show ?thesis using None by auto
2155   next
2156     case (Some res)
2157     obtain ys1 y ys2 where res: "res = (ys1,y,ys2)" by (cases res, auto)
2158     note Some = Some[unfolded res]
2159     from extract_SomeE[OF Some] have "ys = ys1 @ x # ys2" by simp
2160     hence id: "multiset_of ys = multiset_of (ys1 @ ys2) + {#x#}"
2161       by (auto simp: ac_simps)
2162     show ?thesis unfolding ms_lesseq_impl.simps
2163       unfolding Some option.simps split
2164       unfolding id
2165       using Cons[of "ys1 @ ys2"]
2166       unfolding mset_le_def mset_less_def by auto
2167   qed
2168 qed
2170 lemma [code]: "multiset_of xs \<le> multiset_of ys \<longleftrightarrow> ms_lesseq_impl xs ys \<noteq> None"
2171   using ms_lesseq_impl[of xs ys] by (cases "ms_lesseq_impl xs ys", auto)
2173 lemma [code]: "multiset_of xs < multiset_of ys \<longleftrightarrow> ms_lesseq_impl xs ys = Some True"
2174   using ms_lesseq_impl[of xs ys] by (cases "ms_lesseq_impl xs ys", auto)
2176 instantiation multiset :: (equal) equal
2177 begin
2179 definition
2180   [code del]: "HOL.equal A (B :: 'a multiset) \<longleftrightarrow> A = B"
2181 lemma [code]: "HOL.equal (multiset_of xs) (multiset_of ys) \<longleftrightarrow> ms_lesseq_impl xs ys = Some False"
2182   unfolding equal_multiset_def
2183   using ms_lesseq_impl[of xs ys] by (cases "ms_lesseq_impl xs ys", auto)
2185 instance
2186   by default (simp add: equal_multiset_def)
2187 end
2189 lemma [code]:
2190   "msetsum (multiset_of xs) = listsum xs"
2191   by (induct xs) (simp_all add: add.commute)
2193 lemma [code]:
2194   "msetprod (multiset_of xs) = fold times xs 1"
2195 proof -
2196   have "\<And>x. fold times xs x = msetprod (multiset_of xs) * x"
2197     by (induct xs) (simp_all add: mult.assoc)
2198   then show ?thesis by simp
2199 qed
2201 lemma [code]:
2202   "size = mcard"
2203   by (fact size_eq_mcard)
2205 text {*
2206   Exercise for the casual reader: add implementations for @{const le_multiset}
2207   and @{const less_multiset} (multiset order).
2208 *}
2210 text {* Quickcheck generators *}
2212 definition (in term_syntax)
2213   msetify :: "'a\<Colon>typerep list \<times> (unit \<Rightarrow> Code_Evaluation.term)
2214     \<Rightarrow> 'a multiset \<times> (unit \<Rightarrow> Code_Evaluation.term)" where
2215   [code_unfold]: "msetify xs = Code_Evaluation.valtermify multiset_of {\<cdot>} xs"
2217 notation fcomp (infixl "\<circ>>" 60)
2218 notation scomp (infixl "\<circ>\<rightarrow>" 60)
2220 instantiation multiset :: (random) random
2221 begin
2223 definition
2224   "Quickcheck_Random.random i = Quickcheck_Random.random i \<circ>\<rightarrow> (\<lambda>xs. Pair (msetify xs))"
2226 instance ..
2228 end
2230 no_notation fcomp (infixl "\<circ>>" 60)
2231 no_notation scomp (infixl "\<circ>\<rightarrow>" 60)
2233 instantiation multiset :: (full_exhaustive) full_exhaustive
2234 begin
2236 definition full_exhaustive_multiset :: "('a multiset \<times> (unit \<Rightarrow> term) \<Rightarrow> (bool \<times> term list) option) \<Rightarrow> natural \<Rightarrow> (bool \<times> term list) option"
2237 where
2238   "full_exhaustive_multiset f i = Quickcheck_Exhaustive.full_exhaustive (\<lambda>xs. f (msetify xs)) i"
2240 instance ..
2242 end
2244 hide_const (open) msetify
2247 subsection {* BNF setup *}
2249 definition rel_mset where
2250   "rel_mset R X Y \<longleftrightarrow> (\<exists>xs ys. multiset_of xs = X \<and> multiset_of ys = Y \<and> list_all2 R xs ys)"
2252 lemma multiset_of_zip_take_Cons_drop_twice:
2253   assumes "length xs = length ys" "j \<le> length xs"
2254   shows "multiset_of (zip (take j xs @ x # drop j xs) (take j ys @ y # drop j ys)) =
2255     multiset_of (zip xs ys) + {#(x, y)#}"
2256 using assms
2257 proof (induct xs ys arbitrary: x y j rule: list_induct2)
2258   case Nil
2259   thus ?case
2260     by simp
2261 next
2262   case (Cons x xs y ys)
2263   thus ?case
2264   proof (cases "j = 0")
2265     case True
2266     thus ?thesis
2267       by simp
2268   next
2269     case False
2270     then obtain k where k: "j = Suc k"
2271       by (case_tac j) simp
2272     hence "k \<le> length xs"
2273       using Cons.prems by auto
2274     hence "multiset_of (zip (take k xs @ x # drop k xs) (take k ys @ y # drop k ys)) =
2275       multiset_of (zip xs ys) + {#(x, y)#}"
2276       by (rule Cons.hyps(2))
2277     thus ?thesis
2278       unfolding k by (auto simp: add.commute union_lcomm)
2279   qed
2280 qed
2282 lemma ex_multiset_of_zip_left:
2283   assumes "length xs = length ys" "multiset_of xs' = multiset_of xs"
2284   shows "\<exists>ys'. length ys' = length xs' \<and> multiset_of (zip xs' ys') = multiset_of (zip xs ys)"
2285 using assms
2286 proof (induct xs ys arbitrary: xs' rule: list_induct2)
2287   case Nil
2288   thus ?case
2289     by auto
2290 next
2291   case (Cons x xs y ys xs')
2292   obtain j where j_len: "j < length xs'" and nth_j: "xs' ! j = x"
2293   proof -
2294     assume "\<And>j. \<lbrakk>j < length xs'; xs' ! j = x\<rbrakk> \<Longrightarrow> ?thesis"
2295     moreover have "\<And>k m n. (m\<Colon>nat) + n < m + k \<or> \<not> n < k" by linarith
2296     moreover have "\<And>n a as. n - n < length (a # as) \<or> n < n"
2299     moreover have "\<not> length xs' < length xs'" by blast
2300     ultimately show ?thesis
2301       by (metis (no_types) Cons.prems Nat.add_diff_inverse diff_add_inverse2 length_append
2302         less_diff_conv list.set_intros(1) multiset_of_eq_setD nth_append_length split_list)
2303   qed
2305   def xsa \<equiv> "take j xs' @ drop (Suc j) xs'"
2306   have "multiset_of xs' = {#x#} + multiset_of xsa"
2307     unfolding xsa_def using j_len nth_j
2308     by (metis (no_types) ab_semigroup_add_class.add_ac(1) append_take_drop_id drop_Suc_conv_tl
2309       multiset_of.simps(2) union_code union_commute)
2310   hence ms_x: "multiset_of xsa = multiset_of xs"
2311     by (metis Cons.prems add.commute add_right_imp_eq multiset_of.simps(2))
2312   then obtain ysa where
2313     len_a: "length ysa = length xsa" and ms_a: "multiset_of (zip xsa ysa) = multiset_of (zip xs ys)"
2314     using Cons.hyps(2) by blast
2316   def ys' \<equiv> "take j ysa @ y # drop j ysa"
2317   have xs': "xs' = take j xsa @ x # drop j xsa"
2318     using ms_x j_len nth_j Cons.prems xsa_def
2319     by (metis append_eq_append_conv append_take_drop_id diff_Suc_Suc drop_Suc_conv_tl length_Cons
2320       length_drop mcard_multiset_of)
2321   have j_len': "j \<le> length xsa"
2322     using j_len xs' xsa_def
2323     by (metis add_Suc_right append_take_drop_id length_Cons length_append less_eq_Suc_le not_less)
2324   have "length ys' = length xs'"
2325     unfolding ys'_def using Cons.prems len_a ms_x
2326     by (metis add_Suc_right append_take_drop_id length_Cons length_append multiset_of_eq_length)
2327   moreover have "multiset_of (zip xs' ys') = multiset_of (zip (x # xs) (y # ys))"
2328     unfolding xs' ys'_def
2329     by (rule trans[OF multiset_of_zip_take_Cons_drop_twice])
2330       (auto simp: len_a ms_a j_len' add.commute)
2331   ultimately show ?case
2332     by blast
2333 qed
2335 lemma list_all2_reorder_left_invariance:
2336   assumes rel: "list_all2 R xs ys" and ms_x: "multiset_of xs' = multiset_of xs"
2337   shows "\<exists>ys'. list_all2 R xs' ys' \<and> multiset_of ys' = multiset_of ys"
2338 proof -
2339   have len: "length xs = length ys"
2340     using rel list_all2_conv_all_nth by auto
2341   obtain ys' where
2342     len': "length xs' = length ys'" and ms_xy: "multiset_of (zip xs' ys') = multiset_of (zip xs ys)"
2343     using len ms_x by (metis ex_multiset_of_zip_left)
2344   have "list_all2 R xs' ys'"
2345     using assms(1) len' ms_xy unfolding list_all2_iff by (blast dest: multiset_of_eq_setD)
2346   moreover have "multiset_of ys' = multiset_of ys"
2347     using len len' ms_xy map_snd_zip multiset_of_map by metis
2348   ultimately show ?thesis
2349     by blast
2350 qed
2352 lemma ex_multiset_of: "\<exists>xs. multiset_of xs = X"
2353   by (induct X) (simp, metis multiset_of.simps(2))
2355 bnf "'a multiset"
2356   map: image_mset
2357   sets: set_of
2358   bd: natLeq
2359   wits: "{#}"
2360   rel: rel_mset
2361 proof -
2362   show "image_mset id = id"
2363     by (rule image_mset.id)
2364 next
2365   show "\<And>f g. image_mset (g \<circ> f) = image_mset g \<circ> image_mset f"
2366     unfolding comp_def by (rule ext) (simp add: image_mset.compositionality comp_def)
2367 next
2368   fix X :: "'a multiset"
2369   show "\<And>f g. (\<And>z. z \<in> set_of X \<Longrightarrow> f z = g z) \<Longrightarrow> image_mset f X = image_mset g X"
2370     by (induct X, (simp (no_asm))+,
2371       metis One_nat_def Un_iff count_single mem_set_of_iff set_of_union zero_less_Suc)
2372 next
2373   show "\<And>f. set_of \<circ> image_mset f = op ` f \<circ> set_of"
2374     by auto
2375 next
2376   show "card_order natLeq"
2377     by (rule natLeq_card_order)
2378 next
2379   show "BNF_Cardinal_Arithmetic.cinfinite natLeq"
2380     by (rule natLeq_cinfinite)
2381 next
2382   show "\<And>X. ordLeq3 (card_of (set_of X)) natLeq"
2383     by transfer
2384       (auto intro!: ordLess_imp_ordLeq simp: finite_iff_ordLess_natLeq[symmetric] multiset_def)
2385 next
2386   show "\<And>R S. rel_mset R OO rel_mset S \<le> rel_mset (R OO S)"
2387     unfolding rel_mset_def[abs_def] OO_def
2388     apply clarify
2389     apply (rename_tac X Z Y xs ys' ys zs)
2390     apply (drule_tac xs = ys' and ys = zs and xs' = ys in list_all2_reorder_left_invariance)
2391     by (auto intro: list_all2_trans)
2392 next
2393   show "\<And>R. rel_mset R =
2394     (BNF_Def.Grp {x. set_of x \<subseteq> {(x, y). R x y}} (image_mset fst))\<inverse>\<inverse> OO
2395     BNF_Def.Grp {x. set_of x \<subseteq> {(x, y). R x y}} (image_mset snd)"
2396     unfolding rel_mset_def[abs_def] BNF_Def.Grp_def OO_def
2397     apply (rule ext)+
2398     apply auto
2399      apply (rule_tac x = "multiset_of (zip xs ys)" in exI)
2400      apply auto
2401         apply (metis list_all2_lengthD map_fst_zip multiset_of_map)
2402        apply (auto simp: list_all2_iff)
2403       apply (metis list_all2_lengthD map_snd_zip multiset_of_map)
2404      apply (auto simp: list_all2_iff)
2405     apply (rename_tac XY)
2406     apply (cut_tac X = XY in ex_multiset_of)
2407     apply (erule exE)
2408     apply (rename_tac xys)
2409     apply (rule_tac x = "map fst xys" in exI)
2410     apply (auto simp: multiset_of_map)
2411     apply (rule_tac x = "map snd xys" in exI)
2412     by (auto simp: multiset_of_map list_all2I subset_eq zip_map_fst_snd)
2413 next
2414   show "\<And>z. z \<in> set_of {#} \<Longrightarrow> False"
2415     by auto
2416 qed
2418 inductive rel_mset' where
2419   Zero[intro]: "rel_mset' R {#} {#}"
2420 | Plus[intro]: "\<lbrakk>R a b; rel_mset' R M N\<rbrakk> \<Longrightarrow> rel_mset' R (M + {#a#}) (N + {#b#})"
2422 lemma rel_mset_Zero: "rel_mset R {#} {#}"
2423 unfolding rel_mset_def Grp_def by auto
2425 declare multiset.count[simp]
2426 declare Abs_multiset_inverse[simp]
2427 declare multiset.count_inverse[simp]
2428 declare union_preserves_multiset[simp]
2430 lemma rel_mset_Plus:
2431 assumes ab: "R a b" and MN: "rel_mset R M N"
2432 shows "rel_mset R (M + {#a#}) (N + {#b#})"
2433 proof-
2434   {fix y assume "R a b" and "set_of y \<subseteq> {(x, y). R x y}"
2435    hence "\<exists>ya. image_mset fst y + {#a#} = image_mset fst ya \<and>
2436                image_mset snd y + {#b#} = image_mset snd ya \<and>
2437                set_of ya \<subseteq> {(x, y). R x y}"
2438    apply(intro exI[of _ "y + {#(a,b)#}"]) by auto
2439   }
2440   thus ?thesis
2441   using assms
2442   unfolding multiset.rel_compp_Grp Grp_def by blast
2443 qed
2445 lemma rel_mset'_imp_rel_mset:
2446 "rel_mset' R M N \<Longrightarrow> rel_mset R M N"
2447 apply(induct rule: rel_mset'.induct)
2448 using rel_mset_Zero rel_mset_Plus by auto
2450 lemma mcard_image_mset[simp]: "mcard (image_mset f M) = mcard M"
2451   unfolding size_eq_mcard[symmetric] by (rule size_image_mset)
2453 lemma rel_mset_mcard:
2454   assumes "rel_mset R M N"
2455   shows "mcard M = mcard N"
2456 using assms unfolding multiset.rel_compp_Grp Grp_def by auto
2459 assumes empty: "P {#} {#}"
2460 and addL: "\<And>M N a. P M N \<Longrightarrow> P (M + {#a#}) N"
2461 and addR: "\<And>M N a. P M N \<Longrightarrow> P M (N + {#a#})"
2462 shows "P M N"
2463 apply(induct N rule: multiset_induct)
2464   apply(induct M rule: multiset_induct, rule empty, erule addL)
2465   apply(induct M rule: multiset_induct, erule addR, erule addR)
2466 done
2468 lemma multiset_induct2_mcard[consumes 1, case_names empty add]:
2469 assumes c: "mcard M = mcard N"
2470 and empty: "P {#} {#}"
2471 and add: "\<And>M N a b. P M N \<Longrightarrow> P (M + {#a#}) (N + {#b#})"
2472 shows "P M N"
2473 using c proof(induct M arbitrary: N rule: measure_induct_rule[of mcard])
2474   case (less M)  show ?case
2475   proof(cases "M = {#}")
2476     case True hence "N = {#}" using less.prems by auto
2477     thus ?thesis using True empty by auto
2478   next
2479     case False then obtain M1 a where M: "M = M1 + {#a#}" by (metis multi_nonempty_split)
2480     have "N \<noteq> {#}" using False less.prems by auto
2481     then obtain N1 b where N: "N = N1 + {#b#}" by (metis multi_nonempty_split)
2482     have "mcard M1 = mcard N1" using less.prems unfolding M N by auto
2483     thus ?thesis using M N less.hyps add by auto
2484   qed
2485 qed
2487 lemma msed_map_invL:
2488 assumes "image_mset f (M + {#a#}) = N"
2489 shows "\<exists>N1. N = N1 + {#f a#} \<and> image_mset f M = N1"
2490 proof-
2491   have "f a \<in># N"
2492   using assms multiset.set_map[of f "M + {#a#}"] by auto
2493   then obtain N1 where N: "N = N1 + {#f a#}" using multi_member_split by metis
2494   have "image_mset f M = N1" using assms unfolding N by simp
2495   thus ?thesis using N by blast
2496 qed
2498 lemma msed_map_invR:
2499 assumes "image_mset f M = N + {#b#}"
2500 shows "\<exists>M1 a. M = M1 + {#a#} \<and> f a = b \<and> image_mset f M1 = N"
2501 proof-
2502   obtain a where a: "a \<in># M" and fa: "f a = b"
2503   using multiset.set_map[of f M] unfolding assms
2504   by (metis image_iff mem_set_of_iff union_single_eq_member)
2505   then obtain M1 where M: "M = M1 + {#a#}" using multi_member_split by metis
2506   have "image_mset f M1 = N" using assms unfolding M fa[symmetric] by simp
2507   thus ?thesis using M fa by blast
2508 qed
2510 lemma msed_rel_invL:
2511 assumes "rel_mset R (M + {#a#}) N"
2512 shows "\<exists>N1 b. N = N1 + {#b#} \<and> R a b \<and> rel_mset R M N1"
2513 proof-
2514   obtain K where KM: "image_mset fst K = M + {#a#}"
2515   and KN: "image_mset snd K = N" and sK: "set_of K \<subseteq> {(a, b). R a b}"
2516   using assms
2517   unfolding multiset.rel_compp_Grp Grp_def by auto
2518   obtain K1 ab where K: "K = K1 + {#ab#}" and a: "fst ab = a"
2519   and K1M: "image_mset fst K1 = M" using msed_map_invR[OF KM] by auto
2520   obtain N1 where N: "N = N1 + {#snd ab#}" and K1N1: "image_mset snd K1 = N1"
2521   using msed_map_invL[OF KN[unfolded K]] by auto
2522   have Rab: "R a (snd ab)" using sK a unfolding K by auto
2523   have "rel_mset R M N1" using sK K1M K1N1
2524   unfolding K multiset.rel_compp_Grp Grp_def by auto
2525   thus ?thesis using N Rab by auto
2526 qed
2528 lemma msed_rel_invR:
2529 assumes "rel_mset R M (N + {#b#})"
2530 shows "\<exists>M1 a. M = M1 + {#a#} \<and> R a b \<and> rel_mset R M1 N"
2531 proof-
2532   obtain K where KN: "image_mset snd K = N + {#b#}"
2533   and KM: "image_mset fst K = M" and sK: "set_of K \<subseteq> {(a, b). R a b}"
2534   using assms
2535   unfolding multiset.rel_compp_Grp Grp_def by auto
2536   obtain K1 ab where K: "K = K1 + {#ab#}" and b: "snd ab = b"
2537   and K1N: "image_mset snd K1 = N" using msed_map_invR[OF KN] by auto
2538   obtain M1 where M: "M = M1 + {#fst ab#}" and K1M1: "image_mset fst K1 = M1"
2539   using msed_map_invL[OF KM[unfolded K]] by auto
2540   have Rab: "R (fst ab) b" using sK b unfolding K by auto
2541   have "rel_mset R M1 N" using sK K1N K1M1
2542   unfolding K multiset.rel_compp_Grp Grp_def by auto
2543   thus ?thesis using M Rab by auto
2544 qed
2546 lemma rel_mset_imp_rel_mset':
2547 assumes "rel_mset R M N"
2548 shows "rel_mset' R M N"
2549 using assms proof(induct M arbitrary: N rule: measure_induct_rule[of mcard])
2550   case (less M)
2551   have c: "mcard M = mcard N" using rel_mset_mcard[OF less.prems] .
2552   show ?case
2553   proof(cases "M = {#}")
2554     case True hence "N = {#}" using c by simp
2555     thus ?thesis using True rel_mset'.Zero by auto
2556   next
2557     case False then obtain M1 a where M: "M = M1 + {#a#}" by (metis multi_nonempty_split)
2558     obtain N1 b where N: "N = N1 + {#b#}" and R: "R a b" and ms: "rel_mset R M1 N1"
2559     using msed_rel_invL[OF less.prems[unfolded M]] by auto
2560     have "rel_mset' R M1 N1" using less.hyps[of M1 N1] ms unfolding M by simp
2561     thus ?thesis using rel_mset'.Plus[of R a b, OF R] unfolding M N by simp
2562   qed
2563 qed
2565 lemma rel_mset_rel_mset':
2566 "rel_mset R M N = rel_mset' R M N"
2567 using rel_mset_imp_rel_mset' rel_mset'_imp_rel_mset by auto
2569 (* The main end product for rel_mset: inductive characterization *)
2570 theorems rel_mset_induct[case_names empty add, induct pred: rel_mset] =
2571          rel_mset'.induct[unfolded rel_mset_rel_mset'[symmetric]]
2574 subsection {* Size setup *}
2576 lemma multiset_size_o_map: "size_multiset g \<circ> image_mset f = size_multiset (g \<circ> f)"
2577   unfolding o_apply by (rule ext) (induct_tac, auto)
2579 setup {*
2580 BNF_LFP_Size.register_size_global @{type_name multiset} @{const_name size_multiset}
2581   @{thms size_multiset_empty size_multiset_single size_multiset_union size_empty size_single
2582     size_union}
2583   @{thms multiset_size_o_map}
2584 *}
2586 hide_const (open) wcount
2588 end