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