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