src/HOL/Library/Multiset.thy
 author Christian Sternagel Wed Aug 29 12:23:14 2012 +0900 (2012-08-29) changeset 49083 01081bca31b6 parent 48040 4caf6cd063be child 49388 1ffd5a055acf permissions -rw-r--r--
dropped ord and bot instance for list prefixes (use locale interpretation instead, which allows users to decide what order to use on lists)
1 (*  Title:      HOL/Library/Multiset.thy
2     Author:     Tobias Nipkow, Markus Wenzel, Lawrence C Paulson, Norbert Voelker
3 *)
5 header {* (Finite) multisets *}
7 theory Multiset
8 imports Main DAList
9 begin
11 subsection {* The type of multisets *}
13 definition "multiset = {f :: 'a => nat. finite {x. f x > 0}}"
15 typedef (open) 'a multiset = "multiset :: ('a => nat) set"
16   morphisms count Abs_multiset
17   unfolding multiset_def
18 proof
19   show "(\<lambda>x. 0::nat) \<in> {f. finite {x. f x > 0}}" by simp
20 qed
22 setup_lifting type_definition_multiset
24 abbreviation Melem :: "'a => 'a multiset => bool"  ("(_/ :# _)" [50, 51] 50) where
25   "a :# M == 0 < count M a"
27 notation (xsymbols)
28   Melem (infix "\<in>#" 50)
30 lemma multiset_eq_iff:
31   "M = N \<longleftrightarrow> (\<forall>a. count M a = count N a)"
32   by (simp only: count_inject [symmetric] fun_eq_iff)
34 lemma multiset_eqI:
35   "(\<And>x. count A x = count B x) \<Longrightarrow> A = B"
36   using multiset_eq_iff by auto
38 text {*
39  \medskip Preservation of the representing set @{term multiset}.
40 *}
42 lemma const0_in_multiset:
43   "(\<lambda>a. 0) \<in> multiset"
44   by (simp add: multiset_def)
46 lemma only1_in_multiset:
47   "(\<lambda>b. if b = a then n else 0) \<in> multiset"
48   by (simp add: multiset_def)
50 lemma union_preserves_multiset:
51   "M \<in> multiset \<Longrightarrow> N \<in> multiset \<Longrightarrow> (\<lambda>a. M a + N a) \<in> multiset"
52   by (simp add: multiset_def)
54 lemma diff_preserves_multiset:
55   assumes "M \<in> multiset"
56   shows "(\<lambda>a. M a - N a) \<in> multiset"
57 proof -
58   have "{x. N x < M x} \<subseteq> {x. 0 < M x}"
59     by auto
60   with assms show ?thesis
61     by (auto simp add: multiset_def intro: finite_subset)
62 qed
64 lemma filter_preserves_multiset:
65   assumes "M \<in> multiset"
66   shows "(\<lambda>x. if P x then M x else 0) \<in> multiset"
67 proof -
68   have "{x. (P x \<longrightarrow> 0 < M x) \<and> P x} \<subseteq> {x. 0 < M x}"
69     by auto
70   with assms show ?thesis
71     by (auto simp add: multiset_def intro: finite_subset)
72 qed
74 lemmas in_multiset = const0_in_multiset only1_in_multiset
75   union_preserves_multiset diff_preserves_multiset filter_preserves_multiset
78 subsection {* Representing multisets *}
80 text {* Multiset enumeration *}
82 instantiation multiset :: (type) cancel_comm_monoid_add
83 begin
85 lift_definition zero_multiset :: "'a multiset" is "\<lambda>a. 0"
86 by (rule const0_in_multiset)
88 abbreviation Mempty :: "'a multiset" ("{#}") where
89   "Mempty \<equiv> 0"
91 lift_definition plus_multiset :: "'a multiset => 'a multiset => 'a multiset" is "\<lambda>M N. (\<lambda>a. M a + N a)"
92 by (rule union_preserves_multiset)
94 instance
95 by default (transfer, simp add: fun_eq_iff)+
97 end
99 lift_definition single :: "'a => 'a multiset" is "\<lambda>a b. if b = a then 1 else 0"
100 by (rule only1_in_multiset)
102 syntax
103   "_multiset" :: "args => 'a multiset"    ("{#(_)#}")
104 translations
105   "{#x, xs#}" == "{#x#} + {#xs#}"
106   "{#x#}" == "CONST single x"
108 lemma count_empty [simp]: "count {#} a = 0"
109   by (simp add: zero_multiset.rep_eq)
111 lemma count_single [simp]: "count {#b#} a = (if b = a then 1 else 0)"
112   by (simp add: single.rep_eq)
115 subsection {* Basic operations *}
117 subsubsection {* Union *}
119 lemma count_union [simp]: "count (M + N) a = count M a + count N a"
120   by (simp add: plus_multiset.rep_eq)
123 subsubsection {* Difference *}
125 instantiation multiset :: (type) minus
126 begin
128 lift_definition minus_multiset :: "'a multiset => 'a multiset => 'a multiset" is "\<lambda> M N. \<lambda>a. M a - N a"
129 by (rule diff_preserves_multiset)
131 instance ..
133 end
135 lemma count_diff [simp]: "count (M - N) a = count M a - count N a"
136   by (simp add: minus_multiset.rep_eq)
138 lemma diff_empty [simp]: "M - {#} = M \<and> {#} - M = {#}"
139 by(simp add: multiset_eq_iff)
141 lemma diff_cancel[simp]: "A - A = {#}"
142 by (rule multiset_eqI) simp
144 lemma diff_union_cancelR [simp]: "M + N - N = (M::'a multiset)"
145 by(simp add: multiset_eq_iff)
147 lemma diff_union_cancelL [simp]: "N + M - N = (M::'a multiset)"
148 by(simp add: multiset_eq_iff)
150 lemma insert_DiffM:
151   "x \<in># M \<Longrightarrow> {#x#} + (M - {#x#}) = M"
152   by (clarsimp simp: multiset_eq_iff)
154 lemma insert_DiffM2 [simp]:
155   "x \<in># M \<Longrightarrow> M - {#x#} + {#x#} = M"
156   by (clarsimp simp: multiset_eq_iff)
158 lemma diff_right_commute:
159   "(M::'a multiset) - N - Q = M - Q - N"
160   by (auto simp add: multiset_eq_iff)
163   "(M::'a multiset) - (N + Q) = M - N - Q"
164 by (simp add: multiset_eq_iff)
166 lemma diff_union_swap:
167   "a \<noteq> b \<Longrightarrow> M - {#a#} + {#b#} = M + {#b#} - {#a#}"
168   by (auto simp add: multiset_eq_iff)
170 lemma diff_union_single_conv:
171   "a \<in># J \<Longrightarrow> I + J - {#a#} = I + (J - {#a#})"
172   by (simp add: multiset_eq_iff)
175 subsubsection {* Equality of multisets *}
177 lemma single_not_empty [simp]: "{#a#} \<noteq> {#} \<and> {#} \<noteq> {#a#}"
178   by (simp add: multiset_eq_iff)
180 lemma single_eq_single [simp]: "{#a#} = {#b#} \<longleftrightarrow> a = b"
181   by (auto simp add: multiset_eq_iff)
183 lemma union_eq_empty [iff]: "M + N = {#} \<longleftrightarrow> M = {#} \<and> N = {#}"
184   by (auto simp add: multiset_eq_iff)
186 lemma empty_eq_union [iff]: "{#} = M + N \<longleftrightarrow> M = {#} \<and> N = {#}"
187   by (auto simp add: multiset_eq_iff)
189 lemma multi_self_add_other_not_self [simp]: "M = M + {#x#} \<longleftrightarrow> False"
190   by (auto simp add: multiset_eq_iff)
192 lemma diff_single_trivial:
193   "\<not> x \<in># M \<Longrightarrow> M - {#x#} = M"
194   by (auto simp add: multiset_eq_iff)
196 lemma diff_single_eq_union:
197   "x \<in># M \<Longrightarrow> M - {#x#} = N \<longleftrightarrow> M = N + {#x#}"
198   by auto
200 lemma union_single_eq_diff:
201   "M + {#x#} = N \<Longrightarrow> M = N - {#x#}"
202   by (auto dest: sym)
204 lemma union_single_eq_member:
205   "M + {#x#} = N \<Longrightarrow> x \<in># N"
206   by auto
208 lemma union_is_single:
209   "M + N = {#a#} \<longleftrightarrow> M = {#a#} \<and> N={#} \<or> M = {#} \<and> N = {#a#}" (is "?lhs = ?rhs")
210 proof
211   assume ?rhs then show ?lhs by auto
212 next
213   assume ?lhs then show ?rhs
214     by (simp add: multiset_eq_iff split:if_splits) (metis add_is_1)
215 qed
217 lemma single_is_union:
218   "{#a#} = M + N \<longleftrightarrow> {#a#} = M \<and> N = {#} \<or> M = {#} \<and> {#a#} = N"
219   by (auto simp add: eq_commute [of "{#a#}" "M + N"] union_is_single)
222   "M + {#a#} = N + {#b#} \<longleftrightarrow> M = N \<and> a = b \<or> M = N - {#a#} + {#b#} \<and> N = M - {#b#} + {#a#}"  (is "?lhs = ?rhs")
223 (* shorter: by (simp add: multiset_eq_iff) fastforce *)
224 proof
225   assume ?rhs then show ?lhs
227     (drule sym, simp add: add_assoc [symmetric])
228 next
229   assume ?lhs
230   show ?rhs
231   proof (cases "a = b")
232     case True with `?lhs` show ?thesis by simp
233   next
234     case False
235     from `?lhs` have "a \<in># N + {#b#}" by (rule union_single_eq_member)
236     with False have "a \<in># N" by auto
237     moreover from `?lhs` have "M = N + {#b#} - {#a#}" by (rule union_single_eq_diff)
238     moreover note False
239     ultimately show ?thesis by (auto simp add: diff_right_commute [of _ "{#a#}"] diff_union_swap)
240   qed
241 qed
243 lemma insert_noteq_member:
244   assumes BC: "B + {#b#} = C + {#c#}"
245    and bnotc: "b \<noteq> c"
246   shows "c \<in># B"
247 proof -
248   have "c \<in># C + {#c#}" by simp
249   have nc: "\<not> c \<in># {#b#}" using bnotc by simp
250   then have "c \<in># B + {#b#}" using BC by simp
251   then show "c \<in># B" using nc by simp
252 qed
255   "(M + {#a#} = N + {#b#}) =
256     (M = N \<and> a = b \<or> (\<exists>K. M = K + {#b#} \<and> N = K + {#a#}))"
260 subsubsection {* Pointwise ordering induced by count *}
262 instantiation multiset :: (type) ordered_ab_semigroup_add_imp_le
263 begin
265 lift_definition less_eq_multiset :: "'a multiset \<Rightarrow> 'a multiset \<Rightarrow> bool" is "\<lambda> A B. (\<forall>a. A a \<le> B a)"
266 by simp
267 lemmas mset_le_def = less_eq_multiset_def
269 definition less_multiset :: "'a multiset \<Rightarrow> 'a multiset \<Rightarrow> bool" where
270   mset_less_def: "(A::'a multiset) < B \<longleftrightarrow> A \<le> B \<and> A \<noteq> B"
272 instance
273   by default (auto simp add: mset_le_def mset_less_def multiset_eq_iff intro: order_trans antisym)
275 end
277 lemma mset_less_eqI:
278   "(\<And>x. count A x \<le> count B x) \<Longrightarrow> A \<le> B"
279   by (simp add: mset_le_def)
281 lemma mset_le_exists_conv:
282   "(A::'a multiset) \<le> B \<longleftrightarrow> (\<exists>C. B = A + C)"
283 apply (unfold mset_le_def, rule iffI, rule_tac x = "B - A" in exI)
284 apply (auto intro: multiset_eq_iff [THEN iffD2])
285 done
287 lemma mset_le_mono_add_right_cancel [simp]:
288   "(A::'a multiset) + C \<le> B + C \<longleftrightarrow> A \<le> B"
289   by (fact add_le_cancel_right)
291 lemma mset_le_mono_add_left_cancel [simp]:
292   "C + (A::'a multiset) \<le> C + B \<longleftrightarrow> A \<le> B"
293   by (fact add_le_cancel_left)
296   "(A::'a multiset) \<le> B \<Longrightarrow> C \<le> D \<Longrightarrow> A + C \<le> B + D"
297   by (fact add_mono)
299 lemma mset_le_add_left [simp]:
300   "(A::'a multiset) \<le> A + B"
301   unfolding mset_le_def by auto
303 lemma mset_le_add_right [simp]:
304   "B \<le> (A::'a multiset) + B"
305   unfolding mset_le_def by auto
307 lemma mset_le_single:
308   "a :# B \<Longrightarrow> {#a#} \<le> B"
309   by (simp add: mset_le_def)
311 lemma multiset_diff_union_assoc:
312   "C \<le> B \<Longrightarrow> (A::'a multiset) + B - C = A + (B - C)"
313   by (simp add: multiset_eq_iff mset_le_def)
315 lemma mset_le_multiset_union_diff_commute:
316   "B \<le> A \<Longrightarrow> (A::'a multiset) - B + C = A + C - B"
317 by (simp add: multiset_eq_iff mset_le_def)
319 lemma diff_le_self[simp]: "(M::'a multiset) - N \<le> M"
320 by(simp add: mset_le_def)
322 lemma mset_lessD: "A < B \<Longrightarrow> x \<in># A \<Longrightarrow> x \<in># B"
323 apply (clarsimp simp: mset_le_def mset_less_def)
324 apply (erule_tac x=x in allE)
325 apply auto
326 done
328 lemma mset_leD: "A \<le> B \<Longrightarrow> x \<in># A \<Longrightarrow> x \<in># B"
329 apply (clarsimp simp: mset_le_def mset_less_def)
330 apply (erule_tac x = x in allE)
331 apply auto
332 done
334 lemma mset_less_insertD: "(A + {#x#} < B) \<Longrightarrow> (x \<in># B \<and> A < B)"
335 apply (rule conjI)
336  apply (simp add: mset_lessD)
337 apply (clarsimp simp: mset_le_def mset_less_def)
338 apply safe
339  apply (erule_tac x = a in allE)
340  apply (auto split: split_if_asm)
341 done
343 lemma mset_le_insertD: "(A + {#x#} \<le> B) \<Longrightarrow> (x \<in># B \<and> A \<le> B)"
344 apply (rule conjI)
345  apply (simp add: mset_leD)
346 apply (force simp: mset_le_def mset_less_def split: split_if_asm)
347 done
349 lemma mset_less_of_empty[simp]: "A < {#} \<longleftrightarrow> False"
350   by (auto simp add: mset_less_def mset_le_def multiset_eq_iff)
352 lemma multi_psub_of_add_self[simp]: "A < A + {#x#}"
353   by (auto simp: mset_le_def mset_less_def)
355 lemma multi_psub_self[simp]: "(A::'a multiset) < A = False"
356   by simp
359   "T + {#x#} < S + {#x#} \<Longrightarrow> T < S"
360   by (fact add_less_imp_less_right)
362 lemma mset_less_empty_nonempty:
363   "{#} < S \<longleftrightarrow> S \<noteq> {#}"
364   by (auto simp: mset_le_def mset_less_def)
366 lemma mset_less_diff_self:
367   "c \<in># B \<Longrightarrow> B - {#c#} < B"
368   by (auto simp: mset_le_def mset_less_def multiset_eq_iff)
371 subsubsection {* Intersection *}
373 instantiation multiset :: (type) semilattice_inf
374 begin
376 definition inf_multiset :: "'a multiset \<Rightarrow> 'a multiset \<Rightarrow> 'a multiset" where
377   multiset_inter_def: "inf_multiset A B = A - (A - B)"
379 instance
380 proof -
381   have aux: "\<And>m n q :: nat. m \<le> n \<Longrightarrow> m \<le> q \<Longrightarrow> m \<le> n - (n - q)" by arith
382   show "OFCLASS('a multiset, semilattice_inf_class)"
383     by default (auto simp add: multiset_inter_def mset_le_def aux)
384 qed
386 end
388 abbreviation multiset_inter :: "'a multiset \<Rightarrow> 'a multiset \<Rightarrow> 'a multiset" (infixl "#\<inter>" 70) where
389   "multiset_inter \<equiv> inf"
391 lemma multiset_inter_count [simp]:
392   "count (A #\<inter> B) x = min (count A x) (count B x)"
393   by (simp add: multiset_inter_def)
395 lemma multiset_inter_single: "a \<noteq> b \<Longrightarrow> {#a#} #\<inter> {#b#} = {#}"
396   by (rule multiset_eqI) auto
398 lemma multiset_union_diff_commute:
399   assumes "B #\<inter> C = {#}"
400   shows "A + B - C = A - C + B"
401 proof (rule multiset_eqI)
402   fix x
403   from assms have "min (count B x) (count C x) = 0"
404     by (auto simp add: multiset_eq_iff)
405   then have "count B x = 0 \<or> count C x = 0"
406     by auto
407   then show "count (A + B - C) x = count (A - C + B) x"
408     by auto
409 qed
412 subsubsection {* Filter (with comprehension syntax) *}
414 text {* Multiset comprehension *}
416 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"
417 by (rule filter_preserves_multiset)
419 hide_const (open) filter
421 lemma count_filter [simp]:
422   "count (Multiset.filter P M) a = (if P a then count M a else 0)"
423   by (simp add: filter.rep_eq)
425 lemma filter_empty [simp]:
426   "Multiset.filter P {#} = {#}"
427   by (rule multiset_eqI) simp
429 lemma filter_single [simp]:
430   "Multiset.filter P {#x#} = (if P x then {#x#} else {#})"
431   by (rule multiset_eqI) simp
433 lemma filter_union [simp]:
434   "Multiset.filter P (M + N) = Multiset.filter P M + Multiset.filter P N"
435   by (rule multiset_eqI) simp
437 lemma filter_diff [simp]:
438   "Multiset.filter P (M - N) = Multiset.filter P M - Multiset.filter P N"
439   by (rule multiset_eqI) simp
441 lemma filter_inter [simp]:
442   "Multiset.filter P (M #\<inter> N) = Multiset.filter P M #\<inter> Multiset.filter P N"
443   by (rule multiset_eqI) simp
445 syntax
446   "_MCollect" :: "pttrn \<Rightarrow> 'a multiset \<Rightarrow> bool \<Rightarrow> 'a multiset"    ("(1{# _ :# _./ _#})")
447 syntax (xsymbol)
448   "_MCollect" :: "pttrn \<Rightarrow> 'a multiset \<Rightarrow> bool \<Rightarrow> 'a multiset"    ("(1{# _ \<in># _./ _#})")
449 translations
450   "{#x \<in># M. P#}" == "CONST Multiset.filter (\<lambda>x. P) M"
453 subsubsection {* Set of elements *}
455 definition set_of :: "'a multiset => 'a set" where
456   "set_of M = {x. x :# M}"
458 lemma set_of_empty [simp]: "set_of {#} = {}"
459 by (simp add: set_of_def)
461 lemma set_of_single [simp]: "set_of {#b#} = {b}"
462 by (simp add: set_of_def)
464 lemma set_of_union [simp]: "set_of (M + N) = set_of M \<union> set_of N"
465 by (auto simp add: set_of_def)
467 lemma set_of_eq_empty_iff [simp]: "(set_of M = {}) = (M = {#})"
468 by (auto simp add: set_of_def multiset_eq_iff)
470 lemma mem_set_of_iff [simp]: "(x \<in> set_of M) = (x :# M)"
471 by (auto simp add: set_of_def)
473 lemma set_of_filter [simp]: "set_of {# x:#M. P x #} = set_of M \<inter> {x. P x}"
474 by (auto simp add: set_of_def)
476 lemma finite_set_of [iff]: "finite (set_of M)"
477   using count [of M] by (simp add: multiset_def set_of_def)
479 lemma finite_Collect_mem [iff]: "finite {x. x :# M}"
480   unfolding set_of_def[symmetric] by simp
482 subsubsection {* Size *}
484 instantiation multiset :: (type) size
485 begin
487 definition size_def:
488   "size M = setsum (count M) (set_of M)"
490 instance ..
492 end
494 lemma size_empty [simp]: "size {#} = 0"
495 by (simp add: size_def)
497 lemma size_single [simp]: "size {#b#} = 1"
498 by (simp add: size_def)
500 lemma setsum_count_Int:
501   "finite A ==> setsum (count N) (A \<inter> set_of N) = setsum (count N) A"
502 apply (induct rule: finite_induct)
503  apply simp
504 apply (simp add: Int_insert_left set_of_def)
505 done
507 lemma size_union [simp]: "size (M + N::'a multiset) = size M + size N"
508 apply (unfold size_def)
509 apply (subgoal_tac "count (M + N) = (\<lambda>a. count M a + count N a)")
510  prefer 2
511  apply (rule ext, simp)
512 apply (simp (no_asm_simp) add: setsum_Un_nat setsum_addf setsum_count_Int)
513 apply (subst Int_commute)
514 apply (simp (no_asm_simp) add: setsum_count_Int)
515 done
517 lemma size_eq_0_iff_empty [iff]: "(size M = 0) = (M = {#})"
518 by (auto simp add: size_def multiset_eq_iff)
520 lemma nonempty_has_size: "(S \<noteq> {#}) = (0 < size S)"
521 by (metis gr0I gr_implies_not0 size_empty size_eq_0_iff_empty)
523 lemma size_eq_Suc_imp_elem: "size M = Suc n ==> \<exists>a. a :# M"
524 apply (unfold size_def)
525 apply (drule setsum_SucD)
526 apply auto
527 done
529 lemma size_eq_Suc_imp_eq_union:
530   assumes "size M = Suc n"
531   shows "\<exists>a N. M = N + {#a#}"
532 proof -
533   from assms obtain a where "a \<in># M"
534     by (erule size_eq_Suc_imp_elem [THEN exE])
535   then have "M = M - {#a#} + {#a#}" by simp
536   then show ?thesis by blast
537 qed
540 subsection {* Induction and case splits *}
542 theorem multiset_induct [case_names empty add, induct type: multiset]:
543   assumes empty: "P {#}"
544   assumes add: "\<And>M x. P M \<Longrightarrow> P (M + {#x#})"
545   shows "P M"
546 proof (induct n \<equiv> "size M" arbitrary: M)
547   case 0 thus "P M" by (simp add: empty)
548 next
549   case (Suc k)
550   obtain N x where "M = N + {#x#}"
551     using `Suc k = size M` [symmetric]
552     using size_eq_Suc_imp_eq_union by fast
553   with Suc add show "P M" by simp
554 qed
556 lemma multi_nonempty_split: "M \<noteq> {#} \<Longrightarrow> \<exists>A a. M = A + {#a#}"
557 by (induct M) auto
559 lemma multiset_cases [cases type, case_names empty add]:
560 assumes em:  "M = {#} \<Longrightarrow> P"
561 assumes add: "\<And>N x. M = N + {#x#} \<Longrightarrow> P"
562 shows "P"
563 using assms by (induct M) simp_all
565 lemma multi_member_split: "x \<in># M \<Longrightarrow> \<exists>A. M = A + {#x#}"
566 by (rule_tac x="M - {#x#}" in exI, simp)
568 lemma multi_drop_mem_not_eq: "c \<in># B \<Longrightarrow> B - {#c#} \<noteq> B"
569 by (cases "B = {#}") (auto dest: multi_member_split)
571 lemma multiset_partition: "M = {# x:#M. P x #} + {# x:#M. \<not> P x #}"
572 apply (subst multiset_eq_iff)
573 apply auto
574 done
576 lemma mset_less_size: "(A::'a multiset) < B \<Longrightarrow> size A < size B"
577 proof (induct A arbitrary: B)
578   case (empty M)
579   then have "M \<noteq> {#}" by (simp add: mset_less_empty_nonempty)
580   then obtain M' x where "M = M' + {#x#}"
581     by (blast dest: multi_nonempty_split)
582   then show ?case by simp
583 next
584   case (add S x T)
585   have IH: "\<And>B. S < B \<Longrightarrow> size S < size B" by fact
586   have SxsubT: "S + {#x#} < T" by fact
587   then have "x \<in># T" and "S < T" by (auto dest: mset_less_insertD)
588   then obtain T' where T: "T = T' + {#x#}"
589     by (blast dest: multi_member_split)
590   then have "S < T'" using SxsubT
591     by (blast intro: mset_less_add_bothsides)
592   then have "size S < size T'" using IH by simp
593   then show ?case using T by simp
594 qed
597 subsubsection {* Strong induction and subset induction for multisets *}
599 text {* Well-foundedness of proper subset operator: *}
601 text {* proper multiset subset *}
603 definition
604   mset_less_rel :: "('a multiset * 'a multiset) set" where
605   "mset_less_rel = {(A,B). A < B}"
608   assumes "c \<in># B" and "b \<noteq> c"
609   shows "B - {#c#} + {#b#} = B + {#b#} - {#c#}"
610 proof -
611   from `c \<in># B` obtain A where B: "B = A + {#c#}"
612     by (blast dest: multi_member_split)
613   have "A + {#b#} = A + {#b#} + {#c#} - {#c#}" by simp
614   then have "A + {#b#} = A + {#c#} + {#b#} - {#c#}"
616   then show ?thesis using B by simp
617 qed
619 lemma wf_mset_less_rel: "wf mset_less_rel"
620 apply (unfold mset_less_rel_def)
621 apply (rule wf_measure [THEN wf_subset, where f1=size])
622 apply (clarsimp simp: measure_def inv_image_def mset_less_size)
623 done
625 text {* The induction rules: *}
627 lemma full_multiset_induct [case_names less]:
628 assumes ih: "\<And>B. \<forall>(A::'a multiset). A < B \<longrightarrow> P A \<Longrightarrow> P B"
629 shows "P B"
630 apply (rule wf_mset_less_rel [THEN wf_induct])
631 apply (rule ih, auto simp: mset_less_rel_def)
632 done
634 lemma multi_subset_induct [consumes 2, case_names empty add]:
635 assumes "F \<le> A"
636   and empty: "P {#}"
637   and insert: "\<And>a F. a \<in># A \<Longrightarrow> P F \<Longrightarrow> P (F + {#a#})"
638 shows "P F"
639 proof -
640   from `F \<le> A`
641   show ?thesis
642   proof (induct F)
643     show "P {#}" by fact
644   next
645     fix x F
646     assume P: "F \<le> A \<Longrightarrow> P F" and i: "F + {#x#} \<le> A"
647     show "P (F + {#x#})"
648     proof (rule insert)
649       from i show "x \<in># A" by (auto dest: mset_le_insertD)
650       from i have "F \<le> A" by (auto dest: mset_le_insertD)
651       with P show "P F" .
652     qed
653   qed
654 qed
657 subsection {* The fold combinator *}
659 text {*
660   The intended behaviour is
661   @{text "fold_mset f z {#x\<^isub>1, ..., x\<^isub>n#} = f x\<^isub>1 (\<dots> (f x\<^isub>n z)\<dots>)"}
662   if @{text f} is associative-commutative.
663 *}
665 text {*
666   The graph of @{text "fold_mset"}, @{text "z"}: the start element,
667   @{text "f"}: folding function, @{text "A"}: the multiset, @{text
668   "y"}: the result.
669 *}
670 inductive
671   fold_msetG :: "('a \<Rightarrow> 'b \<Rightarrow> 'b) \<Rightarrow> 'b \<Rightarrow> 'a multiset \<Rightarrow> 'b \<Rightarrow> bool"
672   for f :: "'a \<Rightarrow> 'b \<Rightarrow> 'b"
673   and z :: 'b
674 where
675   emptyI [intro]:  "fold_msetG f z {#} z"
676 | insertI [intro]: "fold_msetG f z A y \<Longrightarrow> fold_msetG f z (A + {#x#}) (f x y)"
678 inductive_cases empty_fold_msetGE [elim!]: "fold_msetG f z {#} x"
679 inductive_cases insert_fold_msetGE: "fold_msetG f z (A + {#}) y"
681 definition
682   fold_mset :: "('a \<Rightarrow> 'b \<Rightarrow> 'b) \<Rightarrow> 'b \<Rightarrow> 'a multiset \<Rightarrow> 'b" where
683   "fold_mset f z A = (THE x. fold_msetG f z A x)"
685 lemma Diff1_fold_msetG:
686   "fold_msetG f z (A - {#x#}) y \<Longrightarrow> x \<in># A \<Longrightarrow> fold_msetG f z A (f x y)"
687 apply (frule_tac x = x in fold_msetG.insertI)
688 apply auto
689 done
691 lemma fold_msetG_nonempty: "\<exists>x. fold_msetG f z A x"
692 apply (induct A)
693  apply blast
694 apply clarsimp
695 apply (drule_tac x = x in fold_msetG.insertI)
696 apply auto
697 done
699 lemma fold_mset_empty[simp]: "fold_mset f z {#} = z"
700 unfolding fold_mset_def by blast
702 context comp_fun_commute
703 begin
705 lemma fold_msetG_insertE_aux:
706   "fold_msetG f z A y \<Longrightarrow> a \<in># A \<Longrightarrow> \<exists>y'. y = f a y' \<and> fold_msetG f z (A - {#a#}) y'"
707 proof (induct set: fold_msetG)
708   case (insertI A y x) show ?case
709   proof (cases "x = a")
710     assume "x = a" with insertI show ?case by auto
711   next
712     assume "x \<noteq> a"
713     then obtain y' where y: "y = f a y'" and y': "fold_msetG f z (A - {#a#}) y'"
714       using insertI by auto
715     have "f x y = f a (f x y')"
716       unfolding y by (rule fun_left_comm)
717     moreover have "fold_msetG f z (A + {#x#} - {#a#}) (f x y')"
718       using y' and `x \<noteq> a`
719       by (simp add: diff_union_swap [symmetric] fold_msetG.insertI)
720     ultimately show ?case by fast
721   qed
722 qed simp
724 lemma fold_msetG_insertE:
725   assumes "fold_msetG f z (A + {#x#}) v"
726   obtains y where "v = f x y" and "fold_msetG f z A y"
727 using assms by (auto dest: fold_msetG_insertE_aux [where a=x])
729 lemma fold_msetG_determ:
730   "fold_msetG f z A x \<Longrightarrow> fold_msetG f z A y \<Longrightarrow> y = x"
731 proof (induct arbitrary: y set: fold_msetG)
732   case (insertI A y x v)
733   from `fold_msetG f z (A + {#x#}) v`
734   obtain y' where "v = f x y'" and "fold_msetG f z A y'"
735     by (rule fold_msetG_insertE)
736   from `fold_msetG f z A y'` have "y' = y" by (rule insertI)
737   with `v = f x y'` show "v = f x y" by simp
738 qed fast
740 lemma fold_mset_equality: "fold_msetG f z A y \<Longrightarrow> fold_mset f z A = y"
741 unfolding fold_mset_def by (blast intro: fold_msetG_determ)
743 lemma fold_msetG_fold_mset: "fold_msetG f z A (fold_mset f z A)"
744 proof -
745   from fold_msetG_nonempty fold_msetG_determ
746   have "\<exists>!x. fold_msetG f z A x" by (rule ex_ex1I)
747   then show ?thesis unfolding fold_mset_def by (rule theI')
748 qed
750 lemma fold_mset_insert:
751   "fold_mset f z (A + {#x#}) = f x (fold_mset f z A)"
752 by (intro fold_mset_equality fold_msetG.insertI fold_msetG_fold_mset)
754 lemma fold_mset_commute: "f x (fold_mset f z A) = fold_mset f (f x z) A"
755 by (induct A) (auto simp: fold_mset_insert fun_left_comm [of x])
757 lemma fold_mset_single [simp]: "fold_mset f z {#x#} = f x z"
758 using fold_mset_insert [of z "{#}"] by simp
760 lemma fold_mset_union [simp]:
761   "fold_mset f z (A+B) = fold_mset f (fold_mset f z A) B"
762 proof (induct A)
763   case empty then show ?case by simp
764 next
765   case (add A x)
766   have "A + {#x#} + B = (A+B) + {#x#}" by (simp add: add_ac)
767   then have "fold_mset f z (A + {#x#} + B) = f x (fold_mset f z (A + B))"
768     by (simp add: fold_mset_insert)
769   also have "\<dots> = fold_mset f (fold_mset f z (A + {#x#})) B"
770     by (simp add: fold_mset_commute[of x,symmetric] add fold_mset_insert)
771   finally show ?case .
772 qed
774 lemma fold_mset_fusion:
775   assumes "comp_fun_commute g"
776   shows "(\<And>x y. h (g x y) = f x (h y)) \<Longrightarrow> h (fold_mset g w A) = fold_mset f (h w) A" (is "PROP ?P")
777 proof -
778   interpret comp_fun_commute g by (fact assms)
779   show "PROP ?P" by (induct A) auto
780 qed
782 lemma fold_mset_rec:
783   assumes "a \<in># A"
784   shows "fold_mset f z A = f a (fold_mset f z (A - {#a#}))"
785 proof -
786   from assms obtain A' where "A = A' + {#a#}"
787     by (blast dest: multi_member_split)
788   then show ?thesis by simp
789 qed
791 end
793 text {*
794   A note on code generation: When defining some function containing a
795   subterm @{term"fold_mset F"}, code generation is not automatic. When
796   interpreting locale @{text left_commutative} with @{text F}, the
797   would be code thms for @{const fold_mset} become thms like
798   @{term"fold_mset F z {#} = z"} where @{text F} is not a pattern but
799   contains defined symbols, i.e.\ is not a code thm. Hence a separate
800   constant with its own code thms needs to be introduced for @{text
801   F}. See the image operator below.
802 *}
805 subsection {* Image *}
807 definition image_mset :: "('a \<Rightarrow> 'b) \<Rightarrow> 'a multiset \<Rightarrow> 'b multiset" where
808   "image_mset f = fold_mset (op + o single o f) {#}"
810 interpretation image_fun_commute: comp_fun_commute "op + o single o f" for f
811 proof qed (simp add: add_ac fun_eq_iff)
813 lemma image_mset_empty [simp]: "image_mset f {#} = {#}"
814 by (simp add: image_mset_def)
816 lemma image_mset_single [simp]: "image_mset f {#x#} = {#f x#}"
817 by (simp add: image_mset_def)
819 lemma image_mset_insert:
820   "image_mset f (M + {#a#}) = image_mset f M + {#f a#}"
823 lemma image_mset_union [simp]:
824   "image_mset f (M+N) = image_mset f M + image_mset f N"
825 apply (induct N)
826  apply simp
827 apply (simp add: add_assoc [symmetric] image_mset_insert)
828 done
830 lemma set_of_image_mset [simp]: "set_of (image_mset f M) = image f (set_of M)"
831 by (induct M) simp_all
833 lemma size_image_mset [simp]: "size (image_mset f M) = size M"
834 by (induct M) simp_all
836 lemma image_mset_is_empty_iff [simp]: "image_mset f M = {#} \<longleftrightarrow> M = {#}"
837 by (cases M) auto
839 syntax
840   "_comprehension1_mset" :: "'a \<Rightarrow> 'b \<Rightarrow> 'b multiset \<Rightarrow> 'a multiset"
841       ("({#_/. _ :# _#})")
842 translations
843   "{#e. x:#M#}" == "CONST image_mset (%x. e) M"
845 syntax
846   "_comprehension2_mset" :: "'a \<Rightarrow> 'b \<Rightarrow> 'b multiset \<Rightarrow> bool \<Rightarrow> 'a multiset"
847       ("({#_/ | _ :# _./ _#})")
848 translations
849   "{#e | x:#M. P#}" => "{#e. x :# {# x:#M. P#}#}"
851 text {*
852   This allows to write not just filters like @{term "{#x:#M. x<c#}"}
853   but also images like @{term "{#x+x. x:#M #}"} and @{term [source]
854   "{#x+x|x:#M. x<c#}"}, where the latter is currently displayed as
855   @{term "{#x+x|x:#M. x<c#}"}.
856 *}
858 enriched_type image_mset: image_mset
859 proof -
860   fix f g show "image_mset f \<circ> image_mset g = image_mset (f \<circ> g)"
861   proof
862     fix A
863     show "(image_mset f \<circ> image_mset g) A = image_mset (f \<circ> g) A"
864       by (induct A) simp_all
865   qed
866   show "image_mset id = id"
867   proof
868     fix A
869     show "image_mset id A = id A"
870       by (induct A) simp_all
871   qed
872 qed
875 subsection {* Alternative representations *}
877 subsubsection {* Lists *}
879 primrec multiset_of :: "'a list \<Rightarrow> 'a multiset" where
880   "multiset_of [] = {#}" |
881   "multiset_of (a # x) = multiset_of x + {# a #}"
883 lemma in_multiset_in_set:
884   "x \<in># multiset_of xs \<longleftrightarrow> x \<in> set xs"
885   by (induct xs) simp_all
887 lemma count_multiset_of:
888   "count (multiset_of xs) x = length (filter (\<lambda>y. x = y) xs)"
889   by (induct xs) simp_all
891 lemma multiset_of_zero_iff[simp]: "(multiset_of x = {#}) = (x = [])"
892 by (induct x) auto
894 lemma multiset_of_zero_iff_right[simp]: "({#} = multiset_of x) = (x = [])"
895 by (induct x) auto
897 lemma set_of_multiset_of[simp]: "set_of (multiset_of x) = set x"
898 by (induct x) auto
900 lemma mem_set_multiset_eq: "x \<in> set xs = (x :# multiset_of xs)"
901 by (induct xs) auto
903 lemma size_multiset_of [simp]: "size (multiset_of xs) = length xs"
904   by (induct xs) simp_all
906 lemma multiset_of_append [simp]:
907   "multiset_of (xs @ ys) = multiset_of xs + multiset_of ys"
908   by (induct xs arbitrary: ys) (auto simp: add_ac)
910 lemma multiset_of_filter:
911   "multiset_of (filter P xs) = {#x :# multiset_of xs. P x #}"
912   by (induct xs) simp_all
914 lemma multiset_of_rev [simp]:
915   "multiset_of (rev xs) = multiset_of xs"
916   by (induct xs) simp_all
918 lemma surj_multiset_of: "surj multiset_of"
919 apply (unfold surj_def)
920 apply (rule allI)
921 apply (rule_tac M = y in multiset_induct)
922  apply auto
923 apply (rule_tac x = "x # xa" in exI)
924 apply auto
925 done
927 lemma set_count_greater_0: "set x = {a. count (multiset_of x) a > 0}"
928 by (induct x) auto
930 lemma distinct_count_atmost_1:
931   "distinct x = (! a. count (multiset_of x) a = (if a \<in> set x then 1 else 0))"
932 apply (induct x, simp, rule iffI, simp_all)
933 apply (rule conjI)
934 apply (simp_all add: set_of_multiset_of [THEN sym] del: set_of_multiset_of)
935 apply (erule_tac x = a in allE, simp, clarify)
936 apply (erule_tac x = aa in allE, simp)
937 done
939 lemma multiset_of_eq_setD:
940   "multiset_of xs = multiset_of ys \<Longrightarrow> set xs = set ys"
941 by (rule) (auto simp add:multiset_eq_iff set_count_greater_0)
943 lemma set_eq_iff_multiset_of_eq_distinct:
944   "distinct x \<Longrightarrow> distinct y \<Longrightarrow>
945     (set x = set y) = (multiset_of x = multiset_of y)"
946 by (auto simp: multiset_eq_iff distinct_count_atmost_1)
948 lemma set_eq_iff_multiset_of_remdups_eq:
949    "(set x = set y) = (multiset_of (remdups x) = multiset_of (remdups y))"
950 apply (rule iffI)
951 apply (simp add: set_eq_iff_multiset_of_eq_distinct[THEN iffD1])
952 apply (drule distinct_remdups [THEN distinct_remdups
953       [THEN set_eq_iff_multiset_of_eq_distinct [THEN iffD2]]])
954 apply simp
955 done
957 lemma multiset_of_compl_union [simp]:
958   "multiset_of [x\<leftarrow>xs. P x] + multiset_of [x\<leftarrow>xs. \<not>P x] = multiset_of xs"
959   by (induct xs) (auto simp: add_ac)
961 lemma count_multiset_of_length_filter:
962   "count (multiset_of xs) x = length (filter (\<lambda>y. x = y) xs)"
963   by (induct xs) auto
965 lemma nth_mem_multiset_of: "i < length ls \<Longrightarrow> (ls ! i) :# multiset_of ls"
966 apply (induct ls arbitrary: i)
967  apply simp
968 apply (case_tac i)
969  apply auto
970 done
972 lemma multiset_of_remove1[simp]:
973   "multiset_of (remove1 a xs) = multiset_of xs - {#a#}"
974 by (induct xs) (auto simp add: multiset_eq_iff)
976 lemma multiset_of_eq_length:
977   assumes "multiset_of xs = multiset_of ys"
978   shows "length xs = length ys"
979   using assms by (metis size_multiset_of)
981 lemma multiset_of_eq_length_filter:
982   assumes "multiset_of xs = multiset_of ys"
983   shows "length (filter (\<lambda>x. z = x) xs) = length (filter (\<lambda>y. z = y) ys)"
984   using assms by (metis count_multiset_of)
986 lemma fold_multiset_equiv:
987   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"
988     and equiv: "multiset_of xs = multiset_of ys"
989   shows "fold f xs = fold f ys"
990 using f equiv [symmetric]
991 proof (induct xs arbitrary: ys)
992   case Nil then show ?case by simp
993 next
994   case (Cons x xs)
995   then have *: "set ys = set (x # xs)" by (blast dest: multiset_of_eq_setD)
996   have "\<And>x y. x \<in> set ys \<Longrightarrow> y \<in> set ys \<Longrightarrow> f x \<circ> f y = f y \<circ> f x"
997     by (rule Cons.prems(1)) (simp_all add: *)
998   moreover from * have "x \<in> set ys" by simp
999   ultimately have "fold f ys = fold f (remove1 x ys) \<circ> f x" by (fact fold_remove1_split)
1000   moreover from Cons.prems have "fold f xs = fold f (remove1 x ys)" by (auto intro: Cons.hyps)
1001   ultimately show ?case by simp
1002 qed
1004 context linorder
1005 begin
1007 lemma multiset_of_insort [simp]:
1008   "multiset_of (insort_key k x xs) = {#x#} + multiset_of xs"
1009   by (induct xs) (simp_all add: ac_simps)
1011 lemma multiset_of_sort [simp]:
1012   "multiset_of (sort_key k xs) = multiset_of xs"
1013   by (induct xs) (simp_all add: ac_simps)
1015 text {*
1016   This lemma shows which properties suffice to show that a function
1017   @{text "f"} with @{text "f xs = ys"} behaves like sort.
1018 *}
1020 lemma properties_for_sort_key:
1021   assumes "multiset_of ys = multiset_of xs"
1022   and "\<And>k. k \<in> set ys \<Longrightarrow> filter (\<lambda>x. f k = f x) ys = filter (\<lambda>x. f k = f x) xs"
1023   and "sorted (map f ys)"
1024   shows "sort_key f xs = ys"
1025 using assms
1026 proof (induct xs arbitrary: ys)
1027   case Nil then show ?case by simp
1028 next
1029   case (Cons x xs)
1030   from Cons.prems(2) have
1031     "\<forall>k \<in> set ys. filter (\<lambda>x. f k = f x) (remove1 x ys) = filter (\<lambda>x. f k = f x) xs"
1032     by (simp add: filter_remove1)
1033   with Cons.prems have "sort_key f xs = remove1 x ys"
1034     by (auto intro!: Cons.hyps simp add: sorted_map_remove1)
1035   moreover from Cons.prems have "x \<in> set ys"
1036     by (auto simp add: mem_set_multiset_eq intro!: ccontr)
1037   ultimately show ?case using Cons.prems by (simp add: insort_key_remove1)
1038 qed
1040 lemma properties_for_sort:
1041   assumes multiset: "multiset_of ys = multiset_of xs"
1042   and "sorted ys"
1043   shows "sort xs = ys"
1044 proof (rule properties_for_sort_key)
1045   from multiset show "multiset_of ys = multiset_of xs" .
1046   from `sorted ys` show "sorted (map (\<lambda>x. x) ys)" by simp
1047   from multiset have "\<And>k. length (filter (\<lambda>y. k = y) ys) = length (filter (\<lambda>x. k = x) xs)"
1048     by (rule multiset_of_eq_length_filter)
1049   then have "\<And>k. replicate (length (filter (\<lambda>y. k = y) ys)) k = replicate (length (filter (\<lambda>x. k = x) xs)) k"
1050     by simp
1051   then show "\<And>k. k \<in> set ys \<Longrightarrow> filter (\<lambda>y. k = y) ys = filter (\<lambda>x. k = x) xs"
1052     by (simp add: replicate_length_filter)
1053 qed
1055 lemma sort_key_by_quicksort:
1056   "sort_key f xs = sort_key f [x\<leftarrow>xs. f x < f (xs ! (length xs div 2))]
1057     @ [x\<leftarrow>xs. f x = f (xs ! (length xs div 2))]
1058     @ sort_key f [x\<leftarrow>xs. f x > f (xs ! (length xs div 2))]" (is "sort_key f ?lhs = ?rhs")
1059 proof (rule properties_for_sort_key)
1060   show "multiset_of ?rhs = multiset_of ?lhs"
1061     by (rule multiset_eqI) (auto simp add: multiset_of_filter)
1062 next
1063   show "sorted (map f ?rhs)"
1064     by (auto simp add: sorted_append intro: sorted_map_same)
1065 next
1066   fix l
1067   assume "l \<in> set ?rhs"
1068   let ?pivot = "f (xs ! (length xs div 2))"
1069   have *: "\<And>x. f l = f x \<longleftrightarrow> f x = f l" by auto
1070   have "[x \<leftarrow> sort_key f xs . f x = f l] = [x \<leftarrow> xs. f x = f l]"
1071     unfolding filter_sort by (rule properties_for_sort_key) (auto intro: sorted_map_same)
1072   with * have **: "[x \<leftarrow> sort_key f xs . f l = f x] = [x \<leftarrow> xs. f l = f x]" by simp
1073   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
1074   then have "\<And>P. [x \<leftarrow> sort_key f xs . P (f x) ?pivot \<and> f l = f x] =
1075     [x \<leftarrow> sort_key f xs. P (f l) ?pivot \<and> f l = f x]" by simp
1076   note *** = this [of "op <"] this [of "op >"] this [of "op ="]
1077   show "[x \<leftarrow> ?rhs. f l = f x] = [x \<leftarrow> ?lhs. f l = f x]"
1078   proof (cases "f l" ?pivot rule: linorder_cases)
1079     case less
1080     then have "f l \<noteq> ?pivot" and "\<not> f l > ?pivot" by auto
1081     with less show ?thesis
1082       by (simp add: filter_sort [symmetric] ** ***)
1083   next
1084     case equal then show ?thesis
1085       by (simp add: * less_le)
1086   next
1087     case greater
1088     then have "f l \<noteq> ?pivot" and "\<not> f l < ?pivot" by auto
1089     with greater show ?thesis
1090       by (simp add: filter_sort [symmetric] ** ***)
1091   qed
1092 qed
1094 lemma sort_by_quicksort:
1095   "sort xs = sort [x\<leftarrow>xs. x < xs ! (length xs div 2)]
1096     @ [x\<leftarrow>xs. x = xs ! (length xs div 2)]
1097     @ sort [x\<leftarrow>xs. x > xs ! (length xs div 2)]" (is "sort ?lhs = ?rhs")
1098   using sort_key_by_quicksort [of "\<lambda>x. x", symmetric] by simp
1100 text {* A stable parametrized quicksort *}
1102 definition part :: "('b \<Rightarrow> 'a) \<Rightarrow> 'a \<Rightarrow> 'b list \<Rightarrow> 'b list \<times> 'b list \<times> 'b list" where
1103   "part f pivot xs = ([x \<leftarrow> xs. f x < pivot], [x \<leftarrow> xs. f x = pivot], [x \<leftarrow> xs. pivot < f x])"
1105 lemma part_code [code]:
1106   "part f pivot [] = ([], [], [])"
1107   "part f pivot (x # xs) = (let (lts, eqs, gts) = part f pivot xs; x' = f x in
1108      if x' < pivot then (x # lts, eqs, gts)
1109      else if x' > pivot then (lts, eqs, x # gts)
1110      else (lts, x # eqs, gts))"
1111   by (auto simp add: part_def Let_def split_def)
1113 lemma sort_key_by_quicksort_code [code]:
1114   "sort_key f xs = (case xs of [] \<Rightarrow> []
1115     | [x] \<Rightarrow> xs
1116     | [x, y] \<Rightarrow> (if f x \<le> f y then xs else [y, x])
1117     | _ \<Rightarrow> (let (lts, eqs, gts) = part f (f (xs ! (length xs div 2))) xs
1118        in sort_key f lts @ eqs @ sort_key f gts))"
1119 proof (cases xs)
1120   case Nil then show ?thesis by simp
1121 next
1122   case (Cons _ ys) note hyps = Cons show ?thesis
1123   proof (cases ys)
1124     case Nil with hyps show ?thesis by simp
1125   next
1126     case (Cons _ zs) note hyps = hyps Cons show ?thesis
1127     proof (cases zs)
1128       case Nil with hyps show ?thesis by auto
1129     next
1130       case Cons
1131       from sort_key_by_quicksort [of f xs]
1132       have "sort_key f xs = (let (lts, eqs, gts) = part f (f (xs ! (length xs div 2))) xs
1133         in sort_key f lts @ eqs @ sort_key f gts)"
1134       by (simp only: split_def Let_def part_def fst_conv snd_conv)
1135       with hyps Cons show ?thesis by (simp only: list.cases)
1136     qed
1137   qed
1138 qed
1140 end
1142 hide_const (open) part
1144 lemma multiset_of_remdups_le: "multiset_of (remdups xs) \<le> multiset_of xs"
1145   by (induct xs) (auto intro: order_trans)
1147 lemma multiset_of_update:
1148   "i < length ls \<Longrightarrow> multiset_of (ls[i := v]) = multiset_of ls - {#ls ! i#} + {#v#}"
1149 proof (induct ls arbitrary: i)
1150   case Nil then show ?case by simp
1151 next
1152   case (Cons x xs)
1153   show ?case
1154   proof (cases i)
1155     case 0 then show ?thesis by simp
1156   next
1157     case (Suc i')
1158     with Cons show ?thesis
1159       apply simp
1160       apply (subst add_assoc)
1161       apply (subst add_commute [of "{#v#}" "{#x#}"])
1162       apply (subst add_assoc [symmetric])
1163       apply simp
1164       apply (rule mset_le_multiset_union_diff_commute)
1165       apply (simp add: mset_le_single nth_mem_multiset_of)
1166       done
1167   qed
1168 qed
1170 lemma multiset_of_swap:
1171   "i < length ls \<Longrightarrow> j < length ls \<Longrightarrow>
1172     multiset_of (ls[j := ls ! i, i := ls ! j]) = multiset_of ls"
1173   by (cases "i = j") (simp_all add: multiset_of_update nth_mem_multiset_of)
1176 subsubsection {* Association lists -- including code generation *}
1178 text {* Preliminaries *}
1180 text {* Raw operations on lists *}
1182 definition join_raw :: "('key \<Rightarrow> 'val \<times> 'val \<Rightarrow> 'val) \<Rightarrow> ('key \<times> 'val) list \<Rightarrow> ('key \<times> 'val) list \<Rightarrow> ('key \<times> 'val) list"
1183 where
1184   "join_raw f xs ys = foldr (\<lambda>(k, v). map_default k v (%v'. f k (v', v))) ys xs"
1186 lemma join_raw_Nil [simp]:
1187   "join_raw f xs [] = xs"
1188 by (simp add: join_raw_def)
1190 lemma join_raw_Cons [simp]:
1191   "join_raw f xs ((k, v) # ys) = map_default k v (%v'. f k (v', v)) (join_raw f xs ys)"
1192 by (simp add: join_raw_def)
1194 lemma map_of_join_raw:
1195   assumes "distinct (map fst ys)"
1196   shows "map_of (join_raw f xs ys) x = (case map_of xs x of None => map_of ys x | Some v =>
1197     (case map_of ys x of None => Some v | Some v' => Some (f x (v, v'))))"
1198 using assms
1199 apply (induct ys)
1200 apply (auto simp add: map_of_map_default split: option.split)
1201 apply (metis map_of_eq_None_iff option.simps(2) weak_map_of_SomeI)
1202 by (metis Some_eq_map_of_iff map_of_eq_None_iff option.simps(2))
1204 lemma distinct_join_raw:
1205   assumes "distinct (map fst xs)"
1206   shows "distinct (map fst (join_raw f xs ys))"
1207 using assms
1208 proof (induct ys)
1209   case (Cons y ys)
1210   thus ?case by (cases y) (simp add: distinct_map_default)
1211 qed auto
1213 definition
1214   "subtract_entries_raw xs ys = foldr (%(k, v). AList.map_entry k (%v'. v' - v)) ys xs"
1216 lemma map_of_subtract_entries_raw:
1217   assumes "distinct (map fst ys)"
1218   shows "map_of (subtract_entries_raw xs ys) x = (case map_of xs x of None => None | Some v =>
1219     (case map_of ys x of None => Some v | Some v' => Some (v - v')))"
1220 using assms unfolding subtract_entries_raw_def
1221 apply (induct ys)
1222 apply auto
1223 apply (simp split: option.split)
1224 apply (simp add: map_of_map_entry)
1225 apply (auto split: option.split)
1226 apply (metis map_of_eq_None_iff option.simps(3) option.simps(4))
1227 by (metis map_of_eq_None_iff option.simps(4) option.simps(5))
1229 lemma distinct_subtract_entries_raw:
1230   assumes "distinct (map fst xs)"
1231   shows "distinct (map fst (subtract_entries_raw xs ys))"
1232 using assms
1233 unfolding subtract_entries_raw_def by (induct ys) (auto simp add: distinct_map_entry)
1235 text {* Operations on alists with distinct keys *}
1237 lift_definition join :: "('a \<Rightarrow> 'b \<times> 'b \<Rightarrow> 'b) \<Rightarrow> ('a, 'b) alist \<Rightarrow> ('a, 'b) alist \<Rightarrow> ('a, 'b) alist"
1238 is join_raw
1239 by (simp add: distinct_join_raw)
1241 lift_definition subtract_entries :: "('a, ('b :: minus)) alist \<Rightarrow> ('a, 'b) alist \<Rightarrow> ('a, 'b) alist"
1242 is subtract_entries_raw
1243 by (simp add: distinct_subtract_entries_raw)
1245 text {* Implementing multisets by means of association lists *}
1247 definition count_of :: "('a \<times> nat) list \<Rightarrow> 'a \<Rightarrow> nat" where
1248   "count_of xs x = (case map_of xs x of None \<Rightarrow> 0 | Some n \<Rightarrow> n)"
1250 lemma count_of_multiset:
1251   "count_of xs \<in> multiset"
1252 proof -
1253   let ?A = "{x::'a. 0 < (case map_of xs x of None \<Rightarrow> 0\<Colon>nat | Some (n\<Colon>nat) \<Rightarrow> n)}"
1254   have "?A \<subseteq> dom (map_of xs)"
1255   proof
1256     fix x
1257     assume "x \<in> ?A"
1258     then have "0 < (case map_of xs x of None \<Rightarrow> 0\<Colon>nat | Some (n\<Colon>nat) \<Rightarrow> n)" by simp
1259     then have "map_of xs x \<noteq> None" by (cases "map_of xs x") auto
1260     then show "x \<in> dom (map_of xs)" by auto
1261   qed
1262   with finite_dom_map_of [of xs] have "finite ?A"
1263     by (auto intro: finite_subset)
1264   then show ?thesis
1265     by (simp add: count_of_def fun_eq_iff multiset_def)
1266 qed
1268 lemma count_simps [simp]:
1269   "count_of [] = (\<lambda>_. 0)"
1270   "count_of ((x, n) # xs) = (\<lambda>y. if x = y then n else count_of xs y)"
1271   by (simp_all add: count_of_def fun_eq_iff)
1273 lemma count_of_empty:
1274   "x \<notin> fst ` set xs \<Longrightarrow> count_of xs x = 0"
1275   by (induct xs) (simp_all add: count_of_def)
1277 lemma count_of_filter:
1278   "count_of (List.filter (P \<circ> fst) xs) x = (if P x then count_of xs x else 0)"
1279   by (induct xs) auto
1281 lemma count_of_map_default [simp]:
1282   "count_of (map_default x b (%x. x + b) xs) y = (if x = y then count_of xs x + b else count_of xs y)"
1283 unfolding count_of_def by (simp add: map_of_map_default split: option.split)
1285 lemma count_of_join_raw:
1286   "distinct (map fst ys) ==> count_of xs x + count_of ys x = count_of (join_raw (%x (x, y). x + y) xs ys) x"
1287 unfolding count_of_def by (simp add: map_of_join_raw split: option.split)
1289 lemma count_of_subtract_entries_raw:
1290   "distinct (map fst ys) ==> count_of xs x - count_of ys x = count_of (subtract_entries_raw xs ys) x"
1291 unfolding count_of_def by (simp add: map_of_subtract_entries_raw split: option.split)
1293 text {* Code equations for multiset operations *}
1295 definition Bag :: "('a, nat) alist \<Rightarrow> 'a multiset" where
1296   "Bag xs = Abs_multiset (count_of (DAList.impl_of xs))"
1298 code_datatype Bag
1300 lemma count_Bag [simp, code]:
1301   "count (Bag xs) = count_of (DAList.impl_of xs)"
1302   by (simp add: Bag_def count_of_multiset Abs_multiset_inverse)
1304 lemma Mempty_Bag [code]:
1305   "{#} = Bag (DAList.empty)"
1306   by (simp add: multiset_eq_iff alist.Alist_inverse DAList.empty_def)
1308 lemma single_Bag [code]:
1309   "{#x#} = Bag (DAList.update x 1 DAList.empty)"
1310   by (simp add: multiset_eq_iff alist.Alist_inverse update.rep_eq empty.rep_eq)
1312 lemma union_Bag [code]:
1313   "Bag xs + Bag ys = Bag (join (\<lambda>x (n1, n2). n1 + n2) xs ys)"
1314 by (rule multiset_eqI) (simp add: count_of_join_raw alist.Alist_inverse distinct_join_raw join_def)
1316 lemma minus_Bag [code]:
1317   "Bag xs - Bag ys = Bag (subtract_entries xs ys)"
1318 by (rule multiset_eqI)
1319   (simp add: count_of_subtract_entries_raw alist.Alist_inverse distinct_subtract_entries_raw subtract_entries_def)
1321 lemma filter_Bag [code]:
1322   "Multiset.filter P (Bag xs) = Bag (DAList.filter (P \<circ> fst) xs)"
1323 by (rule multiset_eqI) (simp add: count_of_filter DAList.filter.rep_eq)
1325 lemma mset_less_eq_Bag [code]:
1326   "Bag xs \<le> A \<longleftrightarrow> (\<forall>(x, n) \<in> set (DAList.impl_of xs). count_of (DAList.impl_of xs) x \<le> count A x)"
1327     (is "?lhs \<longleftrightarrow> ?rhs")
1328 proof
1329   assume ?lhs then show ?rhs
1330     by (auto simp add: mset_le_def)
1331 next
1332   assume ?rhs
1333   show ?lhs
1334   proof (rule mset_less_eqI)
1335     fix x
1336     from `?rhs` have "count_of (DAList.impl_of xs) x \<le> count A x"
1337       by (cases "x \<in> fst ` set (DAList.impl_of xs)") (auto simp add: count_of_empty)
1338     then show "count (Bag xs) x \<le> count A x"
1339       by (simp add: mset_le_def)
1340   qed
1341 qed
1343 instantiation multiset :: (equal) equal
1344 begin
1346 definition
1347   [code]: "HOL.equal A B \<longleftrightarrow> (A::'a multiset) \<le> B \<and> B \<le> A"
1349 instance
1350   by default (simp add: equal_multiset_def eq_iff)
1352 end
1354 text {* Quickcheck generators *}
1356 definition (in term_syntax)
1357   bagify :: "('a\<Colon>typerep, nat) alist \<times> (unit \<Rightarrow> Code_Evaluation.term)
1358     \<Rightarrow> 'a multiset \<times> (unit \<Rightarrow> Code_Evaluation.term)" where
1359   [code_unfold]: "bagify xs = Code_Evaluation.valtermify Bag {\<cdot>} xs"
1361 notation fcomp (infixl "\<circ>>" 60)
1362 notation scomp (infixl "\<circ>\<rightarrow>" 60)
1364 instantiation multiset :: (random) random
1365 begin
1367 definition
1368   "Quickcheck.random i = Quickcheck.random i \<circ>\<rightarrow> (\<lambda>xs. Pair (bagify xs))"
1370 instance ..
1372 end
1374 no_notation fcomp (infixl "\<circ>>" 60)
1375 no_notation scomp (infixl "\<circ>\<rightarrow>" 60)
1377 instantiation multiset :: (exhaustive) exhaustive
1378 begin
1380 definition exhaustive_multiset :: "('a multiset => (bool * term list) option) => code_numeral => (bool * term list) option"
1381 where
1382   "exhaustive_multiset f i = Quickcheck_Exhaustive.exhaustive (%xs. f (Bag xs)) i"
1384 instance ..
1386 end
1388 instantiation multiset :: (full_exhaustive) full_exhaustive
1389 begin
1391 definition full_exhaustive_multiset :: "('a multiset * (unit => term) => (bool * term list) option) => code_numeral => (bool * term list) option"
1392 where
1393   "full_exhaustive_multiset f i = Quickcheck_Exhaustive.full_exhaustive (%xs. f (bagify xs)) i"
1395 instance ..
1397 end
1399 hide_const (open) bagify
1402 subsection {* The multiset order *}
1404 subsubsection {* Well-foundedness *}
1406 definition mult1 :: "('a \<times> 'a) set => ('a multiset \<times> 'a multiset) set" where
1407   "mult1 r = {(N, M). \<exists>a M0 K. M = M0 + {#a#} \<and> N = M0 + K \<and>
1408       (\<forall>b. b :# K --> (b, a) \<in> r)}"
1410 definition mult :: "('a \<times> 'a) set => ('a multiset \<times> 'a multiset) set" where
1411   "mult r = (mult1 r)\<^sup>+"
1413 lemma not_less_empty [iff]: "(M, {#}) \<notin> mult1 r"
1414 by (simp add: mult1_def)
1416 lemma less_add: "(N, M0 + {#a#}) \<in> mult1 r ==>
1417     (\<exists>M. (M, M0) \<in> mult1 r \<and> N = M + {#a#}) \<or>
1418     (\<exists>K. (\<forall>b. b :# K --> (b, a) \<in> r) \<and> N = M0 + K)"
1419   (is "_ \<Longrightarrow> ?case1 (mult1 r) \<or> ?case2")
1420 proof (unfold mult1_def)
1421   let ?r = "\<lambda>K a. \<forall>b. b :# K --> (b, a) \<in> r"
1422   let ?R = "\<lambda>N M. \<exists>a M0 K. M = M0 + {#a#} \<and> N = M0 + K \<and> ?r K a"
1423   let ?case1 = "?case1 {(N, M). ?R N M}"
1425   assume "(N, M0 + {#a#}) \<in> {(N, M). ?R N M}"
1426   then have "\<exists>a' M0' K.
1427       M0 + {#a#} = M0' + {#a'#} \<and> N = M0' + K \<and> ?r K a'" by simp
1428   then show "?case1 \<or> ?case2"
1429   proof (elim exE conjE)
1430     fix a' M0' K
1431     assume N: "N = M0' + K" and r: "?r K a'"
1432     assume "M0 + {#a#} = M0' + {#a'#}"
1433     then have "M0 = M0' \<and> a = a' \<or>
1434         (\<exists>K'. M0 = K' + {#a'#} \<and> M0' = K' + {#a#})"
1435       by (simp only: add_eq_conv_ex)
1436     then show ?thesis
1437     proof (elim disjE conjE exE)
1438       assume "M0 = M0'" "a = a'"
1439       with N r have "?r K a \<and> N = M0 + K" by simp
1440       then have ?case2 .. then show ?thesis ..
1441     next
1442       fix K'
1443       assume "M0' = K' + {#a#}"
1444       with N have n: "N = K' + K + {#a#}" by (simp add: add_ac)
1446       assume "M0 = K' + {#a'#}"
1447       with r have "?R (K' + K) M0" by blast
1448       with n have ?case1 by simp then show ?thesis ..
1449     qed
1450   qed
1451 qed
1453 lemma all_accessible: "wf r ==> \<forall>M. M \<in> acc (mult1 r)"
1454 proof
1455   let ?R = "mult1 r"
1456   let ?W = "acc ?R"
1457   {
1458     fix M M0 a
1459     assume M0: "M0 \<in> ?W"
1460       and wf_hyp: "!!b. (b, a) \<in> r ==> (\<forall>M \<in> ?W. M + {#b#} \<in> ?W)"
1461       and acc_hyp: "\<forall>M. (M, M0) \<in> ?R --> M + {#a#} \<in> ?W"
1462     have "M0 + {#a#} \<in> ?W"
1463     proof (rule accI [of "M0 + {#a#}"])
1464       fix N
1465       assume "(N, M0 + {#a#}) \<in> ?R"
1466       then have "((\<exists>M. (M, M0) \<in> ?R \<and> N = M + {#a#}) \<or>
1467           (\<exists>K. (\<forall>b. b :# K --> (b, a) \<in> r) \<and> N = M0 + K))"
1468         by (rule less_add)
1469       then show "N \<in> ?W"
1470       proof (elim exE disjE conjE)
1471         fix M assume "(M, M0) \<in> ?R" and N: "N = M + {#a#}"
1472         from acc_hyp have "(M, M0) \<in> ?R --> M + {#a#} \<in> ?W" ..
1473         from this and `(M, M0) \<in> ?R` have "M + {#a#} \<in> ?W" ..
1474         then show "N \<in> ?W" by (simp only: N)
1475       next
1476         fix K
1477         assume N: "N = M0 + K"
1478         assume "\<forall>b. b :# K --> (b, a) \<in> r"
1479         then have "M0 + K \<in> ?W"
1480         proof (induct K)
1481           case empty
1482           from M0 show "M0 + {#} \<in> ?W" by simp
1483         next
1484           case (add K x)
1485           from add.prems have "(x, a) \<in> r" by simp
1486           with wf_hyp have "\<forall>M \<in> ?W. M + {#x#} \<in> ?W" by blast
1487           moreover from add have "M0 + K \<in> ?W" by simp
1488           ultimately have "(M0 + K) + {#x#} \<in> ?W" ..
1489           then show "M0 + (K + {#x#}) \<in> ?W" by (simp only: add_assoc)
1490         qed
1491         then show "N \<in> ?W" by (simp only: N)
1492       qed
1493     qed
1494   } note tedious_reasoning = this
1496   assume wf: "wf r"
1497   fix M
1498   show "M \<in> ?W"
1499   proof (induct M)
1500     show "{#} \<in> ?W"
1501     proof (rule accI)
1502       fix b assume "(b, {#}) \<in> ?R"
1503       with not_less_empty show "b \<in> ?W" by contradiction
1504     qed
1506     fix M a assume "M \<in> ?W"
1507     from wf have "\<forall>M \<in> ?W. M + {#a#} \<in> ?W"
1508     proof induct
1509       fix a
1510       assume r: "!!b. (b, a) \<in> r ==> (\<forall>M \<in> ?W. M + {#b#} \<in> ?W)"
1511       show "\<forall>M \<in> ?W. M + {#a#} \<in> ?W"
1512       proof
1513         fix M assume "M \<in> ?W"
1514         then show "M + {#a#} \<in> ?W"
1515           by (rule acc_induct) (rule tedious_reasoning [OF _ r])
1516       qed
1517     qed
1518     from this and `M \<in> ?W` show "M + {#a#} \<in> ?W" ..
1519   qed
1520 qed
1522 theorem wf_mult1: "wf r ==> wf (mult1 r)"
1523 by (rule acc_wfI) (rule all_accessible)
1525 theorem wf_mult: "wf r ==> wf (mult r)"
1526 unfolding mult_def by (rule wf_trancl) (rule wf_mult1)
1529 subsubsection {* Closure-free presentation *}
1531 text {* One direction. *}
1533 lemma mult_implies_one_step:
1534   "trans r ==> (M, N) \<in> mult r ==>
1535     \<exists>I J K. N = I + J \<and> M = I + K \<and> J \<noteq> {#} \<and>
1536     (\<forall>k \<in> set_of K. \<exists>j \<in> set_of J. (k, j) \<in> r)"
1537 apply (unfold mult_def mult1_def set_of_def)
1538 apply (erule converse_trancl_induct, clarify)
1539  apply (rule_tac x = M0 in exI, simp, clarify)
1540 apply (case_tac "a :# K")
1541  apply (rule_tac x = I in exI)
1542  apply (simp (no_asm))
1543  apply (rule_tac x = "(K - {#a#}) + Ka" in exI)
1544  apply (simp (no_asm_simp) add: add_assoc [symmetric])
1545  apply (drule_tac f = "\<lambda>M. M - {#a#}" in arg_cong)
1546  apply (simp add: diff_union_single_conv)
1547  apply (simp (no_asm_use) add: trans_def)
1548  apply blast
1549 apply (subgoal_tac "a :# I")
1550  apply (rule_tac x = "I - {#a#}" in exI)
1551  apply (rule_tac x = "J + {#a#}" in exI)
1552  apply (rule_tac x = "K + Ka" in exI)
1553  apply (rule conjI)
1554   apply (simp add: multiset_eq_iff split: nat_diff_split)
1555  apply (rule conjI)
1556   apply (drule_tac f = "\<lambda>M. M - {#a#}" in arg_cong, simp)
1557   apply (simp add: multiset_eq_iff split: nat_diff_split)
1558  apply (simp (no_asm_use) add: trans_def)
1559  apply blast
1560 apply (subgoal_tac "a :# (M0 + {#a#})")
1561  apply simp
1562 apply (simp (no_asm))
1563 done
1565 lemma one_step_implies_mult_aux:
1566   "trans r ==>
1567     \<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))
1568       --> (I + K, I + J) \<in> mult r"
1569 apply (induct_tac n, auto)
1570 apply (frule size_eq_Suc_imp_eq_union, clarify)
1571 apply (rename_tac "J'", simp)
1572 apply (erule notE, auto)
1573 apply (case_tac "J' = {#}")
1574  apply (simp add: mult_def)
1575  apply (rule r_into_trancl)
1576  apply (simp add: mult1_def set_of_def, blast)
1577 txt {* Now we know @{term "J' \<noteq> {#}"}. *}
1578 apply (cut_tac M = K and P = "\<lambda>x. (x, a) \<in> r" in multiset_partition)
1579 apply (erule_tac P = "\<forall>k \<in> set_of K. ?P k" in rev_mp)
1580 apply (erule ssubst)
1581 apply (simp add: Ball_def, auto)
1582 apply (subgoal_tac
1583   "((I + {# x :# K. (x, a) \<in> r #}) + {# x :# K. (x, a) \<notin> r #},
1584     (I + {# x :# K. (x, a) \<in> r #}) + J') \<in> mult r")
1585  prefer 2
1586  apply force
1587 apply (simp (no_asm_use) add: add_assoc [symmetric] mult_def)
1588 apply (erule trancl_trans)
1589 apply (rule r_into_trancl)
1590 apply (simp add: mult1_def set_of_def)
1591 apply (rule_tac x = a in exI)
1592 apply (rule_tac x = "I + J'" in exI)
1594 done
1596 lemma one_step_implies_mult:
1597   "trans r ==> J \<noteq> {#} ==> \<forall>k \<in> set_of K. \<exists>j \<in> set_of J. (k, j) \<in> r
1598     ==> (I + K, I + J) \<in> mult r"
1599 using one_step_implies_mult_aux by blast
1602 subsubsection {* Partial-order properties *}
1604 definition less_multiset :: "'a\<Colon>order multiset \<Rightarrow> 'a multiset \<Rightarrow> bool" (infix "<#" 50) where
1605   "M' <# M \<longleftrightarrow> (M', M) \<in> mult {(x', x). x' < x}"
1607 definition le_multiset :: "'a\<Colon>order multiset \<Rightarrow> 'a multiset \<Rightarrow> bool" (infix "<=#" 50) where
1608   "M' <=# M \<longleftrightarrow> M' <# M \<or> M' = M"
1610 notation (xsymbols) less_multiset (infix "\<subset>#" 50)
1611 notation (xsymbols) le_multiset (infix "\<subseteq>#" 50)
1613 interpretation multiset_order: order le_multiset less_multiset
1614 proof -
1615   have irrefl: "\<And>M :: 'a multiset. \<not> M \<subset># M"
1616   proof
1617     fix M :: "'a multiset"
1618     assume "M \<subset># M"
1619     then have MM: "(M, M) \<in> mult {(x, y). x < y}" by (simp add: less_multiset_def)
1620     have "trans {(x'::'a, x). x' < x}"
1621       by (rule transI) simp
1622     moreover note MM
1623     ultimately have "\<exists>I J K. M = I + J \<and> M = I + K
1624       \<and> J \<noteq> {#} \<and> (\<forall>k\<in>set_of K. \<exists>j\<in>set_of J. (k, j) \<in> {(x, y). x < y})"
1625       by (rule mult_implies_one_step)
1626     then obtain I J K where "M = I + J" and "M = I + K"
1627       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
1628     then have aux1: "K \<noteq> {#}" and aux2: "\<forall>k\<in>set_of K. \<exists>j\<in>set_of K. k < j" by auto
1629     have "finite (set_of K)" by simp
1630     moreover note aux2
1631     ultimately have "set_of K = {}"
1632       by (induct rule: finite_induct) (auto intro: order_less_trans)
1633     with aux1 show False by simp
1634   qed
1635   have trans: "\<And>K M N :: 'a multiset. K \<subset># M \<Longrightarrow> M \<subset># N \<Longrightarrow> K \<subset># N"
1636     unfolding less_multiset_def mult_def by (blast intro: trancl_trans)
1637   show "class.order (le_multiset :: 'a multiset \<Rightarrow> _) less_multiset"
1638     by default (auto simp add: le_multiset_def irrefl dest: trans)
1639 qed
1641 lemma mult_less_irrefl [elim!]: "M \<subset># (M::'a::order multiset) ==> R"
1642   by simp
1645 subsubsection {* Monotonicity of multiset union *}
1647 lemma mult1_union: "(B, D) \<in> mult1 r ==> (C + B, C + D) \<in> mult1 r"
1648 apply (unfold mult1_def)
1649 apply auto
1650 apply (rule_tac x = a in exI)
1651 apply (rule_tac x = "C + M0" in exI)
1653 done
1655 lemma union_less_mono2: "B \<subset># D ==> C + B \<subset># C + (D::'a::order multiset)"
1656 apply (unfold less_multiset_def mult_def)
1657 apply (erule trancl_induct)
1658  apply (blast intro: mult1_union)
1659 apply (blast intro: mult1_union trancl_trans)
1660 done
1662 lemma union_less_mono1: "B \<subset># D ==> B + C \<subset># D + (C::'a::order multiset)"
1663 apply (subst add_commute [of B C])
1664 apply (subst add_commute [of D C])
1665 apply (erule union_less_mono2)
1666 done
1668 lemma union_less_mono:
1669   "A \<subset># C ==> B \<subset># D ==> A + B \<subset># C + (D::'a::order multiset)"
1670   by (blast intro!: union_less_mono1 union_less_mono2 multiset_order.less_trans)
1672 interpretation multiset_order: ordered_ab_semigroup_add plus le_multiset less_multiset
1673 proof
1674 qed (auto simp add: le_multiset_def intro: union_less_mono2)
1677 subsection {* Termination proofs with multiset orders *}
1679 lemma multi_member_skip: "x \<in># XS \<Longrightarrow> x \<in># {# y #} + XS"
1680   and multi_member_this: "x \<in># {# x #} + XS"
1681   and multi_member_last: "x \<in># {# x #}"
1682   by auto
1684 definition "ms_strict = mult pair_less"
1685 definition "ms_weak = ms_strict \<union> Id"
1687 lemma ms_reduction_pair: "reduction_pair (ms_strict, ms_weak)"
1688 unfolding reduction_pair_def ms_strict_def ms_weak_def pair_less_def
1689 by (auto intro: wf_mult1 wf_trancl simp: mult_def)
1691 lemma smsI:
1692   "(set_of A, set_of B) \<in> max_strict \<Longrightarrow> (Z + A, Z + B) \<in> ms_strict"
1693   unfolding ms_strict_def
1694 by (rule one_step_implies_mult) (auto simp add: max_strict_def pair_less_def elim!:max_ext.cases)
1696 lemma wmsI:
1697   "(set_of A, set_of B) \<in> max_strict \<or> A = {#} \<and> B = {#}
1698   \<Longrightarrow> (Z + A, Z + B) \<in> ms_weak"
1699 unfolding ms_weak_def ms_strict_def
1700 by (auto simp add: pair_less_def max_strict_def elim!:max_ext.cases intro: one_step_implies_mult)
1702 inductive pw_leq
1703 where
1704   pw_leq_empty: "pw_leq {#} {#}"
1705 | pw_leq_step:  "\<lbrakk>(x,y) \<in> pair_leq; pw_leq X Y \<rbrakk> \<Longrightarrow> pw_leq ({#x#} + X) ({#y#} + Y)"
1707 lemma pw_leq_lstep:
1708   "(x, y) \<in> pair_leq \<Longrightarrow> pw_leq {#x#} {#y#}"
1709 by (drule pw_leq_step) (rule pw_leq_empty, simp)
1711 lemma pw_leq_split:
1712   assumes "pw_leq X Y"
1713   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 = {#}))"
1714   using assms
1715 proof (induct)
1716   case pw_leq_empty thus ?case by auto
1717 next
1718   case (pw_leq_step x y X Y)
1719   then obtain A B Z where
1720     [simp]: "X = A + Z" "Y = B + Z"
1721       and 1[simp]: "(set_of A, set_of B) \<in> max_strict \<or> (B = {#} \<and> A = {#})"
1722     by auto
1723   from pw_leq_step have "x = y \<or> (x, y) \<in> pair_less"
1724     unfolding pair_leq_def by auto
1725   thus ?case
1726   proof
1727     assume [simp]: "x = y"
1728     have
1729       "{#x#} + X = A + ({#y#}+Z)
1730       \<and> {#y#} + Y = B + ({#y#}+Z)
1731       \<and> ((set_of A, set_of B) \<in> max_strict \<or> (B = {#} \<and> A = {#}))"
1732       by (auto simp: add_ac)
1733     thus ?case by (intro exI)
1734   next
1735     assume A: "(x, y) \<in> pair_less"
1736     let ?A' = "{#x#} + A" and ?B' = "{#y#} + B"
1737     have "{#x#} + X = ?A' + Z"
1738       "{#y#} + Y = ?B' + Z"
1740     moreover have
1741       "(set_of ?A', set_of ?B') \<in> max_strict"
1742       using 1 A unfolding max_strict_def
1743       by (auto elim!: max_ext.cases)
1744     ultimately show ?thesis by blast
1745   qed
1746 qed
1748 lemma
1749   assumes pwleq: "pw_leq Z Z'"
1750   shows ms_strictI: "(set_of A, set_of B) \<in> max_strict \<Longrightarrow> (Z + A, Z' + B) \<in> ms_strict"
1751   and   ms_weakI1:  "(set_of A, set_of B) \<in> max_strict \<Longrightarrow> (Z + A, Z' + B) \<in> ms_weak"
1752   and   ms_weakI2:  "(Z + {#}, Z' + {#}) \<in> ms_weak"
1753 proof -
1754   from pw_leq_split[OF pwleq]
1755   obtain A' B' Z''
1756     where [simp]: "Z = A' + Z''" "Z' = B' + Z''"
1757     and mx_or_empty: "(set_of A', set_of B') \<in> max_strict \<or> (A' = {#} \<and> B' = {#})"
1758     by blast
1759   {
1760     assume max: "(set_of A, set_of B) \<in> max_strict"
1761     from mx_or_empty
1762     have "(Z'' + (A + A'), Z'' + (B + B')) \<in> ms_strict"
1763     proof
1764       assume max': "(set_of A', set_of B') \<in> max_strict"
1765       with max have "(set_of (A + A'), set_of (B + B')) \<in> max_strict"
1766         by (auto simp: max_strict_def intro: max_ext_additive)
1767       thus ?thesis by (rule smsI)
1768     next
1769       assume [simp]: "A' = {#} \<and> B' = {#}"
1770       show ?thesis by (rule smsI) (auto intro: max)
1771     qed
1772     thus "(Z + A, Z' + B) \<in> ms_strict" by (simp add:add_ac)
1773     thus "(Z + A, Z' + B) \<in> ms_weak" by (simp add: ms_weak_def)
1774   }
1775   from mx_or_empty
1776   have "(Z'' + A', Z'' + B') \<in> ms_weak" by (rule wmsI)
1777   thus "(Z + {#}, Z' + {#}) \<in> ms_weak" by (simp add:add_ac)
1778 qed
1780 lemma empty_neutral: "{#} + x = x" "x + {#} = x"
1781 and nonempty_plus: "{# x #} + rs \<noteq> {#}"
1782 and nonempty_single: "{# x #} \<noteq> {#}"
1783 by auto
1785 setup {*
1786 let
1787   fun msetT T = Type (@{type_name multiset}, [T]);
1789   fun mk_mset T [] = Const (@{const_abbrev Mempty}, msetT T)
1790     | mk_mset T [x] = Const (@{const_name single}, T --> msetT T) \$ x
1791     | mk_mset T (x :: xs) =
1792           Const (@{const_name plus}, msetT T --> msetT T --> msetT T) \$
1793                 mk_mset T [x] \$ mk_mset T xs
1795   fun mset_member_tac m i =
1796       (if m <= 0 then
1797            rtac @{thm multi_member_this} i ORELSE rtac @{thm multi_member_last} i
1798        else
1799            rtac @{thm multi_member_skip} i THEN mset_member_tac (m - 1) i)
1801   val mset_nonempty_tac =
1802       rtac @{thm nonempty_plus} ORELSE' rtac @{thm nonempty_single}
1804   val regroup_munion_conv =
1805       Function_Lib.regroup_conv @{const_abbrev Mempty} @{const_name plus}
1806         (map (fn t => t RS eq_reflection) (@{thms add_ac} @ @{thms empty_neutral}))
1808   fun unfold_pwleq_tac i =
1809     (rtac @{thm pw_leq_step} i THEN (fn st => unfold_pwleq_tac (i + 1) st))
1810       ORELSE (rtac @{thm pw_leq_lstep} i)
1811       ORELSE (rtac @{thm pw_leq_empty} i)
1813   val set_of_simps = [@{thm set_of_empty}, @{thm set_of_single}, @{thm set_of_union},
1814                       @{thm Un_insert_left}, @{thm Un_empty_left}]
1815 in
1816   ScnpReconstruct.multiset_setup (ScnpReconstruct.Multiset
1817   {
1818     msetT=msetT, mk_mset=mk_mset, mset_regroup_conv=regroup_munion_conv,
1819     mset_member_tac=mset_member_tac, mset_nonempty_tac=mset_nonempty_tac,
1820     mset_pwleq_tac=unfold_pwleq_tac, set_of_simps=set_of_simps,
1821     smsI'= @{thm ms_strictI}, wmsI2''= @{thm ms_weakI2}, wmsI1= @{thm ms_weakI1},
1822     reduction_pair= @{thm ms_reduction_pair}
1823   })
1824 end
1825 *}
1828 subsection {* Legacy theorem bindings *}
1830 lemmas multi_count_eq = multiset_eq_iff [symmetric]
1832 lemma union_commute: "M + N = N + (M::'a multiset)"
1833   by (fact add_commute)
1835 lemma union_assoc: "(M + N) + K = M + (N + (K::'a multiset))"
1836   by (fact add_assoc)
1838 lemma union_lcomm: "M + (N + K) = N + (M + (K::'a multiset))"
1839   by (fact add_left_commute)
1841 lemmas union_ac = union_assoc union_commute union_lcomm
1843 lemma union_right_cancel: "M + K = N + K \<longleftrightarrow> M = (N::'a multiset)"
1844   by (fact add_right_cancel)
1846 lemma union_left_cancel: "K + M = K + N \<longleftrightarrow> M = (N::'a multiset)"
1847   by (fact add_left_cancel)
1849 lemma multi_union_self_other_eq: "(A::'a multiset) + X = A + Y \<Longrightarrow> X = Y"
1850   by (fact add_imp_eq)
1852 lemma mset_less_trans: "(M::'a multiset) < K \<Longrightarrow> K < N \<Longrightarrow> M < N"
1853   by (fact order_less_trans)
1855 lemma multiset_inter_commute: "A #\<inter> B = B #\<inter> A"
1856   by (fact inf.commute)
1858 lemma multiset_inter_assoc: "A #\<inter> (B #\<inter> C) = A #\<inter> B #\<inter> C"
1859   by (fact inf.assoc [symmetric])
1861 lemma multiset_inter_left_commute: "A #\<inter> (B #\<inter> C) = B #\<inter> (A #\<inter> C)"
1862   by (fact inf.left_commute)
1864 lemmas multiset_inter_ac =
1865   multiset_inter_commute
1866   multiset_inter_assoc
1867   multiset_inter_left_commute
1869 lemma mult_less_not_refl:
1870   "\<not> M \<subset># (M::'a::order multiset)"
1871   by (fact multiset_order.less_irrefl)
1873 lemma mult_less_trans:
1874   "K \<subset># M ==> M \<subset># N ==> K \<subset># (N::'a::order multiset)"
1875   by (fact multiset_order.less_trans)
1877 lemma mult_less_not_sym:
1878   "M \<subset># N ==> \<not> N \<subset># (M::'a::order multiset)"
1879   by (fact multiset_order.less_not_sym)
1881 lemma mult_less_asym:
1882   "M \<subset># N ==> (\<not> P ==> N \<subset># (M::'a::order multiset)) ==> P"
1883   by (fact multiset_order.less_asym)
1885 ML {*
1886 fun multiset_postproc _ maybe_name all_values (T as Type (_, [elem_T]))
1887                       (Const _ \$ t') =
1888     let
1889       val (maybe_opt, ps) =
1890         Nitpick_Model.dest_plain_fun t' ||> op ~~
1891         ||> map (apsnd (snd o HOLogic.dest_number))
1892       fun elems_for t =
1893         case AList.lookup (op =) ps t of
1894           SOME n => replicate n t
1895         | NONE => [Const (maybe_name, elem_T --> elem_T) \$ t]
1896     in
1897       case maps elems_for (all_values elem_T) @
1898            (if maybe_opt then [Const (Nitpick_Model.unrep (), elem_T)]
1899             else []) of
1900         [] => Const (@{const_name zero_class.zero}, T)
1901       | ts => foldl1 (fn (t1, t2) =>
1902                          Const (@{const_name plus_class.plus}, T --> T --> T)
1903                          \$ t1 \$ t2)
1904                      (map (curry (op \$) (Const (@{const_name single},
1905                                                 elem_T --> T))) ts)
1906     end
1907   | multiset_postproc _ _ _ _ t = t
1908 *}
1910 declaration {*
1911 Nitpick_Model.register_term_postprocessor @{typ "'a multiset"}
1912     multiset_postproc
1913 *}
1915 end