src/HOL/Library/Multiset.thy
 author bulwahn Wed Feb 01 15:28:02 2012 +0100 (2012-02-01) changeset 46394 68f973ffd763 parent 46238 9ace9e5b79be child 46730 e3b99d0231bc permissions -rw-r--r--
improving code equations for multisets that violated the distinct AList abstraction
```     1 (*  Title:      HOL/Library/Multiset.thy
```
```     2     Author:     Tobias Nipkow, Markus Wenzel, Lawrence C Paulson, Norbert Voelker
```
```     3 *)
```
```     4
```
```     5 header {* (Finite) multisets *}
```
```     6
```
```     7 theory Multiset
```
```     8 imports Main DAList
```
```     9 begin
```
```    10
```
```    11 subsection {* The type of multisets *}
```
```    12
```
```    13 definition "multiset = {f :: 'a => nat. finite {x. f x > 0}}"
```
```    14
```
```    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
```
```    21
```
```    22 lemmas multiset_typedef = Abs_multiset_inverse count_inverse count
```
```    23
```
```    24 abbreviation Melem :: "'a => 'a multiset => bool"  ("(_/ :# _)" [50, 51] 50) where
```
```    25   "a :# M == 0 < count M a"
```
```    26
```
```    27 notation (xsymbols)
```
```    28   Melem (infix "\<in>#" 50)
```
```    29
```
```    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)
```
```    33
```
```    34 lemma multiset_eqI:
```
```    35   "(\<And>x. count A x = count B x) \<Longrightarrow> A = B"
```
```    36   using multiset_eq_iff by auto
```
```    37
```
```    38 text {*
```
```    39  \medskip Preservation of the representing set @{term multiset}.
```
```    40 *}
```
```    41
```
```    42 lemma const0_in_multiset:
```
```    43   "(\<lambda>a. 0) \<in> multiset"
```
```    44   by (simp add: multiset_def)
```
```    45
```
```    46 lemma only1_in_multiset:
```
```    47   "(\<lambda>b. if b = a then n else 0) \<in> multiset"
```
```    48   by (simp add: multiset_def)
```
```    49
```
```    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)
```
```    53
```
```    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
```
```    63
```
```    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
```
```    73
```
```    74 lemmas in_multiset = const0_in_multiset only1_in_multiset
```
```    75   union_preserves_multiset diff_preserves_multiset filter_preserves_multiset
```
```    76
```
```    77
```
```    78 subsection {* Representing multisets *}
```
```    79
```
```    80 text {* Multiset enumeration *}
```
```    81
```
```    82 instantiation multiset :: (type) "{zero, plus}"
```
```    83 begin
```
```    84
```
```    85 definition Mempty_def:
```
```    86   "0 = Abs_multiset (\<lambda>a. 0)"
```
```    87
```
```    88 abbreviation Mempty :: "'a multiset" ("{#}") where
```
```    89   "Mempty \<equiv> 0"
```
```    90
```
```    91 definition union_def:
```
```    92   "M + N = Abs_multiset (\<lambda>a. count M a + count N a)"
```
```    93
```
```    94 instance ..
```
```    95
```
```    96 end
```
```    97
```
```    98 definition single :: "'a => 'a multiset" where
```
```    99   "single a = Abs_multiset (\<lambda>b. if b = a then 1 else 0)"
```
```   100
```
```   101 syntax
```
```   102   "_multiset" :: "args => 'a multiset"    ("{#(_)#}")
```
```   103 translations
```
```   104   "{#x, xs#}" == "{#x#} + {#xs#}"
```
```   105   "{#x#}" == "CONST single x"
```
```   106
```
```   107 lemma count_empty [simp]: "count {#} a = 0"
```
```   108   by (simp add: Mempty_def in_multiset multiset_typedef)
```
```   109
```
```   110 lemma count_single [simp]: "count {#b#} a = (if b = a then 1 else 0)"
```
```   111   by (simp add: single_def in_multiset multiset_typedef)
```
```   112
```
```   113
```
```   114 subsection {* Basic operations *}
```
```   115
```
```   116 subsubsection {* Union *}
```
```   117
```
```   118 lemma count_union [simp]: "count (M + N) a = count M a + count N a"
```
```   119   by (simp add: union_def in_multiset multiset_typedef)
```
```   120
```
```   121 instance multiset :: (type) cancel_comm_monoid_add proof
```
```   122 qed (simp_all add: multiset_eq_iff)
```
```   123
```
```   124
```
```   125 subsubsection {* Difference *}
```
```   126
```
```   127 instantiation multiset :: (type) minus
```
```   128 begin
```
```   129
```
```   130 definition diff_def:
```
```   131   "M - N = Abs_multiset (\<lambda>a. count M a - count N a)"
```
```   132
```
```   133 instance ..
```
```   134
```
```   135 end
```
```   136
```
```   137 lemma count_diff [simp]: "count (M - N) a = count M a - count N a"
```
```   138   by (simp add: diff_def in_multiset multiset_typedef)
```
```   139
```
```   140 lemma diff_empty [simp]: "M - {#} = M \<and> {#} - M = {#}"
```
```   141 by(simp add: multiset_eq_iff)
```
```   142
```
```   143 lemma diff_cancel[simp]: "A - A = {#}"
```
```   144 by (rule multiset_eqI) simp
```
```   145
```
```   146 lemma diff_union_cancelR [simp]: "M + N - N = (M::'a multiset)"
```
```   147 by(simp add: multiset_eq_iff)
```
```   148
```
```   149 lemma diff_union_cancelL [simp]: "N + M - N = (M::'a multiset)"
```
```   150 by(simp add: multiset_eq_iff)
```
```   151
```
```   152 lemma insert_DiffM:
```
```   153   "x \<in># M \<Longrightarrow> {#x#} + (M - {#x#}) = M"
```
```   154   by (clarsimp simp: multiset_eq_iff)
```
```   155
```
```   156 lemma insert_DiffM2 [simp]:
```
```   157   "x \<in># M \<Longrightarrow> M - {#x#} + {#x#} = M"
```
```   158   by (clarsimp simp: multiset_eq_iff)
```
```   159
```
```   160 lemma diff_right_commute:
```
```   161   "(M::'a multiset) - N - Q = M - Q - N"
```
```   162   by (auto simp add: multiset_eq_iff)
```
```   163
```
```   164 lemma diff_add:
```
```   165   "(M::'a multiset) - (N + Q) = M - N - Q"
```
```   166 by (simp add: multiset_eq_iff)
```
```   167
```
```   168 lemma diff_union_swap:
```
```   169   "a \<noteq> b \<Longrightarrow> M - {#a#} + {#b#} = M + {#b#} - {#a#}"
```
```   170   by (auto simp add: multiset_eq_iff)
```
```   171
```
```   172 lemma diff_union_single_conv:
```
```   173   "a \<in># J \<Longrightarrow> I + J - {#a#} = I + (J - {#a#})"
```
```   174   by (simp add: multiset_eq_iff)
```
```   175
```
```   176
```
```   177 subsubsection {* Equality of multisets *}
```
```   178
```
```   179 lemma single_not_empty [simp]: "{#a#} \<noteq> {#} \<and> {#} \<noteq> {#a#}"
```
```   180   by (simp add: multiset_eq_iff)
```
```   181
```
```   182 lemma single_eq_single [simp]: "{#a#} = {#b#} \<longleftrightarrow> a = b"
```
```   183   by (auto simp add: multiset_eq_iff)
```
```   184
```
```   185 lemma union_eq_empty [iff]: "M + N = {#} \<longleftrightarrow> M = {#} \<and> N = {#}"
```
```   186   by (auto simp add: multiset_eq_iff)
```
```   187
```
```   188 lemma empty_eq_union [iff]: "{#} = M + N \<longleftrightarrow> M = {#} \<and> N = {#}"
```
```   189   by (auto simp add: multiset_eq_iff)
```
```   190
```
```   191 lemma multi_self_add_other_not_self [simp]: "M = M + {#x#} \<longleftrightarrow> False"
```
```   192   by (auto simp add: multiset_eq_iff)
```
```   193
```
```   194 lemma diff_single_trivial:
```
```   195   "\<not> x \<in># M \<Longrightarrow> M - {#x#} = M"
```
```   196   by (auto simp add: multiset_eq_iff)
```
```   197
```
```   198 lemma diff_single_eq_union:
```
```   199   "x \<in># M \<Longrightarrow> M - {#x#} = N \<longleftrightarrow> M = N + {#x#}"
```
```   200   by auto
```
```   201
```
```   202 lemma union_single_eq_diff:
```
```   203   "M + {#x#} = N \<Longrightarrow> M = N - {#x#}"
```
```   204   by (auto dest: sym)
```
```   205
```
```   206 lemma union_single_eq_member:
```
```   207   "M + {#x#} = N \<Longrightarrow> x \<in># N"
```
```   208   by auto
```
```   209
```
```   210 lemma union_is_single:
```
```   211   "M + N = {#a#} \<longleftrightarrow> M = {#a#} \<and> N={#} \<or> M = {#} \<and> N = {#a#}" (is "?lhs = ?rhs")proof
```
```   212   assume ?rhs then show ?lhs by auto
```
```   213 next
```
```   214   assume ?lhs thus ?rhs
```
```   215     by(simp add: multiset_eq_iff split:if_splits) (metis add_is_1)
```
```   216 qed
```
```   217
```
```   218 lemma single_is_union:
```
```   219   "{#a#} = M + N \<longleftrightarrow> {#a#} = M \<and> N = {#} \<or> M = {#} \<and> {#a#} = N"
```
```   220   by (auto simp add: eq_commute [of "{#a#}" "M + N"] union_is_single)
```
```   221
```
```   222 lemma add_eq_conv_diff:
```
```   223   "M + {#a#} = N + {#b#} \<longleftrightarrow> M = N \<and> a = b \<or> M = N - {#a#} + {#b#} \<and> N = M - {#b#} + {#a#}"  (is "?lhs = ?rhs")
```
```   224 (* shorter: by (simp add: multiset_eq_iff) fastforce *)
```
```   225 proof
```
```   226   assume ?rhs then show ?lhs
```
```   227   by (auto simp add: add_assoc add_commute [of "{#b#}"])
```
```   228     (drule sym, simp add: add_assoc [symmetric])
```
```   229 next
```
```   230   assume ?lhs
```
```   231   show ?rhs
```
```   232   proof (cases "a = b")
```
```   233     case True with `?lhs` show ?thesis by simp
```
```   234   next
```
```   235     case False
```
```   236     from `?lhs` have "a \<in># N + {#b#}" by (rule union_single_eq_member)
```
```   237     with False have "a \<in># N" by auto
```
```   238     moreover from `?lhs` have "M = N + {#b#} - {#a#}" by (rule union_single_eq_diff)
```
```   239     moreover note False
```
```   240     ultimately show ?thesis by (auto simp add: diff_right_commute [of _ "{#a#}"] diff_union_swap)
```
```   241   qed
```
```   242 qed
```
```   243
```
```   244 lemma insert_noteq_member:
```
```   245   assumes BC: "B + {#b#} = C + {#c#}"
```
```   246    and bnotc: "b \<noteq> c"
```
```   247   shows "c \<in># B"
```
```   248 proof -
```
```   249   have "c \<in># C + {#c#}" by simp
```
```   250   have nc: "\<not> c \<in># {#b#}" using bnotc by simp
```
```   251   then have "c \<in># B + {#b#}" using BC by simp
```
```   252   then show "c \<in># B" using nc by simp
```
```   253 qed
```
```   254
```
```   255 lemma add_eq_conv_ex:
```
```   256   "(M + {#a#} = N + {#b#}) =
```
```   257     (M = N \<and> a = b \<or> (\<exists>K. M = K + {#b#} \<and> N = K + {#a#}))"
```
```   258   by (auto simp add: add_eq_conv_diff)
```
```   259
```
```   260
```
```   261 subsubsection {* Pointwise ordering induced by count *}
```
```   262
```
```   263 instantiation multiset :: (type) ordered_ab_semigroup_add_imp_le
```
```   264 begin
```
```   265
```
```   266 definition less_eq_multiset :: "'a multiset \<Rightarrow> 'a multiset \<Rightarrow> bool" where
```
```   267   mset_le_def: "A \<le> B \<longleftrightarrow> (\<forall>a. count A a \<le> count B a)"
```
```   268
```
```   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"
```
```   271
```
```   272 instance proof
```
```   273 qed (auto simp add: mset_le_def mset_less_def multiset_eq_iff intro: order_trans antisym)
```
```   274
```
```   275 end
```
```   276
```
```   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)
```
```   280
```
```   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
```
```   286
```
```   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)
```
```   290
```
```   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)
```
```   294
```
```   295 lemma mset_le_mono_add:
```
```   296   "(A::'a multiset) \<le> B \<Longrightarrow> C \<le> D \<Longrightarrow> A + C \<le> B + D"
```
```   297   by (fact add_mono)
```
```   298
```
```   299 lemma mset_le_add_left [simp]:
```
```   300   "(A::'a multiset) \<le> A + B"
```
```   301   unfolding mset_le_def by auto
```
```   302
```
```   303 lemma mset_le_add_right [simp]:
```
```   304   "B \<le> (A::'a multiset) + B"
```
```   305   unfolding mset_le_def by auto
```
```   306
```
```   307 lemma mset_le_single:
```
```   308   "a :# B \<Longrightarrow> {#a#} \<le> B"
```
```   309   by (simp add: mset_le_def)
```
```   310
```
```   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)
```
```   314
```
```   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)
```
```   318
```
```   319 lemma diff_le_self[simp]: "(M::'a multiset) - N \<le> M"
```
```   320 by(simp add: mset_le_def)
```
```   321
```
```   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
```
```   327
```
```   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
```
```   333
```
```   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
```
```   342
```
```   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
```
```   348
```
```   349 lemma mset_less_of_empty[simp]: "A < {#} \<longleftrightarrow> False"
```
```   350   by (auto simp add: mset_less_def mset_le_def multiset_eq_iff)
```
```   351
```
```   352 lemma multi_psub_of_add_self[simp]: "A < A + {#x#}"
```
```   353   by (auto simp: mset_le_def mset_less_def)
```
```   354
```
```   355 lemma multi_psub_self[simp]: "(A::'a multiset) < A = False"
```
```   356   by simp
```
```   357
```
```   358 lemma mset_less_add_bothsides:
```
```   359   "T + {#x#} < S + {#x#} \<Longrightarrow> T < S"
```
```   360   by (fact add_less_imp_less_right)
```
```   361
```
```   362 lemma mset_less_empty_nonempty:
```
```   363   "{#} < S \<longleftrightarrow> S \<noteq> {#}"
```
```   364   by (auto simp: mset_le_def mset_less_def)
```
```   365
```
```   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)
```
```   369
```
```   370
```
```   371 subsubsection {* Intersection *}
```
```   372
```
```   373 instantiation multiset :: (type) semilattice_inf
```
```   374 begin
```
```   375
```
```   376 definition inf_multiset :: "'a multiset \<Rightarrow> 'a multiset \<Rightarrow> 'a multiset" where
```
```   377   multiset_inter_def: "inf_multiset A B = A - (A - B)"
```
```   378
```
```   379 instance proof -
```
```   380   have aux: "\<And>m n q :: nat. m \<le> n \<Longrightarrow> m \<le> q \<Longrightarrow> m \<le> n - (n - q)" by arith
```
```   381   show "OFCLASS('a multiset, semilattice_inf_class)" proof
```
```   382   qed (auto simp add: multiset_inter_def mset_le_def aux)
```
```   383 qed
```
```   384
```
```   385 end
```
```   386
```
```   387 abbreviation multiset_inter :: "'a multiset \<Rightarrow> 'a multiset \<Rightarrow> 'a multiset" (infixl "#\<inter>" 70) where
```
```   388   "multiset_inter \<equiv> inf"
```
```   389
```
```   390 lemma multiset_inter_count [simp]:
```
```   391   "count (A #\<inter> B) x = min (count A x) (count B x)"
```
```   392   by (simp add: multiset_inter_def multiset_typedef)
```
```   393
```
```   394 lemma multiset_inter_single: "a \<noteq> b \<Longrightarrow> {#a#} #\<inter> {#b#} = {#}"
```
```   395   by (rule multiset_eqI) (auto simp add: multiset_inter_count)
```
```   396
```
```   397 lemma multiset_union_diff_commute:
```
```   398   assumes "B #\<inter> C = {#}"
```
```   399   shows "A + B - C = A - C + B"
```
```   400 proof (rule multiset_eqI)
```
```   401   fix x
```
```   402   from assms have "min (count B x) (count C x) = 0"
```
```   403     by (auto simp add: multiset_inter_count multiset_eq_iff)
```
```   404   then have "count B x = 0 \<or> count C x = 0"
```
```   405     by auto
```
```   406   then show "count (A + B - C) x = count (A - C + B) x"
```
```   407     by auto
```
```   408 qed
```
```   409
```
```   410
```
```   411 subsubsection {* Filter (with comprehension syntax) *}
```
```   412
```
```   413 text {* Multiset comprehension *}
```
```   414
```
```   415 definition filter :: "('a \<Rightarrow> bool) \<Rightarrow> 'a multiset \<Rightarrow> 'a multiset" where
```
```   416   "filter P M = Abs_multiset (\<lambda>x. if P x then count M x else 0)"
```
```   417
```
```   418 hide_const (open) filter
```
```   419
```
```   420 lemma count_filter [simp]:
```
```   421   "count (Multiset.filter P M) a = (if P a then count M a else 0)"
```
```   422   by (simp add: filter_def in_multiset multiset_typedef)
```
```   423
```
```   424 lemma filter_empty [simp]:
```
```   425   "Multiset.filter P {#} = {#}"
```
```   426   by (rule multiset_eqI) simp
```
```   427
```
```   428 lemma filter_single [simp]:
```
```   429   "Multiset.filter P {#x#} = (if P x then {#x#} else {#})"
```
```   430   by (rule multiset_eqI) simp
```
```   431
```
```   432 lemma filter_union [simp]:
```
```   433   "Multiset.filter P (M + N) = Multiset.filter P M + Multiset.filter P N"
```
```   434   by (rule multiset_eqI) simp
```
```   435
```
```   436 lemma filter_diff [simp]:
```
```   437   "Multiset.filter P (M - N) = Multiset.filter P M - Multiset.filter P N"
```
```   438   by (rule multiset_eqI) simp
```
```   439
```
```   440 lemma filter_inter [simp]:
```
```   441   "Multiset.filter P (M #\<inter> N) = Multiset.filter P M #\<inter> Multiset.filter P N"
```
```   442   by (rule multiset_eqI) simp
```
```   443
```
```   444 syntax
```
```   445   "_MCollect" :: "pttrn \<Rightarrow> 'a multiset \<Rightarrow> bool \<Rightarrow> 'a multiset"    ("(1{# _ :# _./ _#})")
```
```   446 syntax (xsymbol)
```
```   447   "_MCollect" :: "pttrn \<Rightarrow> 'a multiset \<Rightarrow> bool \<Rightarrow> 'a multiset"    ("(1{# _ \<in># _./ _#})")
```
```   448 translations
```
```   449   "{#x \<in># M. P#}" == "CONST Multiset.filter (\<lambda>x. P) M"
```
```   450
```
```   451
```
```   452 subsubsection {* Set of elements *}
```
```   453
```
```   454 definition set_of :: "'a multiset => 'a set" where
```
```   455   "set_of M = {x. x :# M}"
```
```   456
```
```   457 lemma set_of_empty [simp]: "set_of {#} = {}"
```
```   458 by (simp add: set_of_def)
```
```   459
```
```   460 lemma set_of_single [simp]: "set_of {#b#} = {b}"
```
```   461 by (simp add: set_of_def)
```
```   462
```
```   463 lemma set_of_union [simp]: "set_of (M + N) = set_of M \<union> set_of N"
```
```   464 by (auto simp add: set_of_def)
```
```   465
```
```   466 lemma set_of_eq_empty_iff [simp]: "(set_of M = {}) = (M = {#})"
```
```   467 by (auto simp add: set_of_def multiset_eq_iff)
```
```   468
```
```   469 lemma mem_set_of_iff [simp]: "(x \<in> set_of M) = (x :# M)"
```
```   470 by (auto simp add: set_of_def)
```
```   471
```
```   472 lemma set_of_filter [simp]: "set_of {# x:#M. P x #} = set_of M \<inter> {x. P x}"
```
```   473 by (auto simp add: set_of_def)
```
```   474
```
```   475 lemma finite_set_of [iff]: "finite (set_of M)"
```
```   476   using count [of M] by (simp add: multiset_def set_of_def)
```
```   477
```
```   478
```
```   479 subsubsection {* Size *}
```
```   480
```
```   481 instantiation multiset :: (type) size
```
```   482 begin
```
```   483
```
```   484 definition size_def:
```
```   485   "size M = setsum (count M) (set_of M)"
```
```   486
```
```   487 instance ..
```
```   488
```
```   489 end
```
```   490
```
```   491 lemma size_empty [simp]: "size {#} = 0"
```
```   492 by (simp add: size_def)
```
```   493
```
```   494 lemma size_single [simp]: "size {#b#} = 1"
```
```   495 by (simp add: size_def)
```
```   496
```
```   497 lemma setsum_count_Int:
```
```   498   "finite A ==> setsum (count N) (A \<inter> set_of N) = setsum (count N) A"
```
```   499 apply (induct rule: finite_induct)
```
```   500  apply simp
```
```   501 apply (simp add: Int_insert_left set_of_def)
```
```   502 done
```
```   503
```
```   504 lemma size_union [simp]: "size (M + N::'a multiset) = size M + size N"
```
```   505 apply (unfold size_def)
```
```   506 apply (subgoal_tac "count (M + N) = (\<lambda>a. count M a + count N a)")
```
```   507  prefer 2
```
```   508  apply (rule ext, simp)
```
```   509 apply (simp (no_asm_simp) add: setsum_Un_nat setsum_addf setsum_count_Int)
```
```   510 apply (subst Int_commute)
```
```   511 apply (simp (no_asm_simp) add: setsum_count_Int)
```
```   512 done
```
```   513
```
```   514 lemma size_eq_0_iff_empty [iff]: "(size M = 0) = (M = {#})"
```
```   515 by (auto simp add: size_def multiset_eq_iff)
```
```   516
```
```   517 lemma nonempty_has_size: "(S \<noteq> {#}) = (0 < size S)"
```
```   518 by (metis gr0I gr_implies_not0 size_empty size_eq_0_iff_empty)
```
```   519
```
```   520 lemma size_eq_Suc_imp_elem: "size M = Suc n ==> \<exists>a. a :# M"
```
```   521 apply (unfold size_def)
```
```   522 apply (drule setsum_SucD)
```
```   523 apply auto
```
```   524 done
```
```   525
```
```   526 lemma size_eq_Suc_imp_eq_union:
```
```   527   assumes "size M = Suc n"
```
```   528   shows "\<exists>a N. M = N + {#a#}"
```
```   529 proof -
```
```   530   from assms obtain a where "a \<in># M"
```
```   531     by (erule size_eq_Suc_imp_elem [THEN exE])
```
```   532   then have "M = M - {#a#} + {#a#}" by simp
```
```   533   then show ?thesis by blast
```
```   534 qed
```
```   535
```
```   536
```
```   537 subsection {* Induction and case splits *}
```
```   538
```
```   539 lemma setsum_decr:
```
```   540   "finite F ==> (0::nat) < f a ==>
```
```   541     setsum (f (a := f a - 1)) F = (if a\<in>F then setsum f F - 1 else setsum f F)"
```
```   542 apply (induct rule: finite_induct)
```
```   543  apply auto
```
```   544 apply (drule_tac a = a in mk_disjoint_insert, auto)
```
```   545 done
```
```   546
```
```   547 lemma rep_multiset_induct_aux:
```
```   548 assumes 1: "P (\<lambda>a. (0::nat))"
```
```   549   and 2: "!!f b. f \<in> multiset ==> P f ==> P (f (b := f b + 1))"
```
```   550 shows "\<forall>f. f \<in> multiset --> setsum f {x. f x \<noteq> 0} = n --> P f"
```
```   551 apply (unfold multiset_def)
```
```   552 apply (induct_tac n, simp, clarify)
```
```   553  apply (subgoal_tac "f = (\<lambda>a.0)")
```
```   554   apply simp
```
```   555   apply (rule 1)
```
```   556  apply (rule ext, force, clarify)
```
```   557 apply (frule setsum_SucD, clarify)
```
```   558 apply (rename_tac a)
```
```   559 apply (subgoal_tac "finite {x. (f (a := f a - 1)) x > 0}")
```
```   560  prefer 2
```
```   561  apply (rule finite_subset)
```
```   562   prefer 2
```
```   563   apply assumption
```
```   564  apply simp
```
```   565  apply blast
```
```   566 apply (subgoal_tac "f = (f (a := f a - 1))(a := (f (a := f a - 1)) a + 1)")
```
```   567  prefer 2
```
```   568  apply (rule ext)
```
```   569  apply (simp (no_asm_simp))
```
```   570  apply (erule ssubst, rule 2 [unfolded multiset_def], blast)
```
```   571 apply (erule allE, erule impE, erule_tac  mp, blast)
```
```   572 apply (simp (no_asm_simp) add: setsum_decr del: fun_upd_apply One_nat_def)
```
```   573 apply (subgoal_tac "{x. x \<noteq> a --> f x \<noteq> 0} = {x. f x \<noteq> 0}")
```
```   574  prefer 2
```
```   575  apply blast
```
```   576 apply (subgoal_tac "{x. x \<noteq> a \<and> f x \<noteq> 0} = {x. f x \<noteq> 0} - {a}")
```
```   577  prefer 2
```
```   578  apply blast
```
```   579 apply (simp add: le_imp_diff_is_add setsum_diff1_nat cong: conj_cong)
```
```   580 done
```
```   581
```
```   582 theorem rep_multiset_induct:
```
```   583   "f \<in> multiset ==> P (\<lambda>a. 0) ==>
```
```   584     (!!f b. f \<in> multiset ==> P f ==> P (f (b := f b + 1))) ==> P f"
```
```   585 using rep_multiset_induct_aux by blast
```
```   586
```
```   587 theorem multiset_induct [case_names empty add, induct type: multiset]:
```
```   588 assumes empty: "P {#}"
```
```   589   and add: "!!M x. P M ==> P (M + {#x#})"
```
```   590 shows "P M"
```
```   591 proof -
```
```   592   note defns = union_def single_def Mempty_def
```
```   593   note add' = add [unfolded defns, simplified]
```
```   594   have aux: "\<And>a::'a. count (Abs_multiset (\<lambda>b. if b = a then 1 else 0)) =
```
```   595     (\<lambda>b. if b = a then 1 else 0)" by (simp add: Abs_multiset_inverse in_multiset)
```
```   596   show ?thesis
```
```   597     apply (rule count_inverse [THEN subst])
```
```   598     apply (rule count [THEN rep_multiset_induct])
```
```   599      apply (rule empty [unfolded defns])
```
```   600     apply (subgoal_tac "f(b := f b + 1) = (\<lambda>a. f a + (if a=b then 1 else 0))")
```
```   601      prefer 2
```
```   602      apply (simp add: fun_eq_iff)
```
```   603     apply (erule ssubst)
```
```   604     apply (erule Abs_multiset_inverse [THEN subst])
```
```   605     apply (drule add')
```
```   606     apply (simp add: aux)
```
```   607     done
```
```   608 qed
```
```   609
```
```   610 lemma multi_nonempty_split: "M \<noteq> {#} \<Longrightarrow> \<exists>A a. M = A + {#a#}"
```
```   611 by (induct M) auto
```
```   612
```
```   613 lemma multiset_cases [cases type, case_names empty add]:
```
```   614 assumes em:  "M = {#} \<Longrightarrow> P"
```
```   615 assumes add: "\<And>N x. M = N + {#x#} \<Longrightarrow> P"
```
```   616 shows "P"
```
```   617 proof (cases "M = {#}")
```
```   618   assume "M = {#}" then show ?thesis using em by simp
```
```   619 next
```
```   620   assume "M \<noteq> {#}"
```
```   621   then obtain M' m where "M = M' + {#m#}"
```
```   622     by (blast dest: multi_nonempty_split)
```
```   623   then show ?thesis using add by simp
```
```   624 qed
```
```   625
```
```   626 lemma multi_member_split: "x \<in># M \<Longrightarrow> \<exists>A. M = A + {#x#}"
```
```   627 apply (cases M)
```
```   628  apply simp
```
```   629 apply (rule_tac x="M - {#x#}" in exI, simp)
```
```   630 done
```
```   631
```
```   632 lemma multi_drop_mem_not_eq: "c \<in># B \<Longrightarrow> B - {#c#} \<noteq> B"
```
```   633 by (cases "B = {#}") (auto dest: multi_member_split)
```
```   634
```
```   635 lemma multiset_partition: "M = {# x:#M. P x #} + {# x:#M. \<not> P x #}"
```
```   636 apply (subst multiset_eq_iff)
```
```   637 apply auto
```
```   638 done
```
```   639
```
```   640 lemma mset_less_size: "(A::'a multiset) < B \<Longrightarrow> size A < size B"
```
```   641 proof (induct A arbitrary: B)
```
```   642   case (empty M)
```
```   643   then have "M \<noteq> {#}" by (simp add: mset_less_empty_nonempty)
```
```   644   then obtain M' x where "M = M' + {#x#}"
```
```   645     by (blast dest: multi_nonempty_split)
```
```   646   then show ?case by simp
```
```   647 next
```
```   648   case (add S x T)
```
```   649   have IH: "\<And>B. S < B \<Longrightarrow> size S < size B" by fact
```
```   650   have SxsubT: "S + {#x#} < T" by fact
```
```   651   then have "x \<in># T" and "S < T" by (auto dest: mset_less_insertD)
```
```   652   then obtain T' where T: "T = T' + {#x#}"
```
```   653     by (blast dest: multi_member_split)
```
```   654   then have "S < T'" using SxsubT
```
```   655     by (blast intro: mset_less_add_bothsides)
```
```   656   then have "size S < size T'" using IH by simp
```
```   657   then show ?case using T by simp
```
```   658 qed
```
```   659
```
```   660
```
```   661 subsubsection {* Strong induction and subset induction for multisets *}
```
```   662
```
```   663 text {* Well-foundedness of proper subset operator: *}
```
```   664
```
```   665 text {* proper multiset subset *}
```
```   666
```
```   667 definition
```
```   668   mset_less_rel :: "('a multiset * 'a multiset) set" where
```
```   669   "mset_less_rel = {(A,B). A < B}"
```
```   670
```
```   671 lemma multiset_add_sub_el_shuffle:
```
```   672   assumes "c \<in># B" and "b \<noteq> c"
```
```   673   shows "B - {#c#} + {#b#} = B + {#b#} - {#c#}"
```
```   674 proof -
```
```   675   from `c \<in># B` obtain A where B: "B = A + {#c#}"
```
```   676     by (blast dest: multi_member_split)
```
```   677   have "A + {#b#} = A + {#b#} + {#c#} - {#c#}" by simp
```
```   678   then have "A + {#b#} = A + {#c#} + {#b#} - {#c#}"
```
```   679     by (simp add: add_ac)
```
```   680   then show ?thesis using B by simp
```
```   681 qed
```
```   682
```
```   683 lemma wf_mset_less_rel: "wf mset_less_rel"
```
```   684 apply (unfold mset_less_rel_def)
```
```   685 apply (rule wf_measure [THEN wf_subset, where f1=size])
```
```   686 apply (clarsimp simp: measure_def inv_image_def mset_less_size)
```
```   687 done
```
```   688
```
```   689 text {* The induction rules: *}
```
```   690
```
```   691 lemma full_multiset_induct [case_names less]:
```
```   692 assumes ih: "\<And>B. \<forall>(A::'a multiset). A < B \<longrightarrow> P A \<Longrightarrow> P B"
```
```   693 shows "P B"
```
```   694 apply (rule wf_mset_less_rel [THEN wf_induct])
```
```   695 apply (rule ih, auto simp: mset_less_rel_def)
```
```   696 done
```
```   697
```
```   698 lemma multi_subset_induct [consumes 2, case_names empty add]:
```
```   699 assumes "F \<le> A"
```
```   700   and empty: "P {#}"
```
```   701   and insert: "\<And>a F. a \<in># A \<Longrightarrow> P F \<Longrightarrow> P (F + {#a#})"
```
```   702 shows "P F"
```
```   703 proof -
```
```   704   from `F \<le> A`
```
```   705   show ?thesis
```
```   706   proof (induct F)
```
```   707     show "P {#}" by fact
```
```   708   next
```
```   709     fix x F
```
```   710     assume P: "F \<le> A \<Longrightarrow> P F" and i: "F + {#x#} \<le> A"
```
```   711     show "P (F + {#x#})"
```
```   712     proof (rule insert)
```
```   713       from i show "x \<in># A" by (auto dest: mset_le_insertD)
```
```   714       from i have "F \<le> A" by (auto dest: mset_le_insertD)
```
```   715       with P show "P F" .
```
```   716     qed
```
```   717   qed
```
```   718 qed
```
```   719
```
```   720
```
```   721 subsection {* Alternative representations *}
```
```   722
```
```   723 subsubsection {* Lists *}
```
```   724
```
```   725 primrec multiset_of :: "'a list \<Rightarrow> 'a multiset" where
```
```   726   "multiset_of [] = {#}" |
```
```   727   "multiset_of (a # x) = multiset_of x + {# a #}"
```
```   728
```
```   729 lemma in_multiset_in_set:
```
```   730   "x \<in># multiset_of xs \<longleftrightarrow> x \<in> set xs"
```
```   731   by (induct xs) simp_all
```
```   732
```
```   733 lemma count_multiset_of:
```
```   734   "count (multiset_of xs) x = length (filter (\<lambda>y. x = y) xs)"
```
```   735   by (induct xs) simp_all
```
```   736
```
```   737 lemma multiset_of_zero_iff[simp]: "(multiset_of x = {#}) = (x = [])"
```
```   738 by (induct x) auto
```
```   739
```
```   740 lemma multiset_of_zero_iff_right[simp]: "({#} = multiset_of x) = (x = [])"
```
```   741 by (induct x) auto
```
```   742
```
```   743 lemma set_of_multiset_of[simp]: "set_of (multiset_of x) = set x"
```
```   744 by (induct x) auto
```
```   745
```
```   746 lemma mem_set_multiset_eq: "x \<in> set xs = (x :# multiset_of xs)"
```
```   747 by (induct xs) auto
```
```   748
```
```   749 lemma multiset_of_append [simp]:
```
```   750   "multiset_of (xs @ ys) = multiset_of xs + multiset_of ys"
```
```   751   by (induct xs arbitrary: ys) (auto simp: add_ac)
```
```   752
```
```   753 lemma multiset_of_filter:
```
```   754   "multiset_of (filter P xs) = {#x :# multiset_of xs. P x #}"
```
```   755   by (induct xs) simp_all
```
```   756
```
```   757 lemma multiset_of_rev [simp]:
```
```   758   "multiset_of (rev xs) = multiset_of xs"
```
```   759   by (induct xs) simp_all
```
```   760
```
```   761 lemma surj_multiset_of: "surj multiset_of"
```
```   762 apply (unfold surj_def)
```
```   763 apply (rule allI)
```
```   764 apply (rule_tac M = y in multiset_induct)
```
```   765  apply auto
```
```   766 apply (rule_tac x = "x # xa" in exI)
```
```   767 apply auto
```
```   768 done
```
```   769
```
```   770 lemma set_count_greater_0: "set x = {a. count (multiset_of x) a > 0}"
```
```   771 by (induct x) auto
```
```   772
```
```   773 lemma distinct_count_atmost_1:
```
```   774   "distinct x = (! a. count (multiset_of x) a = (if a \<in> set x then 1 else 0))"
```
```   775 apply (induct x, simp, rule iffI, simp_all)
```
```   776 apply (rule conjI)
```
```   777 apply (simp_all add: set_of_multiset_of [THEN sym] del: set_of_multiset_of)
```
```   778 apply (erule_tac x = a in allE, simp, clarify)
```
```   779 apply (erule_tac x = aa in allE, simp)
```
```   780 done
```
```   781
```
```   782 lemma multiset_of_eq_setD:
```
```   783   "multiset_of xs = multiset_of ys \<Longrightarrow> set xs = set ys"
```
```   784 by (rule) (auto simp add:multiset_eq_iff set_count_greater_0)
```
```   785
```
```   786 lemma set_eq_iff_multiset_of_eq_distinct:
```
```   787   "distinct x \<Longrightarrow> distinct y \<Longrightarrow>
```
```   788     (set x = set y) = (multiset_of x = multiset_of y)"
```
```   789 by (auto simp: multiset_eq_iff distinct_count_atmost_1)
```
```   790
```
```   791 lemma set_eq_iff_multiset_of_remdups_eq:
```
```   792    "(set x = set y) = (multiset_of (remdups x) = multiset_of (remdups y))"
```
```   793 apply (rule iffI)
```
```   794 apply (simp add: set_eq_iff_multiset_of_eq_distinct[THEN iffD1])
```
```   795 apply (drule distinct_remdups [THEN distinct_remdups
```
```   796       [THEN set_eq_iff_multiset_of_eq_distinct [THEN iffD2]]])
```
```   797 apply simp
```
```   798 done
```
```   799
```
```   800 lemma multiset_of_compl_union [simp]:
```
```   801   "multiset_of [x\<leftarrow>xs. P x] + multiset_of [x\<leftarrow>xs. \<not>P x] = multiset_of xs"
```
```   802   by (induct xs) (auto simp: add_ac)
```
```   803
```
```   804 lemma count_multiset_of_length_filter:
```
```   805   "count (multiset_of xs) x = length (filter (\<lambda>y. x = y) xs)"
```
```   806   by (induct xs) auto
```
```   807
```
```   808 lemma nth_mem_multiset_of: "i < length ls \<Longrightarrow> (ls ! i) :# multiset_of ls"
```
```   809 apply (induct ls arbitrary: i)
```
```   810  apply simp
```
```   811 apply (case_tac i)
```
```   812  apply auto
```
```   813 done
```
```   814
```
```   815 lemma multiset_of_remove1[simp]:
```
```   816   "multiset_of (remove1 a xs) = multiset_of xs - {#a#}"
```
```   817 by (induct xs) (auto simp add: multiset_eq_iff)
```
```   818
```
```   819 lemma multiset_of_eq_length:
```
```   820   assumes "multiset_of xs = multiset_of ys"
```
```   821   shows "length xs = length ys"
```
```   822 using assms proof (induct xs arbitrary: ys)
```
```   823   case Nil then show ?case by simp
```
```   824 next
```
```   825   case (Cons x xs)
```
```   826   then have "x \<in># multiset_of ys" by (simp add: union_single_eq_member)
```
```   827   then have "x \<in> set ys" by (simp add: in_multiset_in_set)
```
```   828   from Cons.prems [symmetric] have "multiset_of xs = multiset_of (remove1 x ys)"
```
```   829     by simp
```
```   830   with Cons.hyps have "length xs = length (remove1 x ys)" .
```
```   831   with `x \<in> set ys` show ?case
```
```   832     by (auto simp add: length_remove1 dest: length_pos_if_in_set)
```
```   833 qed
```
```   834
```
```   835 lemma multiset_of_eq_length_filter:
```
```   836   assumes "multiset_of xs = multiset_of ys"
```
```   837   shows "length (filter (\<lambda>x. z = x) xs) = length (filter (\<lambda>y. z = y) ys)"
```
```   838 proof (cases "z \<in># multiset_of xs")
```
```   839   case False
```
```   840   moreover have "\<not> z \<in># multiset_of ys" using assms False by simp
```
```   841   ultimately show ?thesis by (simp add: count_multiset_of_length_filter)
```
```   842 next
```
```   843   case True
```
```   844   moreover have "z \<in># multiset_of ys" using assms True by simp
```
```   845   show ?thesis using assms proof (induct xs arbitrary: ys)
```
```   846     case Nil then show ?case by simp
```
```   847   next
```
```   848     case (Cons x xs)
```
```   849     from `multiset_of (x # xs) = multiset_of ys` [symmetric]
```
```   850       have *: "multiset_of xs = multiset_of (remove1 x ys)"
```
```   851       and "x \<in> set ys"
```
```   852       by (auto simp add: mem_set_multiset_eq)
```
```   853     from * have "length (filter (\<lambda>x. z = x) xs) = length (filter (\<lambda>y. z = y) (remove1 x ys))" by (rule Cons.hyps)
```
```   854     moreover from `x \<in> set ys` have "length (filter (\<lambda>y. x = y) ys) > 0" by (simp add: filter_empty_conv)
```
```   855     ultimately show ?case using `x \<in> set ys`
```
```   856       by (simp add: filter_remove1) (auto simp add: length_remove1)
```
```   857   qed
```
```   858 qed
```
```   859
```
```   860 lemma fold_multiset_equiv:
```
```   861   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"
```
```   862     and equiv: "multiset_of xs = multiset_of ys"
```
```   863   shows "fold f xs = fold f ys"
```
```   864 using f equiv [symmetric] proof (induct xs arbitrary: ys)
```
```   865   case Nil then show ?case by simp
```
```   866 next
```
```   867   case (Cons x xs)
```
```   868   then have *: "set ys = set (x # xs)" by (blast dest: multiset_of_eq_setD)
```
```   869   have "\<And>x y. x \<in> set ys \<Longrightarrow> y \<in> set ys \<Longrightarrow> f x \<circ> f y = f y \<circ> f x"
```
```   870     by (rule Cons.prems(1)) (simp_all add: *)
```
```   871   moreover from * have "x \<in> set ys" by simp
```
```   872   ultimately have "fold f ys = fold f (remove1 x ys) \<circ> f x" by (fact fold_remove1_split)
```
```   873   moreover from Cons.prems have "fold f xs = fold f (remove1 x ys)" by (auto intro: Cons.hyps)
```
```   874   ultimately show ?case by simp
```
```   875 qed
```
```   876
```
```   877 context linorder
```
```   878 begin
```
```   879
```
```   880 lemma multiset_of_insort [simp]:
```
```   881   "multiset_of (insort_key k x xs) = {#x#} + multiset_of xs"
```
```   882   by (induct xs) (simp_all add: ac_simps)
```
```   883
```
```   884 lemma multiset_of_sort [simp]:
```
```   885   "multiset_of (sort_key k xs) = multiset_of xs"
```
```   886   by (induct xs) (simp_all add: ac_simps)
```
```   887
```
```   888 text {*
```
```   889   This lemma shows which properties suffice to show that a function
```
```   890   @{text "f"} with @{text "f xs = ys"} behaves like sort.
```
```   891 *}
```
```   892
```
```   893 lemma properties_for_sort_key:
```
```   894   assumes "multiset_of ys = multiset_of xs"
```
```   895   and "\<And>k. k \<in> set ys \<Longrightarrow> filter (\<lambda>x. f k = f x) ys = filter (\<lambda>x. f k = f x) xs"
```
```   896   and "sorted (map f ys)"
```
```   897   shows "sort_key f xs = ys"
```
```   898 using assms proof (induct xs arbitrary: ys)
```
```   899   case Nil then show ?case by simp
```
```   900 next
```
```   901   case (Cons x xs)
```
```   902   from Cons.prems(2) have
```
```   903     "\<forall>k \<in> set ys. filter (\<lambda>x. f k = f x) (remove1 x ys) = filter (\<lambda>x. f k = f x) xs"
```
```   904     by (simp add: filter_remove1)
```
```   905   with Cons.prems have "sort_key f xs = remove1 x ys"
```
```   906     by (auto intro!: Cons.hyps simp add: sorted_map_remove1)
```
```   907   moreover from Cons.prems have "x \<in> set ys"
```
```   908     by (auto simp add: mem_set_multiset_eq intro!: ccontr)
```
```   909   ultimately show ?case using Cons.prems by (simp add: insort_key_remove1)
```
```   910 qed
```
```   911
```
```   912 lemma properties_for_sort:
```
```   913   assumes multiset: "multiset_of ys = multiset_of xs"
```
```   914   and "sorted ys"
```
```   915   shows "sort xs = ys"
```
```   916 proof (rule properties_for_sort_key)
```
```   917   from multiset show "multiset_of ys = multiset_of xs" .
```
```   918   from `sorted ys` show "sorted (map (\<lambda>x. x) ys)" by simp
```
```   919   from multiset have "\<And>k. length (filter (\<lambda>y. k = y) ys) = length (filter (\<lambda>x. k = x) xs)"
```
```   920     by (rule multiset_of_eq_length_filter)
```
```   921   then have "\<And>k. replicate (length (filter (\<lambda>y. k = y) ys)) k = replicate (length (filter (\<lambda>x. k = x) xs)) k"
```
```   922     by simp
```
```   923   then show "\<And>k. k \<in> set ys \<Longrightarrow> filter (\<lambda>y. k = y) ys = filter (\<lambda>x. k = x) xs"
```
```   924     by (simp add: replicate_length_filter)
```
```   925 qed
```
```   926
```
```   927 lemma sort_key_by_quicksort:
```
```   928   "sort_key f xs = sort_key f [x\<leftarrow>xs. f x < f (xs ! (length xs div 2))]
```
```   929     @ [x\<leftarrow>xs. f x = f (xs ! (length xs div 2))]
```
```   930     @ sort_key f [x\<leftarrow>xs. f x > f (xs ! (length xs div 2))]" (is "sort_key f ?lhs = ?rhs")
```
```   931 proof (rule properties_for_sort_key)
```
```   932   show "multiset_of ?rhs = multiset_of ?lhs"
```
```   933     by (rule multiset_eqI) (auto simp add: multiset_of_filter)
```
```   934 next
```
```   935   show "sorted (map f ?rhs)"
```
```   936     by (auto simp add: sorted_append intro: sorted_map_same)
```
```   937 next
```
```   938   fix l
```
```   939   assume "l \<in> set ?rhs"
```
```   940   let ?pivot = "f (xs ! (length xs div 2))"
```
```   941   have *: "\<And>x. f l = f x \<longleftrightarrow> f x = f l" by auto
```
```   942   have "[x \<leftarrow> sort_key f xs . f x = f l] = [x \<leftarrow> xs. f x = f l]"
```
```   943     unfolding filter_sort by (rule properties_for_sort_key) (auto intro: sorted_map_same)
```
```   944   with * have **: "[x \<leftarrow> sort_key f xs . f l = f x] = [x \<leftarrow> xs. f l = f x]" by simp
```
```   945   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
```
```   946   then have "\<And>P. [x \<leftarrow> sort_key f xs . P (f x) ?pivot \<and> f l = f x] =
```
```   947     [x \<leftarrow> sort_key f xs. P (f l) ?pivot \<and> f l = f x]" by simp
```
```   948   note *** = this [of "op <"] this [of "op >"] this [of "op ="]
```
```   949   show "[x \<leftarrow> ?rhs. f l = f x] = [x \<leftarrow> ?lhs. f l = f x]"
```
```   950   proof (cases "f l" ?pivot rule: linorder_cases)
```
```   951     case less then moreover have "f l \<noteq> ?pivot" and "\<not> f l > ?pivot" by auto
```
```   952     ultimately show ?thesis
```
```   953       by (simp add: filter_sort [symmetric] ** ***)
```
```   954   next
```
```   955     case equal then show ?thesis
```
```   956       by (simp add: * less_le)
```
```   957   next
```
```   958     case greater then moreover have "f l \<noteq> ?pivot" and "\<not> f l < ?pivot" by auto
```
```   959     ultimately show ?thesis
```
```   960       by (simp add: filter_sort [symmetric] ** ***)
```
```   961   qed
```
```   962 qed
```
```   963
```
```   964 lemma sort_by_quicksort:
```
```   965   "sort xs = sort [x\<leftarrow>xs. x < xs ! (length xs div 2)]
```
```   966     @ [x\<leftarrow>xs. x = xs ! (length xs div 2)]
```
```   967     @ sort [x\<leftarrow>xs. x > xs ! (length xs div 2)]" (is "sort ?lhs = ?rhs")
```
```   968   using sort_key_by_quicksort [of "\<lambda>x. x", symmetric] by simp
```
```   969
```
```   970 text {* A stable parametrized quicksort *}
```
```   971
```
```   972 definition part :: "('b \<Rightarrow> 'a) \<Rightarrow> 'a \<Rightarrow> 'b list \<Rightarrow> 'b list \<times> 'b list \<times> 'b list" where
```
```   973   "part f pivot xs = ([x \<leftarrow> xs. f x < pivot], [x \<leftarrow> xs. f x = pivot], [x \<leftarrow> xs. pivot < f x])"
```
```   974
```
```   975 lemma part_code [code]:
```
```   976   "part f pivot [] = ([], [], [])"
```
```   977   "part f pivot (x # xs) = (let (lts, eqs, gts) = part f pivot xs; x' = f x in
```
```   978      if x' < pivot then (x # lts, eqs, gts)
```
```   979      else if x' > pivot then (lts, eqs, x # gts)
```
```   980      else (lts, x # eqs, gts))"
```
```   981   by (auto simp add: part_def Let_def split_def)
```
```   982
```
```   983 lemma sort_key_by_quicksort_code [code]:
```
```   984   "sort_key f xs = (case xs of [] \<Rightarrow> []
```
```   985     | [x] \<Rightarrow> xs
```
```   986     | [x, y] \<Rightarrow> (if f x \<le> f y then xs else [y, x])
```
```   987     | _ \<Rightarrow> (let (lts, eqs, gts) = part f (f (xs ! (length xs div 2))) xs
```
```   988        in sort_key f lts @ eqs @ sort_key f gts))"
```
```   989 proof (cases xs)
```
```   990   case Nil then show ?thesis by simp
```
```   991 next
```
```   992   case (Cons _ ys) note hyps = Cons show ?thesis proof (cases ys)
```
```   993     case Nil with hyps show ?thesis by simp
```
```   994   next
```
```   995     case (Cons _ zs) note hyps = hyps Cons show ?thesis proof (cases zs)
```
```   996       case Nil with hyps show ?thesis by auto
```
```   997     next
```
```   998       case Cons
```
```   999       from sort_key_by_quicksort [of f xs]
```
```  1000       have "sort_key f xs = (let (lts, eqs, gts) = part f (f (xs ! (length xs div 2))) xs
```
```  1001         in sort_key f lts @ eqs @ sort_key f gts)"
```
```  1002       by (simp only: split_def Let_def part_def fst_conv snd_conv)
```
```  1003       with hyps Cons show ?thesis by (simp only: list.cases)
```
```  1004     qed
```
```  1005   qed
```
```  1006 qed
```
```  1007
```
```  1008 end
```
```  1009
```
```  1010 hide_const (open) part
```
```  1011
```
```  1012 lemma multiset_of_remdups_le: "multiset_of (remdups xs) \<le> multiset_of xs"
```
```  1013   by (induct xs) (auto intro: order_trans)
```
```  1014
```
```  1015 lemma multiset_of_update:
```
```  1016   "i < length ls \<Longrightarrow> multiset_of (ls[i := v]) = multiset_of ls - {#ls ! i#} + {#v#}"
```
```  1017 proof (induct ls arbitrary: i)
```
```  1018   case Nil then show ?case by simp
```
```  1019 next
```
```  1020   case (Cons x xs)
```
```  1021   show ?case
```
```  1022   proof (cases i)
```
```  1023     case 0 then show ?thesis by simp
```
```  1024   next
```
```  1025     case (Suc i')
```
```  1026     with Cons show ?thesis
```
```  1027       apply simp
```
```  1028       apply (subst add_assoc)
```
```  1029       apply (subst add_commute [of "{#v#}" "{#x#}"])
```
```  1030       apply (subst add_assoc [symmetric])
```
```  1031       apply simp
```
```  1032       apply (rule mset_le_multiset_union_diff_commute)
```
```  1033       apply (simp add: mset_le_single nth_mem_multiset_of)
```
```  1034       done
```
```  1035   qed
```
```  1036 qed
```
```  1037
```
```  1038 lemma multiset_of_swap:
```
```  1039   "i < length ls \<Longrightarrow> j < length ls \<Longrightarrow>
```
```  1040     multiset_of (ls[j := ls ! i, i := ls ! j]) = multiset_of ls"
```
```  1041   by (cases "i = j") (simp_all add: multiset_of_update nth_mem_multiset_of)
```
```  1042
```
```  1043
```
```  1044 subsubsection {* Association lists -- including code generation *}
```
```  1045
```
```  1046 text {* Preliminaries *}
```
```  1047
```
```  1048 text {* Raw operations on lists *}
```
```  1049
```
```  1050 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"
```
```  1051 where
```
```  1052   "join_raw f xs ys = foldr (\<lambda>(k, v). map_default k v (%v'. f k (v', v))) ys xs"
```
```  1053
```
```  1054 lemma join_raw_Nil [simp]:
```
```  1055   "join_raw f xs [] = xs"
```
```  1056 by (simp add: join_raw_def)
```
```  1057
```
```  1058 lemma join_raw_Cons [simp]:
```
```  1059   "join_raw f xs ((k, v) # ys) = map_default k v (%v'. f k (v', v)) (join_raw f xs ys)"
```
```  1060 by (simp add: join_raw_def)
```
```  1061
```
```  1062 lemma map_of_join_raw:
```
```  1063   assumes "distinct (map fst ys)"
```
```  1064   shows "map_of (join_raw f xs ys) x = (case map_of xs x of None => map_of ys x | Some v => (case map_of ys x of None => Some v | Some v' => Some (f x (v, v'))))"
```
```  1065 using assms
```
```  1066 apply (induct ys)
```
```  1067 apply (auto simp add: map_of_map_default split: option.split)
```
```  1068 apply (metis map_of_eq_None_iff option.simps(2) weak_map_of_SomeI)
```
```  1069 by (metis Some_eq_map_of_iff map_of_eq_None_iff option.simps(2))
```
```  1070
```
```  1071 lemma distinct_join_raw:
```
```  1072   assumes "distinct (map fst xs)"
```
```  1073   shows "distinct (map fst (join_raw f xs ys))"
```
```  1074 using assms
```
```  1075 proof (induct ys)
```
```  1076   case (Cons y ys)
```
```  1077   thus ?case by (cases y) (simp add: distinct_map_default)
```
```  1078 qed auto
```
```  1079
```
```  1080 definition
```
```  1081   "subtract_entries_raw xs ys = foldr (%(k, v). AList.map_entry k (%v'. v' - v)) ys xs"
```
```  1082
```
```  1083 lemma map_of_subtract_entries_raw:
```
```  1084   "distinct (map fst ys) ==> map_of (subtract_entries_raw xs ys) x = (case map_of xs x of None => None | Some v => (case map_of ys x of None => Some v | Some v' => Some (v - v')))"
```
```  1085 unfolding subtract_entries_raw_def
```
```  1086 apply (induct ys)
```
```  1087 apply auto
```
```  1088 apply (simp split: option.split)
```
```  1089 apply (simp add: map_of_map_entry)
```
```  1090 apply (auto split: option.split)
```
```  1091 apply (metis map_of_eq_None_iff option.simps(3) option.simps(4))
```
```  1092 by (metis map_of_eq_None_iff option.simps(4) option.simps(5))
```
```  1093
```
```  1094 lemma distinct_subtract_entries_raw:
```
```  1095   assumes "distinct (map fst xs)"
```
```  1096   shows "distinct (map fst (subtract_entries_raw xs ys))"
```
```  1097 using assms
```
```  1098 unfolding subtract_entries_raw_def by (induct ys) (auto simp add: distinct_map_entry)
```
```  1099
```
```  1100 text {* Operations on alists *}
```
```  1101
```
```  1102 definition join
```
```  1103 where
```
```  1104   "join f xs ys = DAList.Alist (join_raw f (DAList.impl_of xs) (DAList.impl_of ys))"
```
```  1105
```
```  1106 lemma [code abstract]:
```
```  1107   "DAList.impl_of (join f xs ys) = join_raw f (DAList.impl_of xs) (DAList.impl_of ys)"
```
```  1108 unfolding join_def by (simp add: Alist_inverse distinct_join_raw)
```
```  1109
```
```  1110 definition subtract_entries
```
```  1111 where
```
```  1112   "subtract_entries xs ys = DAList.Alist (subtract_entries_raw (DAList.impl_of xs) (DAList.impl_of ys))"
```
```  1113
```
```  1114 lemma [code abstract]:
```
```  1115   "DAList.impl_of (subtract_entries xs ys) = subtract_entries_raw (DAList.impl_of xs) (DAList.impl_of ys)"
```
```  1116 unfolding subtract_entries_def by (simp add: Alist_inverse distinct_subtract_entries_raw)
```
```  1117
```
```  1118 text {* Implementing multisets by means of association lists *}
```
```  1119
```
```  1120 definition count_of :: "('a \<times> nat) list \<Rightarrow> 'a \<Rightarrow> nat" where
```
```  1121   "count_of xs x = (case map_of xs x of None \<Rightarrow> 0 | Some n \<Rightarrow> n)"
```
```  1122
```
```  1123 lemma count_of_multiset:
```
```  1124   "count_of xs \<in> multiset"
```
```  1125 proof -
```
```  1126   let ?A = "{x::'a. 0 < (case map_of xs x of None \<Rightarrow> 0\<Colon>nat | Some (n\<Colon>nat) \<Rightarrow> n)}"
```
```  1127   have "?A \<subseteq> dom (map_of xs)"
```
```  1128   proof
```
```  1129     fix x
```
```  1130     assume "x \<in> ?A"
```
```  1131     then have "0 < (case map_of xs x of None \<Rightarrow> 0\<Colon>nat | Some (n\<Colon>nat) \<Rightarrow> n)" by simp
```
```  1132     then have "map_of xs x \<noteq> None" by (cases "map_of xs x") auto
```
```  1133     then show "x \<in> dom (map_of xs)" by auto
```
```  1134   qed
```
```  1135   with finite_dom_map_of [of xs] have "finite ?A"
```
```  1136     by (auto intro: finite_subset)
```
```  1137   then show ?thesis
```
```  1138     by (simp add: count_of_def fun_eq_iff multiset_def)
```
```  1139 qed
```
```  1140
```
```  1141 lemma count_simps [simp]:
```
```  1142   "count_of [] = (\<lambda>_. 0)"
```
```  1143   "count_of ((x, n) # xs) = (\<lambda>y. if x = y then n else count_of xs y)"
```
```  1144   by (simp_all add: count_of_def fun_eq_iff)
```
```  1145
```
```  1146 lemma count_of_empty:
```
```  1147   "x \<notin> fst ` set xs \<Longrightarrow> count_of xs x = 0"
```
```  1148   by (induct xs) (simp_all add: count_of_def)
```
```  1149
```
```  1150 lemma count_of_filter:
```
```  1151   "count_of (List.filter (P \<circ> fst) xs) x = (if P x then count_of xs x else 0)"
```
```  1152   by (induct xs) auto
```
```  1153
```
```  1154 lemma count_of_map_default [simp]:
```
```  1155   "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)"
```
```  1156 unfolding count_of_def by (simp add: map_of_map_default split: option.split)
```
```  1157
```
```  1158 lemma count_of_join_raw:
```
```  1159   "distinct (map fst ys) ==> count_of xs x + count_of ys x = count_of (join_raw (%x (x, y). x + y) xs ys) x"
```
```  1160 unfolding count_of_def by (simp add: map_of_join_raw split: option.split)
```
```  1161
```
```  1162 lemma count_of_subtract_entries_raw:
```
```  1163   "distinct (map fst ys) ==> count_of xs x - count_of ys x = count_of (subtract_entries_raw xs ys) x"
```
```  1164 unfolding count_of_def by (simp add: map_of_subtract_entries_raw split: option.split)
```
```  1165
```
```  1166 text {* Code equations for multiset operations *}
```
```  1167
```
```  1168 definition Bag :: "('a, nat) alist \<Rightarrow> 'a multiset" where
```
```  1169   "Bag xs = Abs_multiset (count_of (DAList.impl_of xs))"
```
```  1170
```
```  1171 code_datatype Bag
```
```  1172
```
```  1173 lemma count_Bag [simp, code]:
```
```  1174   "count (Bag xs) = count_of (DAList.impl_of xs)"
```
```  1175   by (simp add: Bag_def count_of_multiset Abs_multiset_inverse)
```
```  1176
```
```  1177 lemma Mempty_Bag [code]:
```
```  1178   "{#} = Bag (DAList.empty)"
```
```  1179   by (simp add: multiset_eq_iff alist.Alist_inverse DAList.empty_def)
```
```  1180
```
```  1181 lemma single_Bag [code]:
```
```  1182   "{#x#} = Bag (DAList.update x 1 DAList.empty)"
```
```  1183   by (simp add: multiset_eq_iff alist.Alist_inverse impl_of_update impl_of_empty)
```
```  1184
```
```  1185 lemma union_Bag [code]:
```
```  1186   "Bag xs + Bag ys = Bag (join (\<lambda>x (n1, n2). n1 + n2) xs ys)"
```
```  1187 by (rule multiset_eqI) (simp add: count_of_join_raw alist.Alist_inverse distinct_join_raw join_def)
```
```  1188
```
```  1189 lemma minus_Bag [code]:
```
```  1190   "Bag xs - Bag ys = Bag (subtract_entries xs ys)"
```
```  1191 by (rule multiset_eqI)
```
```  1192   (simp add: count_of_subtract_entries_raw alist.Alist_inverse distinct_subtract_entries_raw subtract_entries_def)
```
```  1193
```
```  1194 lemma filter_Bag [code]:
```
```  1195   "Multiset.filter P (Bag xs) = Bag (DAList.filter (P \<circ> fst) xs)"
```
```  1196 by (rule multiset_eqI) (simp add: count_of_filter impl_of_filter)
```
```  1197
```
```  1198 lemma mset_less_eq_Bag [code]:
```
```  1199   "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)"
```
```  1200     (is "?lhs \<longleftrightarrow> ?rhs")
```
```  1201 proof
```
```  1202   assume ?lhs then show ?rhs
```
```  1203     by (auto simp add: mset_le_def count_Bag)
```
```  1204 next
```
```  1205   assume ?rhs
```
```  1206   show ?lhs
```
```  1207   proof (rule mset_less_eqI)
```
```  1208     fix x
```
```  1209     from `?rhs` have "count_of (DAList.impl_of xs) x \<le> count A x"
```
```  1210       by (cases "x \<in> fst ` set (DAList.impl_of xs)") (auto simp add: count_of_empty)
```
```  1211     then show "count (Bag xs) x \<le> count A x"
```
```  1212       by (simp add: mset_le_def count_Bag)
```
```  1213   qed
```
```  1214 qed
```
```  1215
```
```  1216 instantiation multiset :: (equal) equal
```
```  1217 begin
```
```  1218
```
```  1219 definition
```
```  1220   [code]: "HOL.equal A B \<longleftrightarrow> (A::'a multiset) \<le> B \<and> B \<le> A"
```
```  1221
```
```  1222 instance proof
```
```  1223 qed (simp add: equal_multiset_def eq_iff)
```
```  1224
```
```  1225 end
```
```  1226
```
```  1227 text {* Quickcheck generators *}
```
```  1228
```
```  1229 definition (in term_syntax)
```
```  1230   bagify :: "('a\<Colon>typerep, nat) alist \<times> (unit \<Rightarrow> Code_Evaluation.term)
```
```  1231     \<Rightarrow> 'a multiset \<times> (unit \<Rightarrow> Code_Evaluation.term)" where
```
```  1232   [code_unfold]: "bagify xs = Code_Evaluation.valtermify Bag {\<cdot>} xs"
```
```  1233
```
```  1234 notation fcomp (infixl "\<circ>>" 60)
```
```  1235 notation scomp (infixl "\<circ>\<rightarrow>" 60)
```
```  1236
```
```  1237 instantiation multiset :: (random) random
```
```  1238 begin
```
```  1239
```
```  1240 definition
```
```  1241   "Quickcheck.random i = Quickcheck.random i \<circ>\<rightarrow> (\<lambda>xs. Pair (bagify xs))"
```
```  1242
```
```  1243 instance ..
```
```  1244
```
```  1245 end
```
```  1246
```
```  1247 no_notation fcomp (infixl "\<circ>>" 60)
```
```  1248 no_notation scomp (infixl "\<circ>\<rightarrow>" 60)
```
```  1249
```
```  1250 instantiation multiset :: (exhaustive) exhaustive
```
```  1251 begin
```
```  1252
```
```  1253 definition exhaustive_multiset :: "('a multiset => (bool * term list) option) => code_numeral => (bool * term list) option"
```
```  1254 where
```
```  1255   "exhaustive_multiset f i = Quickcheck_Exhaustive.exhaustive (%xs. f (Bag xs)) i"
```
```  1256
```
```  1257 instance ..
```
```  1258
```
```  1259 end
```
```  1260
```
```  1261 instantiation multiset :: (full_exhaustive) full_exhaustive
```
```  1262 begin
```
```  1263
```
```  1264 definition full_exhaustive_multiset :: "('a multiset * (unit => term) => (bool * term list) option) => code_numeral => (bool * term list) option"
```
```  1265 where
```
```  1266   "full_exhaustive_multiset f i = Quickcheck_Exhaustive.full_exhaustive (%xs. f (bagify xs)) i"
```
```  1267
```
```  1268 instance ..
```
```  1269
```
```  1270 end
```
```  1271
```
```  1272 hide_const (open) bagify
```
```  1273
```
```  1274
```
```  1275 subsection {* The multiset order *}
```
```  1276
```
```  1277 subsubsection {* Well-foundedness *}
```
```  1278
```
```  1279 definition mult1 :: "('a \<times> 'a) set => ('a multiset \<times> 'a multiset) set" where
```
```  1280   "mult1 r = {(N, M). \<exists>a M0 K. M = M0 + {#a#} \<and> N = M0 + K \<and>
```
```  1281       (\<forall>b. b :# K --> (b, a) \<in> r)}"
```
```  1282
```
```  1283 definition mult :: "('a \<times> 'a) set => ('a multiset \<times> 'a multiset) set" where
```
```  1284   "mult r = (mult1 r)\<^sup>+"
```
```  1285
```
```  1286 lemma not_less_empty [iff]: "(M, {#}) \<notin> mult1 r"
```
```  1287 by (simp add: mult1_def)
```
```  1288
```
```  1289 lemma less_add: "(N, M0 + {#a#}) \<in> mult1 r ==>
```
```  1290     (\<exists>M. (M, M0) \<in> mult1 r \<and> N = M + {#a#}) \<or>
```
```  1291     (\<exists>K. (\<forall>b. b :# K --> (b, a) \<in> r) \<and> N = M0 + K)"
```
```  1292   (is "_ \<Longrightarrow> ?case1 (mult1 r) \<or> ?case2")
```
```  1293 proof (unfold mult1_def)
```
```  1294   let ?r = "\<lambda>K a. \<forall>b. b :# K --> (b, a) \<in> r"
```
```  1295   let ?R = "\<lambda>N M. \<exists>a M0 K. M = M0 + {#a#} \<and> N = M0 + K \<and> ?r K a"
```
```  1296   let ?case1 = "?case1 {(N, M). ?R N M}"
```
```  1297
```
```  1298   assume "(N, M0 + {#a#}) \<in> {(N, M). ?R N M}"
```
```  1299   then have "\<exists>a' M0' K.
```
```  1300       M0 + {#a#} = M0' + {#a'#} \<and> N = M0' + K \<and> ?r K a'" by simp
```
```  1301   then show "?case1 \<or> ?case2"
```
```  1302   proof (elim exE conjE)
```
```  1303     fix a' M0' K
```
```  1304     assume N: "N = M0' + K" and r: "?r K a'"
```
```  1305     assume "M0 + {#a#} = M0' + {#a'#}"
```
```  1306     then have "M0 = M0' \<and> a = a' \<or>
```
```  1307         (\<exists>K'. M0 = K' + {#a'#} \<and> M0' = K' + {#a#})"
```
```  1308       by (simp only: add_eq_conv_ex)
```
```  1309     then show ?thesis
```
```  1310     proof (elim disjE conjE exE)
```
```  1311       assume "M0 = M0'" "a = a'"
```
```  1312       with N r have "?r K a \<and> N = M0 + K" by simp
```
```  1313       then have ?case2 .. then show ?thesis ..
```
```  1314     next
```
```  1315       fix K'
```
```  1316       assume "M0' = K' + {#a#}"
```
```  1317       with N have n: "N = K' + K + {#a#}" by (simp add: add_ac)
```
```  1318
```
```  1319       assume "M0 = K' + {#a'#}"
```
```  1320       with r have "?R (K' + K) M0" by blast
```
```  1321       with n have ?case1 by simp then show ?thesis ..
```
```  1322     qed
```
```  1323   qed
```
```  1324 qed
```
```  1325
```
```  1326 lemma all_accessible: "wf r ==> \<forall>M. M \<in> acc (mult1 r)"
```
```  1327 proof
```
```  1328   let ?R = "mult1 r"
```
```  1329   let ?W = "acc ?R"
```
```  1330   {
```
```  1331     fix M M0 a
```
```  1332     assume M0: "M0 \<in> ?W"
```
```  1333       and wf_hyp: "!!b. (b, a) \<in> r ==> (\<forall>M \<in> ?W. M + {#b#} \<in> ?W)"
```
```  1334       and acc_hyp: "\<forall>M. (M, M0) \<in> ?R --> M + {#a#} \<in> ?W"
```
```  1335     have "M0 + {#a#} \<in> ?W"
```
```  1336     proof (rule accI [of "M0 + {#a#}"])
```
```  1337       fix N
```
```  1338       assume "(N, M0 + {#a#}) \<in> ?R"
```
```  1339       then have "((\<exists>M. (M, M0) \<in> ?R \<and> N = M + {#a#}) \<or>
```
```  1340           (\<exists>K. (\<forall>b. b :# K --> (b, a) \<in> r) \<and> N = M0 + K))"
```
```  1341         by (rule less_add)
```
```  1342       then show "N \<in> ?W"
```
```  1343       proof (elim exE disjE conjE)
```
```  1344         fix M assume "(M, M0) \<in> ?R" and N: "N = M + {#a#}"
```
```  1345         from acc_hyp have "(M, M0) \<in> ?R --> M + {#a#} \<in> ?W" ..
```
```  1346         from this and `(M, M0) \<in> ?R` have "M + {#a#} \<in> ?W" ..
```
```  1347         then show "N \<in> ?W" by (simp only: N)
```
```  1348       next
```
```  1349         fix K
```
```  1350         assume N: "N = M0 + K"
```
```  1351         assume "\<forall>b. b :# K --> (b, a) \<in> r"
```
```  1352         then have "M0 + K \<in> ?W"
```
```  1353         proof (induct K)
```
```  1354           case empty
```
```  1355           from M0 show "M0 + {#} \<in> ?W" by simp
```
```  1356         next
```
```  1357           case (add K x)
```
```  1358           from add.prems have "(x, a) \<in> r" by simp
```
```  1359           with wf_hyp have "\<forall>M \<in> ?W. M + {#x#} \<in> ?W" by blast
```
```  1360           moreover from add have "M0 + K \<in> ?W" by simp
```
```  1361           ultimately have "(M0 + K) + {#x#} \<in> ?W" ..
```
```  1362           then show "M0 + (K + {#x#}) \<in> ?W" by (simp only: add_assoc)
```
```  1363         qed
```
```  1364         then show "N \<in> ?W" by (simp only: N)
```
```  1365       qed
```
```  1366     qed
```
```  1367   } note tedious_reasoning = this
```
```  1368
```
```  1369   assume wf: "wf r"
```
```  1370   fix M
```
```  1371   show "M \<in> ?W"
```
```  1372   proof (induct M)
```
```  1373     show "{#} \<in> ?W"
```
```  1374     proof (rule accI)
```
```  1375       fix b assume "(b, {#}) \<in> ?R"
```
```  1376       with not_less_empty show "b \<in> ?W" by contradiction
```
```  1377     qed
```
```  1378
```
```  1379     fix M a assume "M \<in> ?W"
```
```  1380     from wf have "\<forall>M \<in> ?W. M + {#a#} \<in> ?W"
```
```  1381     proof induct
```
```  1382       fix a
```
```  1383       assume r: "!!b. (b, a) \<in> r ==> (\<forall>M \<in> ?W. M + {#b#} \<in> ?W)"
```
```  1384       show "\<forall>M \<in> ?W. M + {#a#} \<in> ?W"
```
```  1385       proof
```
```  1386         fix M assume "M \<in> ?W"
```
```  1387         then show "M + {#a#} \<in> ?W"
```
```  1388           by (rule acc_induct) (rule tedious_reasoning [OF _ r])
```
```  1389       qed
```
```  1390     qed
```
```  1391     from this and `M \<in> ?W` show "M + {#a#} \<in> ?W" ..
```
```  1392   qed
```
```  1393 qed
```
```  1394
```
```  1395 theorem wf_mult1: "wf r ==> wf (mult1 r)"
```
```  1396 by (rule acc_wfI) (rule all_accessible)
```
```  1397
```
```  1398 theorem wf_mult: "wf r ==> wf (mult r)"
```
```  1399 unfolding mult_def by (rule wf_trancl) (rule wf_mult1)
```
```  1400
```
```  1401
```
```  1402 subsubsection {* Closure-free presentation *}
```
```  1403
```
```  1404 text {* One direction. *}
```
```  1405
```
```  1406 lemma mult_implies_one_step:
```
```  1407   "trans r ==> (M, N) \<in> mult r ==>
```
```  1408     \<exists>I J K. N = I + J \<and> M = I + K \<and> J \<noteq> {#} \<and>
```
```  1409     (\<forall>k \<in> set_of K. \<exists>j \<in> set_of J. (k, j) \<in> r)"
```
```  1410 apply (unfold mult_def mult1_def set_of_def)
```
```  1411 apply (erule converse_trancl_induct, clarify)
```
```  1412  apply (rule_tac x = M0 in exI, simp, clarify)
```
```  1413 apply (case_tac "a :# K")
```
```  1414  apply (rule_tac x = I in exI)
```
```  1415  apply (simp (no_asm))
```
```  1416  apply (rule_tac x = "(K - {#a#}) + Ka" in exI)
```
```  1417  apply (simp (no_asm_simp) add: add_assoc [symmetric])
```
```  1418  apply (drule_tac f = "\<lambda>M. M - {#a#}" in arg_cong)
```
```  1419  apply (simp add: diff_union_single_conv)
```
```  1420  apply (simp (no_asm_use) add: trans_def)
```
```  1421  apply blast
```
```  1422 apply (subgoal_tac "a :# I")
```
```  1423  apply (rule_tac x = "I - {#a#}" in exI)
```
```  1424  apply (rule_tac x = "J + {#a#}" in exI)
```
```  1425  apply (rule_tac x = "K + Ka" in exI)
```
```  1426  apply (rule conjI)
```
```  1427   apply (simp add: multiset_eq_iff split: nat_diff_split)
```
```  1428  apply (rule conjI)
```
```  1429   apply (drule_tac f = "\<lambda>M. M - {#a#}" in arg_cong, simp)
```
```  1430   apply (simp add: multiset_eq_iff split: nat_diff_split)
```
```  1431  apply (simp (no_asm_use) add: trans_def)
```
```  1432  apply blast
```
```  1433 apply (subgoal_tac "a :# (M0 + {#a#})")
```
```  1434  apply simp
```
```  1435 apply (simp (no_asm))
```
```  1436 done
```
```  1437
```
```  1438 lemma one_step_implies_mult_aux:
```
```  1439   "trans r ==>
```
```  1440     \<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))
```
```  1441       --> (I + K, I + J) \<in> mult r"
```
```  1442 apply (induct_tac n, auto)
```
```  1443 apply (frule size_eq_Suc_imp_eq_union, clarify)
```
```  1444 apply (rename_tac "J'", simp)
```
```  1445 apply (erule notE, auto)
```
```  1446 apply (case_tac "J' = {#}")
```
```  1447  apply (simp add: mult_def)
```
```  1448  apply (rule r_into_trancl)
```
```  1449  apply (simp add: mult1_def set_of_def, blast)
```
```  1450 txt {* Now we know @{term "J' \<noteq> {#}"}. *}
```
```  1451 apply (cut_tac M = K and P = "\<lambda>x. (x, a) \<in> r" in multiset_partition)
```
```  1452 apply (erule_tac P = "\<forall>k \<in> set_of K. ?P k" in rev_mp)
```
```  1453 apply (erule ssubst)
```
```  1454 apply (simp add: Ball_def, auto)
```
```  1455 apply (subgoal_tac
```
```  1456   "((I + {# x :# K. (x, a) \<in> r #}) + {# x :# K. (x, a) \<notin> r #},
```
```  1457     (I + {# x :# K. (x, a) \<in> r #}) + J') \<in> mult r")
```
```  1458  prefer 2
```
```  1459  apply force
```
```  1460 apply (simp (no_asm_use) add: add_assoc [symmetric] mult_def)
```
```  1461 apply (erule trancl_trans)
```
```  1462 apply (rule r_into_trancl)
```
```  1463 apply (simp add: mult1_def set_of_def)
```
```  1464 apply (rule_tac x = a in exI)
```
```  1465 apply (rule_tac x = "I + J'" in exI)
```
```  1466 apply (simp add: add_ac)
```
```  1467 done
```
```  1468
```
```  1469 lemma one_step_implies_mult:
```
```  1470   "trans r ==> J \<noteq> {#} ==> \<forall>k \<in> set_of K. \<exists>j \<in> set_of J. (k, j) \<in> r
```
```  1471     ==> (I + K, I + J) \<in> mult r"
```
```  1472 using one_step_implies_mult_aux by blast
```
```  1473
```
```  1474
```
```  1475 subsubsection {* Partial-order properties *}
```
```  1476
```
```  1477 definition less_multiset :: "'a\<Colon>order multiset \<Rightarrow> 'a multiset \<Rightarrow> bool" (infix "<#" 50) where
```
```  1478   "M' <# M \<longleftrightarrow> (M', M) \<in> mult {(x', x). x' < x}"
```
```  1479
```
```  1480 definition le_multiset :: "'a\<Colon>order multiset \<Rightarrow> 'a multiset \<Rightarrow> bool" (infix "<=#" 50) where
```
```  1481   "M' <=# M \<longleftrightarrow> M' <# M \<or> M' = M"
```
```  1482
```
```  1483 notation (xsymbols) less_multiset (infix "\<subset>#" 50)
```
```  1484 notation (xsymbols) le_multiset (infix "\<subseteq>#" 50)
```
```  1485
```
```  1486 interpretation multiset_order: order le_multiset less_multiset
```
```  1487 proof -
```
```  1488   have irrefl: "\<And>M :: 'a multiset. \<not> M \<subset># M"
```
```  1489   proof
```
```  1490     fix M :: "'a multiset"
```
```  1491     assume "M \<subset># M"
```
```  1492     then have MM: "(M, M) \<in> mult {(x, y). x < y}" by (simp add: less_multiset_def)
```
```  1493     have "trans {(x'::'a, x). x' < x}"
```
```  1494       by (rule transI) simp
```
```  1495     moreover note MM
```
```  1496     ultimately have "\<exists>I J K. M = I + J \<and> M = I + K
```
```  1497       \<and> J \<noteq> {#} \<and> (\<forall>k\<in>set_of K. \<exists>j\<in>set_of J. (k, j) \<in> {(x, y). x < y})"
```
```  1498       by (rule mult_implies_one_step)
```
```  1499     then obtain I J K where "M = I + J" and "M = I + K"
```
```  1500       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
```
```  1501     then have aux1: "K \<noteq> {#}" and aux2: "\<forall>k\<in>set_of K. \<exists>j\<in>set_of K. k < j" by auto
```
```  1502     have "finite (set_of K)" by simp
```
```  1503     moreover note aux2
```
```  1504     ultimately have "set_of K = {}"
```
```  1505       by (induct rule: finite_induct) (auto intro: order_less_trans)
```
```  1506     with aux1 show False by simp
```
```  1507   qed
```
```  1508   have trans: "\<And>K M N :: 'a multiset. K \<subset># M \<Longrightarrow> M \<subset># N \<Longrightarrow> K \<subset># N"
```
```  1509     unfolding less_multiset_def mult_def by (blast intro: trancl_trans)
```
```  1510   show "class.order (le_multiset :: 'a multiset \<Rightarrow> _) less_multiset" proof
```
```  1511   qed (auto simp add: le_multiset_def irrefl dest: trans)
```
```  1512 qed
```
```  1513
```
```  1514 lemma mult_less_irrefl [elim!]:
```
```  1515   "M \<subset># (M::'a::order multiset) ==> R"
```
```  1516   by (simp add: multiset_order.less_irrefl)
```
```  1517
```
```  1518
```
```  1519 subsubsection {* Monotonicity of multiset union *}
```
```  1520
```
```  1521 lemma mult1_union:
```
```  1522   "(B, D) \<in> mult1 r ==> (C + B, C + D) \<in> mult1 r"
```
```  1523 apply (unfold mult1_def)
```
```  1524 apply auto
```
```  1525 apply (rule_tac x = a in exI)
```
```  1526 apply (rule_tac x = "C + M0" in exI)
```
```  1527 apply (simp add: add_assoc)
```
```  1528 done
```
```  1529
```
```  1530 lemma union_less_mono2: "B \<subset># D ==> C + B \<subset># C + (D::'a::order multiset)"
```
```  1531 apply (unfold less_multiset_def mult_def)
```
```  1532 apply (erule trancl_induct)
```
```  1533  apply (blast intro: mult1_union)
```
```  1534 apply (blast intro: mult1_union trancl_trans)
```
```  1535 done
```
```  1536
```
```  1537 lemma union_less_mono1: "B \<subset># D ==> B + C \<subset># D + (C::'a::order multiset)"
```
```  1538 apply (subst add_commute [of B C])
```
```  1539 apply (subst add_commute [of D C])
```
```  1540 apply (erule union_less_mono2)
```
```  1541 done
```
```  1542
```
```  1543 lemma union_less_mono:
```
```  1544   "A \<subset># C ==> B \<subset># D ==> A + B \<subset># C + (D::'a::order multiset)"
```
```  1545   by (blast intro!: union_less_mono1 union_less_mono2 multiset_order.less_trans)
```
```  1546
```
```  1547 interpretation multiset_order: ordered_ab_semigroup_add plus le_multiset less_multiset
```
```  1548 proof
```
```  1549 qed (auto simp add: le_multiset_def intro: union_less_mono2)
```
```  1550
```
```  1551
```
```  1552 subsection {* The fold combinator *}
```
```  1553
```
```  1554 text {*
```
```  1555   The intended behaviour is
```
```  1556   @{text "fold_mset f z {#x\<^isub>1, ..., x\<^isub>n#} = f x\<^isub>1 (\<dots> (f x\<^isub>n z)\<dots>)"}
```
```  1557   if @{text f} is associative-commutative.
```
```  1558 *}
```
```  1559
```
```  1560 text {*
```
```  1561   The graph of @{text "fold_mset"}, @{text "z"}: the start element,
```
```  1562   @{text "f"}: folding function, @{text "A"}: the multiset, @{text
```
```  1563   "y"}: the result.
```
```  1564 *}
```
```  1565 inductive
```
```  1566   fold_msetG :: "('a \<Rightarrow> 'b \<Rightarrow> 'b) \<Rightarrow> 'b \<Rightarrow> 'a multiset \<Rightarrow> 'b \<Rightarrow> bool"
```
```  1567   for f :: "'a \<Rightarrow> 'b \<Rightarrow> 'b"
```
```  1568   and z :: 'b
```
```  1569 where
```
```  1570   emptyI [intro]:  "fold_msetG f z {#} z"
```
```  1571 | insertI [intro]: "fold_msetG f z A y \<Longrightarrow> fold_msetG f z (A + {#x#}) (f x y)"
```
```  1572
```
```  1573 inductive_cases empty_fold_msetGE [elim!]: "fold_msetG f z {#} x"
```
```  1574 inductive_cases insert_fold_msetGE: "fold_msetG f z (A + {#}) y"
```
```  1575
```
```  1576 definition
```
```  1577   fold_mset :: "('a \<Rightarrow> 'b \<Rightarrow> 'b) \<Rightarrow> 'b \<Rightarrow> 'a multiset \<Rightarrow> 'b" where
```
```  1578   "fold_mset f z A = (THE x. fold_msetG f z A x)"
```
```  1579
```
```  1580 lemma Diff1_fold_msetG:
```
```  1581   "fold_msetG f z (A - {#x#}) y \<Longrightarrow> x \<in># A \<Longrightarrow> fold_msetG f z A (f x y)"
```
```  1582 apply (frule_tac x = x in fold_msetG.insertI)
```
```  1583 apply auto
```
```  1584 done
```
```  1585
```
```  1586 lemma fold_msetG_nonempty: "\<exists>x. fold_msetG f z A x"
```
```  1587 apply (induct A)
```
```  1588  apply blast
```
```  1589 apply clarsimp
```
```  1590 apply (drule_tac x = x in fold_msetG.insertI)
```
```  1591 apply auto
```
```  1592 done
```
```  1593
```
```  1594 lemma fold_mset_empty[simp]: "fold_mset f z {#} = z"
```
```  1595 unfolding fold_mset_def by blast
```
```  1596
```
```  1597 context comp_fun_commute
```
```  1598 begin
```
```  1599
```
```  1600 lemma fold_msetG_determ:
```
```  1601   "fold_msetG f z A x \<Longrightarrow> fold_msetG f z A y \<Longrightarrow> y = x"
```
```  1602 proof (induct arbitrary: x y z rule: full_multiset_induct)
```
```  1603   case (less M x\<^isub>1 x\<^isub>2 Z)
```
```  1604   have IH: "\<forall>A. A < M \<longrightarrow>
```
```  1605     (\<forall>x x' x''. fold_msetG f x'' A x \<longrightarrow> fold_msetG f x'' A x'
```
```  1606                \<longrightarrow> x' = x)" by fact
```
```  1607   have Mfoldx\<^isub>1: "fold_msetG f Z M x\<^isub>1" and Mfoldx\<^isub>2: "fold_msetG f Z M x\<^isub>2" by fact+
```
```  1608   show ?case
```
```  1609   proof (rule fold_msetG.cases [OF Mfoldx\<^isub>1])
```
```  1610     assume "M = {#}" and "x\<^isub>1 = Z"
```
```  1611     then show ?case using Mfoldx\<^isub>2 by auto
```
```  1612   next
```
```  1613     fix B b u
```
```  1614     assume "M = B + {#b#}" and "x\<^isub>1 = f b u" and Bu: "fold_msetG f Z B u"
```
```  1615     then have MBb: "M = B + {#b#}" and x\<^isub>1: "x\<^isub>1 = f b u" by auto
```
```  1616     show ?case
```
```  1617     proof (rule fold_msetG.cases [OF Mfoldx\<^isub>2])
```
```  1618       assume "M = {#}" "x\<^isub>2 = Z"
```
```  1619       then show ?case using Mfoldx\<^isub>1 by auto
```
```  1620     next
```
```  1621       fix C c v
```
```  1622       assume "M = C + {#c#}" and "x\<^isub>2 = f c v" and Cv: "fold_msetG f Z C v"
```
```  1623       then have MCc: "M = C + {#c#}" and x\<^isub>2: "x\<^isub>2 = f c v" by auto
```
```  1624       then have CsubM: "C < M" by simp
```
```  1625       from MBb have BsubM: "B < M" by simp
```
```  1626       show ?case
```
```  1627       proof cases
```
```  1628         assume "b=c"
```
```  1629         then moreover have "B = C" using MBb MCc by auto
```
```  1630         ultimately show ?thesis using Bu Cv x\<^isub>1 x\<^isub>2 CsubM IH by auto
```
```  1631       next
```
```  1632         assume diff: "b \<noteq> c"
```
```  1633         let ?D = "B - {#c#}"
```
```  1634         have cinB: "c \<in># B" and binC: "b \<in># C" using MBb MCc diff
```
```  1635           by (auto intro: insert_noteq_member dest: sym)
```
```  1636         have "B - {#c#} < B" using cinB by (rule mset_less_diff_self)
```
```  1637         then have DsubM: "?D < M" using BsubM by (blast intro: order_less_trans)
```
```  1638         from MBb MCc have "B + {#b#} = C + {#c#}" by blast
```
```  1639         then have [simp]: "B + {#b#} - {#c#} = C"
```
```  1640           using MBb MCc binC cinB by auto
```
```  1641         have B: "B = ?D + {#c#}" and C: "C = ?D + {#b#}"
```
```  1642           using MBb MCc diff binC cinB
```
```  1643           by (auto simp: multiset_add_sub_el_shuffle)
```
```  1644         then obtain d where Dfoldd: "fold_msetG f Z ?D d"
```
```  1645           using fold_msetG_nonempty by iprover
```
```  1646         then have "fold_msetG f Z B (f c d)" using cinB
```
```  1647           by (rule Diff1_fold_msetG)
```
```  1648         then have "f c d = u" using IH BsubM Bu by blast
```
```  1649         moreover
```
```  1650         have "fold_msetG f Z C (f b d)" using binC cinB diff Dfoldd
```
```  1651           by (auto simp: multiset_add_sub_el_shuffle
```
```  1652             dest: fold_msetG.insertI [where x=b])
```
```  1653         then have "f b d = v" using IH CsubM Cv by blast
```
```  1654         ultimately show ?thesis using x\<^isub>1 x\<^isub>2
```
```  1655           by (auto simp: fun_left_comm)
```
```  1656       qed
```
```  1657     qed
```
```  1658   qed
```
```  1659 qed
```
```  1660
```
```  1661 lemma fold_mset_insert_aux:
```
```  1662   "(fold_msetG f z (A + {#x#}) v) =
```
```  1663     (\<exists>y. fold_msetG f z A y \<and> v = f x y)"
```
```  1664 apply (rule iffI)
```
```  1665  prefer 2
```
```  1666  apply blast
```
```  1667 apply (rule_tac A1=A and f1=f in fold_msetG_nonempty [THEN exE])
```
```  1668 apply (blast intro: fold_msetG_determ)
```
```  1669 done
```
```  1670
```
```  1671 lemma fold_mset_equality: "fold_msetG f z A y \<Longrightarrow> fold_mset f z A = y"
```
```  1672 unfolding fold_mset_def by (blast intro: fold_msetG_determ)
```
```  1673
```
```  1674 lemma fold_mset_insert:
```
```  1675   "fold_mset f z (A + {#x#}) = f x (fold_mset f z A)"
```
```  1676 apply (simp add: fold_mset_def fold_mset_insert_aux)
```
```  1677 apply (rule the_equality)
```
```  1678  apply (auto cong add: conj_cong
```
```  1679      simp add: fold_mset_def [symmetric] fold_mset_equality fold_msetG_nonempty)
```
```  1680 done
```
```  1681
```
```  1682 lemma fold_mset_commute: "f x (fold_mset f z A) = fold_mset f (f x z) A"
```
```  1683 by (induct A) (auto simp: fold_mset_insert fun_left_comm [of x])
```
```  1684
```
```  1685 lemma fold_mset_single [simp]: "fold_mset f z {#x#} = f x z"
```
```  1686 using fold_mset_insert [of z "{#}"] by simp
```
```  1687
```
```  1688 lemma fold_mset_union [simp]:
```
```  1689   "fold_mset f z (A+B) = fold_mset f (fold_mset f z A) B"
```
```  1690 proof (induct A)
```
```  1691   case empty then show ?case by simp
```
```  1692 next
```
```  1693   case (add A x)
```
```  1694   have "A + {#x#} + B = (A+B) + {#x#}" by (simp add: add_ac)
```
```  1695   then have "fold_mset f z (A + {#x#} + B) = f x (fold_mset f z (A + B))"
```
```  1696     by (simp add: fold_mset_insert)
```
```  1697   also have "\<dots> = fold_mset f (fold_mset f z (A + {#x#})) B"
```
```  1698     by (simp add: fold_mset_commute[of x,symmetric] add fold_mset_insert)
```
```  1699   finally show ?case .
```
```  1700 qed
```
```  1701
```
```  1702 lemma fold_mset_fusion:
```
```  1703   assumes "comp_fun_commute g"
```
```  1704   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")
```
```  1705 proof -
```
```  1706   interpret comp_fun_commute g by (fact assms)
```
```  1707   show "PROP ?P" by (induct A) auto
```
```  1708 qed
```
```  1709
```
```  1710 lemma fold_mset_rec:
```
```  1711   assumes "a \<in># A"
```
```  1712   shows "fold_mset f z A = f a (fold_mset f z (A - {#a#}))"
```
```  1713 proof -
```
```  1714   from assms obtain A' where "A = A' + {#a#}"
```
```  1715     by (blast dest: multi_member_split)
```
```  1716   then show ?thesis by simp
```
```  1717 qed
```
```  1718
```
```  1719 end
```
```  1720
```
```  1721 text {*
```
```  1722   A note on code generation: When defining some function containing a
```
```  1723   subterm @{term"fold_mset F"}, code generation is not automatic. When
```
```  1724   interpreting locale @{text left_commutative} with @{text F}, the
```
```  1725   would be code thms for @{const fold_mset} become thms like
```
```  1726   @{term"fold_mset F z {#} = z"} where @{text F} is not a pattern but
```
```  1727   contains defined symbols, i.e.\ is not a code thm. Hence a separate
```
```  1728   constant with its own code thms needs to be introduced for @{text
```
```  1729   F}. See the image operator below.
```
```  1730 *}
```
```  1731
```
```  1732
```
```  1733 subsection {* Image *}
```
```  1734
```
```  1735 definition image_mset :: "('a \<Rightarrow> 'b) \<Rightarrow> 'a multiset \<Rightarrow> 'b multiset" where
```
```  1736   "image_mset f = fold_mset (op + o single o f) {#}"
```
```  1737
```
```  1738 interpretation image_fun_commute: comp_fun_commute "op + o single o f" for f
```
```  1739 proof qed (simp add: add_ac fun_eq_iff)
```
```  1740
```
```  1741 lemma image_mset_empty [simp]: "image_mset f {#} = {#}"
```
```  1742 by (simp add: image_mset_def)
```
```  1743
```
```  1744 lemma image_mset_single [simp]: "image_mset f {#x#} = {#f x#}"
```
```  1745 by (simp add: image_mset_def)
```
```  1746
```
```  1747 lemma image_mset_insert:
```
```  1748   "image_mset f (M + {#a#}) = image_mset f M + {#f a#}"
```
```  1749 by (simp add: image_mset_def add_ac)
```
```  1750
```
```  1751 lemma image_mset_union [simp]:
```
```  1752   "image_mset f (M+N) = image_mset f M + image_mset f N"
```
```  1753 apply (induct N)
```
```  1754  apply simp
```
```  1755 apply (simp add: add_assoc [symmetric] image_mset_insert)
```
```  1756 done
```
```  1757
```
```  1758 lemma size_image_mset [simp]: "size (image_mset f M) = size M"
```
```  1759 by (induct M) simp_all
```
```  1760
```
```  1761 lemma image_mset_is_empty_iff [simp]: "image_mset f M = {#} \<longleftrightarrow> M = {#}"
```
```  1762 by (cases M) auto
```
```  1763
```
```  1764 syntax
```
```  1765   "_comprehension1_mset" :: "'a \<Rightarrow> 'b \<Rightarrow> 'b multiset \<Rightarrow> 'a multiset"
```
```  1766       ("({#_/. _ :# _#})")
```
```  1767 translations
```
```  1768   "{#e. x:#M#}" == "CONST image_mset (%x. e) M"
```
```  1769
```
```  1770 syntax
```
```  1771   "_comprehension2_mset" :: "'a \<Rightarrow> 'b \<Rightarrow> 'b multiset \<Rightarrow> bool \<Rightarrow> 'a multiset"
```
```  1772       ("({#_/ | _ :# _./ _#})")
```
```  1773 translations
```
```  1774   "{#e | x:#M. P#}" => "{#e. x :# {# x:#M. P#}#}"
```
```  1775
```
```  1776 text {*
```
```  1777   This allows to write not just filters like @{term "{#x:#M. x<c#}"}
```
```  1778   but also images like @{term "{#x+x. x:#M #}"} and @{term [source]
```
```  1779   "{#x+x|x:#M. x<c#}"}, where the latter is currently displayed as
```
```  1780   @{term "{#x+x|x:#M. x<c#}"}.
```
```  1781 *}
```
```  1782
```
```  1783 enriched_type image_mset: image_mset proof -
```
```  1784   fix f g
```
```  1785   show "image_mset f \<circ> image_mset g = image_mset (f \<circ> g)"
```
```  1786   proof
```
```  1787     fix A
```
```  1788     show "(image_mset f \<circ> image_mset g) A = image_mset (f \<circ> g) A"
```
```  1789       by (induct A) simp_all
```
```  1790   qed
```
```  1791 next
```
```  1792   show "image_mset id = id"
```
```  1793   proof
```
```  1794     fix A
```
```  1795     show "image_mset id A = id A"
```
```  1796       by (induct A) simp_all
```
```  1797   qed
```
```  1798 qed
```
```  1799
```
```  1800
```
```  1801 subsection {* Termination proofs with multiset orders *}
```
```  1802
```
```  1803 lemma multi_member_skip: "x \<in># XS \<Longrightarrow> x \<in># {# y #} + XS"
```
```  1804   and multi_member_this: "x \<in># {# x #} + XS"
```
```  1805   and multi_member_last: "x \<in># {# x #}"
```
```  1806   by auto
```
```  1807
```
```  1808 definition "ms_strict = mult pair_less"
```
```  1809 definition "ms_weak = ms_strict \<union> Id"
```
```  1810
```
```  1811 lemma ms_reduction_pair: "reduction_pair (ms_strict, ms_weak)"
```
```  1812 unfolding reduction_pair_def ms_strict_def ms_weak_def pair_less_def
```
```  1813 by (auto intro: wf_mult1 wf_trancl simp: mult_def)
```
```  1814
```
```  1815 lemma smsI:
```
```  1816   "(set_of A, set_of B) \<in> max_strict \<Longrightarrow> (Z + A, Z + B) \<in> ms_strict"
```
```  1817   unfolding ms_strict_def
```
```  1818 by (rule one_step_implies_mult) (auto simp add: max_strict_def pair_less_def elim!:max_ext.cases)
```
```  1819
```
```  1820 lemma wmsI:
```
```  1821   "(set_of A, set_of B) \<in> max_strict \<or> A = {#} \<and> B = {#}
```
```  1822   \<Longrightarrow> (Z + A, Z + B) \<in> ms_weak"
```
```  1823 unfolding ms_weak_def ms_strict_def
```
```  1824 by (auto simp add: pair_less_def max_strict_def elim!:max_ext.cases intro: one_step_implies_mult)
```
```  1825
```
```  1826 inductive pw_leq
```
```  1827 where
```
```  1828   pw_leq_empty: "pw_leq {#} {#}"
```
```  1829 | pw_leq_step:  "\<lbrakk>(x,y) \<in> pair_leq; pw_leq X Y \<rbrakk> \<Longrightarrow> pw_leq ({#x#} + X) ({#y#} + Y)"
```
```  1830
```
```  1831 lemma pw_leq_lstep:
```
```  1832   "(x, y) \<in> pair_leq \<Longrightarrow> pw_leq {#x#} {#y#}"
```
```  1833 by (drule pw_leq_step) (rule pw_leq_empty, simp)
```
```  1834
```
```  1835 lemma pw_leq_split:
```
```  1836   assumes "pw_leq X Y"
```
```  1837   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 = {#}))"
```
```  1838   using assms
```
```  1839 proof (induct)
```
```  1840   case pw_leq_empty thus ?case by auto
```
```  1841 next
```
```  1842   case (pw_leq_step x y X Y)
```
```  1843   then obtain A B Z where
```
```  1844     [simp]: "X = A + Z" "Y = B + Z"
```
```  1845       and 1[simp]: "(set_of A, set_of B) \<in> max_strict \<or> (B = {#} \<and> A = {#})"
```
```  1846     by auto
```
```  1847   from pw_leq_step have "x = y \<or> (x, y) \<in> pair_less"
```
```  1848     unfolding pair_leq_def by auto
```
```  1849   thus ?case
```
```  1850   proof
```
```  1851     assume [simp]: "x = y"
```
```  1852     have
```
```  1853       "{#x#} + X = A + ({#y#}+Z)
```
```  1854       \<and> {#y#} + Y = B + ({#y#}+Z)
```
```  1855       \<and> ((set_of A, set_of B) \<in> max_strict \<or> (B = {#} \<and> A = {#}))"
```
```  1856       by (auto simp: add_ac)
```
```  1857     thus ?case by (intro exI)
```
```  1858   next
```
```  1859     assume A: "(x, y) \<in> pair_less"
```
```  1860     let ?A' = "{#x#} + A" and ?B' = "{#y#} + B"
```
```  1861     have "{#x#} + X = ?A' + Z"
```
```  1862       "{#y#} + Y = ?B' + Z"
```
```  1863       by (auto simp add: add_ac)
```
```  1864     moreover have
```
```  1865       "(set_of ?A', set_of ?B') \<in> max_strict"
```
```  1866       using 1 A unfolding max_strict_def
```
```  1867       by (auto elim!: max_ext.cases)
```
```  1868     ultimately show ?thesis by blast
```
```  1869   qed
```
```  1870 qed
```
```  1871
```
```  1872 lemma
```
```  1873   assumes pwleq: "pw_leq Z Z'"
```
```  1874   shows ms_strictI: "(set_of A, set_of B) \<in> max_strict \<Longrightarrow> (Z + A, Z' + B) \<in> ms_strict"
```
```  1875   and   ms_weakI1:  "(set_of A, set_of B) \<in> max_strict \<Longrightarrow> (Z + A, Z' + B) \<in> ms_weak"
```
```  1876   and   ms_weakI2:  "(Z + {#}, Z' + {#}) \<in> ms_weak"
```
```  1877 proof -
```
```  1878   from pw_leq_split[OF pwleq]
```
```  1879   obtain A' B' Z''
```
```  1880     where [simp]: "Z = A' + Z''" "Z' = B' + Z''"
```
```  1881     and mx_or_empty: "(set_of A', set_of B') \<in> max_strict \<or> (A' = {#} \<and> B' = {#})"
```
```  1882     by blast
```
```  1883   {
```
```  1884     assume max: "(set_of A, set_of B) \<in> max_strict"
```
```  1885     from mx_or_empty
```
```  1886     have "(Z'' + (A + A'), Z'' + (B + B')) \<in> ms_strict"
```
```  1887     proof
```
```  1888       assume max': "(set_of A', set_of B') \<in> max_strict"
```
```  1889       with max have "(set_of (A + A'), set_of (B + B')) \<in> max_strict"
```
```  1890         by (auto simp: max_strict_def intro: max_ext_additive)
```
```  1891       thus ?thesis by (rule smsI)
```
```  1892     next
```
```  1893       assume [simp]: "A' = {#} \<and> B' = {#}"
```
```  1894       show ?thesis by (rule smsI) (auto intro: max)
```
```  1895     qed
```
```  1896     thus "(Z + A, Z' + B) \<in> ms_strict" by (simp add:add_ac)
```
```  1897     thus "(Z + A, Z' + B) \<in> ms_weak" by (simp add: ms_weak_def)
```
```  1898   }
```
```  1899   from mx_or_empty
```
```  1900   have "(Z'' + A', Z'' + B') \<in> ms_weak" by (rule wmsI)
```
```  1901   thus "(Z + {#}, Z' + {#}) \<in> ms_weak" by (simp add:add_ac)
```
```  1902 qed
```
```  1903
```
```  1904 lemma empty_neutral: "{#} + x = x" "x + {#} = x"
```
```  1905 and nonempty_plus: "{# x #} + rs \<noteq> {#}"
```
```  1906 and nonempty_single: "{# x #} \<noteq> {#}"
```
```  1907 by auto
```
```  1908
```
```  1909 setup {*
```
```  1910 let
```
```  1911   fun msetT T = Type (@{type_name multiset}, [T]);
```
```  1912
```
```  1913   fun mk_mset T [] = Const (@{const_abbrev Mempty}, msetT T)
```
```  1914     | mk_mset T [x] = Const (@{const_name single}, T --> msetT T) \$ x
```
```  1915     | mk_mset T (x :: xs) =
```
```  1916           Const (@{const_name plus}, msetT T --> msetT T --> msetT T) \$
```
```  1917                 mk_mset T [x] \$ mk_mset T xs
```
```  1918
```
```  1919   fun mset_member_tac m i =
```
```  1920       (if m <= 0 then
```
```  1921            rtac @{thm multi_member_this} i ORELSE rtac @{thm multi_member_last} i
```
```  1922        else
```
```  1923            rtac @{thm multi_member_skip} i THEN mset_member_tac (m - 1) i)
```
```  1924
```
```  1925   val mset_nonempty_tac =
```
```  1926       rtac @{thm nonempty_plus} ORELSE' rtac @{thm nonempty_single}
```
```  1927
```
```  1928   val regroup_munion_conv =
```
```  1929       Function_Lib.regroup_conv @{const_abbrev Mempty} @{const_name plus}
```
```  1930         (map (fn t => t RS eq_reflection) (@{thms add_ac} @ @{thms empty_neutral}))
```
```  1931
```
```  1932   fun unfold_pwleq_tac i =
```
```  1933     (rtac @{thm pw_leq_step} i THEN (fn st => unfold_pwleq_tac (i + 1) st))
```
```  1934       ORELSE (rtac @{thm pw_leq_lstep} i)
```
```  1935       ORELSE (rtac @{thm pw_leq_empty} i)
```
```  1936
```
```  1937   val set_of_simps = [@{thm set_of_empty}, @{thm set_of_single}, @{thm set_of_union},
```
```  1938                       @{thm Un_insert_left}, @{thm Un_empty_left}]
```
```  1939 in
```
```  1940   ScnpReconstruct.multiset_setup (ScnpReconstruct.Multiset
```
```  1941   {
```
```  1942     msetT=msetT, mk_mset=mk_mset, mset_regroup_conv=regroup_munion_conv,
```
```  1943     mset_member_tac=mset_member_tac, mset_nonempty_tac=mset_nonempty_tac,
```
```  1944     mset_pwleq_tac=unfold_pwleq_tac, set_of_simps=set_of_simps,
```
```  1945     smsI'= @{thm ms_strictI}, wmsI2''= @{thm ms_weakI2}, wmsI1= @{thm ms_weakI1},
```
```  1946     reduction_pair= @{thm ms_reduction_pair}
```
```  1947   })
```
```  1948 end
```
```  1949 *}
```
```  1950
```
```  1951
```
```  1952 subsection {* Legacy theorem bindings *}
```
```  1953
```
```  1954 lemmas multi_count_eq = multiset_eq_iff [symmetric]
```
```  1955
```
```  1956 lemma union_commute: "M + N = N + (M::'a multiset)"
```
```  1957   by (fact add_commute)
```
```  1958
```
```  1959 lemma union_assoc: "(M + N) + K = M + (N + (K::'a multiset))"
```
```  1960   by (fact add_assoc)
```
```  1961
```
```  1962 lemma union_lcomm: "M + (N + K) = N + (M + (K::'a multiset))"
```
```  1963   by (fact add_left_commute)
```
```  1964
```
```  1965 lemmas union_ac = union_assoc union_commute union_lcomm
```
```  1966
```
```  1967 lemma union_right_cancel: "M + K = N + K \<longleftrightarrow> M = (N::'a multiset)"
```
```  1968   by (fact add_right_cancel)
```
```  1969
```
```  1970 lemma union_left_cancel: "K + M = K + N \<longleftrightarrow> M = (N::'a multiset)"
```
```  1971   by (fact add_left_cancel)
```
```  1972
```
```  1973 lemma multi_union_self_other_eq: "(A::'a multiset) + X = A + Y \<Longrightarrow> X = Y"
```
```  1974   by (fact add_imp_eq)
```
```  1975
```
```  1976 lemma mset_less_trans: "(M::'a multiset) < K \<Longrightarrow> K < N \<Longrightarrow> M < N"
```
```  1977   by (fact order_less_trans)
```
```  1978
```
```  1979 lemma multiset_inter_commute: "A #\<inter> B = B #\<inter> A"
```
```  1980   by (fact inf.commute)
```
```  1981
```
```  1982 lemma multiset_inter_assoc: "A #\<inter> (B #\<inter> C) = A #\<inter> B #\<inter> C"
```
```  1983   by (fact inf.assoc [symmetric])
```
```  1984
```
```  1985 lemma multiset_inter_left_commute: "A #\<inter> (B #\<inter> C) = B #\<inter> (A #\<inter> C)"
```
```  1986   by (fact inf.left_commute)
```
```  1987
```
```  1988 lemmas multiset_inter_ac =
```
```  1989   multiset_inter_commute
```
```  1990   multiset_inter_assoc
```
```  1991   multiset_inter_left_commute
```
```  1992
```
```  1993 lemma mult_less_not_refl:
```
```  1994   "\<not> M \<subset># (M::'a::order multiset)"
```
```  1995   by (fact multiset_order.less_irrefl)
```
```  1996
```
```  1997 lemma mult_less_trans:
```
```  1998   "K \<subset># M ==> M \<subset># N ==> K \<subset># (N::'a::order multiset)"
```
```  1999   by (fact multiset_order.less_trans)
```
```  2000
```
```  2001 lemma mult_less_not_sym:
```
```  2002   "M \<subset># N ==> \<not> N \<subset># (M::'a::order multiset)"
```
```  2003   by (fact multiset_order.less_not_sym)
```
```  2004
```
```  2005 lemma mult_less_asym:
```
```  2006   "M \<subset># N ==> (\<not> P ==> N \<subset># (M::'a::order multiset)) ==> P"
```
```  2007   by (fact multiset_order.less_asym)
```
```  2008
```
```  2009 ML {*
```
```  2010 fun multiset_postproc _ maybe_name all_values (T as Type (_, [elem_T]))
```
```  2011                       (Const _ \$ t') =
```
```  2012     let
```
```  2013       val (maybe_opt, ps) =
```
```  2014         Nitpick_Model.dest_plain_fun t' ||> op ~~
```
```  2015         ||> map (apsnd (snd o HOLogic.dest_number))
```
```  2016       fun elems_for t =
```
```  2017         case AList.lookup (op =) ps t of
```
```  2018           SOME n => replicate n t
```
```  2019         | NONE => [Const (maybe_name, elem_T --> elem_T) \$ t]
```
```  2020     in
```
```  2021       case maps elems_for (all_values elem_T) @
```
```  2022            (if maybe_opt then [Const (Nitpick_Model.unrep (), elem_T)]
```
```  2023             else []) of
```
```  2024         [] => Const (@{const_name zero_class.zero}, T)
```
```  2025       | ts => foldl1 (fn (t1, t2) =>
```
```  2026                          Const (@{const_name plus_class.plus}, T --> T --> T)
```
```  2027                          \$ t1 \$ t2)
```
```  2028                      (map (curry (op \$) (Const (@{const_name single},
```
```  2029                                                 elem_T --> T))) ts)
```
```  2030     end
```
```  2031   | multiset_postproc _ _ _ _ t = t
```
```  2032 *}
```
```  2033
```
```  2034 declaration {*
```
```  2035 Nitpick_Model.register_term_postprocessor @{typ "'a multiset"}
```
```  2036     multiset_postproc
```
```  2037 *}
```
```  2038
```
```  2039 end
```