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