src/HOL/Library/Multiset.thy
author wenzelm
Wed Jun 17 11:03:05 2015 +0200 (2015-06-17)
changeset 60500 903bb1495239
parent 60400 a8a31b9ebff5
child 60502 aa58872267ee
permissions -rw-r--r--
isabelle update_cartouches;
     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_of :: "'a multiset => 'a set" where
   553   "set_of M = {x. x :# M}"
   554 
   555 lemma set_of_empty [simp]: "set_of {#} = {}"
   556 by (simp add: set_of_def)
   557 
   558 lemma set_of_single [simp]: "set_of {#b#} = {b}"
   559 by (simp add: set_of_def)
   560 
   561 lemma set_of_union [simp]: "set_of (M + N) = set_of M \<union> set_of N"
   562 by (auto simp add: set_of_def)
   563 
   564 lemma set_of_eq_empty_iff [simp]: "(set_of M = {}) = (M = {#})"
   565 by (auto simp add: set_of_def multiset_eq_iff)
   566 
   567 lemma mem_set_of_iff [simp]: "(x \<in> set_of M) = (x :# M)"
   568 by (auto simp add: set_of_def)
   569 
   570 lemma set_of_filter [simp]: "set_of {# x:#M. P x #} = set_of M \<inter> {x. P x}"
   571 by (auto simp add: set_of_def)
   572 
   573 lemma finite_set_of [iff]: "finite (set_of M)"
   574   using count [of M] by (simp add: multiset_def set_of_def)
   575 
   576 lemma finite_Collect_mem [iff]: "finite {x. x :# M}"
   577   unfolding set_of_def[symmetric] by simp
   578 
   579 lemma set_of_mono: "A \<le># B \<Longrightarrow> set_of A \<subseteq> set_of B"
   580   by (metis mset_leD subsetI mem_set_of_iff)
   581 
   582 lemma ball_set_of_iff: "(\<forall>x \<in> set_of 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_of 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_of N) = setsum (wcount f N) A"
   621 apply (induct rule: finite_induct)
   622  apply simp
   623 apply (simp add: Int_insert_left set_of_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_of 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_of 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_of M) =
   796       Finite_Set.fold (\<lambda>y. f y ^^ count M y) s (set_of 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_of M - {x}"
   803     from N_def True have *: "set_of 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_of_image_mset [simp]:
   888   "set_of (image_mset f M) = image f (set_of 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_of M"
   931   by (metis mem_set_of_iff set_of_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_of_multiset_of[simp]: "set_of (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_of_multiset_of [THEN sym] del: set_of_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 count_multiset_of_length_filter:
  1050   "count (multiset_of xs) x = length (filter (\<lambda>y. x = y) xs)"
  1051   by (induct xs) auto
  1052 
  1053 lemma nth_mem_multiset_of: "i < length ls \<Longrightarrow> (ls ! i) :# multiset_of ls"
  1054 apply (induct ls arbitrary: i)
  1055  apply simp
  1056 apply (case_tac i)
  1057  apply auto
  1058 done
  1059 
  1060 lemma multiset_of_remove1[simp]:
  1061   "multiset_of (remove1 a xs) = multiset_of xs - {#a#}"
  1062 by (induct xs) (auto simp add: multiset_eq_iff)
  1063 
  1064 lemma multiset_of_eq_length:
  1065   assumes "multiset_of xs = multiset_of ys"
  1066   shows "length xs = length ys"
  1067   using assms by (metis size_multiset_of)
  1068 
  1069 lemma multiset_of_eq_length_filter:
  1070   assumes "multiset_of xs = multiset_of ys"
  1071   shows "length (filter (\<lambda>x. z = x) xs) = length (filter (\<lambda>y. z = y) ys)"
  1072   using assms by (metis count_multiset_of)
  1073 
  1074 lemma fold_multiset_equiv:
  1075   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"
  1076     and equiv: "multiset_of xs = multiset_of ys"
  1077   shows "List.fold f xs = List.fold f ys"
  1078 using f equiv [symmetric]
  1079 proof (induct xs arbitrary: ys)
  1080   case Nil then show ?case by simp
  1081 next
  1082   case (Cons x xs)
  1083   then have *: "set ys = set (x # xs)" by (blast dest: multiset_of_eq_setD)
  1084   have "\<And>x y. x \<in> set ys \<Longrightarrow> y \<in> set ys \<Longrightarrow> f x \<circ> f y = f y \<circ> f x"
  1085     by (rule Cons.prems(1)) (simp_all add: *)
  1086   moreover from * have "x \<in> set ys" by simp
  1087   ultimately have "List.fold f ys = List.fold f (remove1 x ys) \<circ> f x" by (fact fold_remove1_split)
  1088   moreover from Cons.prems have "List.fold f xs = List.fold f (remove1 x ys)" by (auto intro: Cons.hyps)
  1089   ultimately show ?case by simp
  1090 qed
  1091 
  1092 lemma multiset_of_insort [simp]:
  1093   "multiset_of (insort x xs) = multiset_of xs + {#x#}"
  1094   by (induct xs) (simp_all add: ac_simps)
  1095 
  1096 lemma multiset_of_map:
  1097   "multiset_of (map f xs) = image_mset f (multiset_of xs)"
  1098   by (induct xs) simp_all
  1099 
  1100 definition multiset_of_set :: "'a set \<Rightarrow> 'a multiset"
  1101 where
  1102   "multiset_of_set = folding.F (\<lambda>x M. {#x#} + M) {#}"
  1103 
  1104 interpretation multiset_of_set!: folding "\<lambda>x M. {#x#} + M" "{#}"
  1105 where
  1106   "folding.F (\<lambda>x M. {#x#} + M) {#} = multiset_of_set"
  1107 proof -
  1108   interpret comp_fun_commute "\<lambda>x M. {#x#} + M" by default (simp add: fun_eq_iff ac_simps)
  1109   show "folding (\<lambda>x M. {#x#} + M)" by default (fact comp_fun_commute)
  1110   from multiset_of_set_def show "folding.F (\<lambda>x M. {#x#} + M) {#} = multiset_of_set" ..
  1111 qed
  1112 
  1113 lemma count_multiset_of_set [simp]:
  1114   "finite A \<Longrightarrow> x \<in> A \<Longrightarrow> count (multiset_of_set A) x = 1" (is "PROP ?P")
  1115   "\<not> finite A \<Longrightarrow> count (multiset_of_set A) x = 0" (is "PROP ?Q")
  1116   "x \<notin> A \<Longrightarrow> count (multiset_of_set A) x = 0" (is "PROP ?R")
  1117 proof -
  1118   { fix A
  1119     assume "x \<notin> A"
  1120     have "count (multiset_of_set A) x = 0"
  1121     proof (cases "finite A")
  1122       case False then show ?thesis by simp
  1123     next
  1124       case True from True \<open>x \<notin> A\<close> show ?thesis by (induct A) auto
  1125     qed
  1126   } note * = this
  1127   then show "PROP ?P" "PROP ?Q" "PROP ?R"
  1128   by (auto elim!: Set.set_insert)
  1129 qed -- \<open>TODO: maybe define @{const multiset_of_set} also in terms of @{const Abs_multiset}\<close>
  1130 
  1131 lemma elem_multiset_of_set[simp, intro]: "finite A \<Longrightarrow> x \<in># multiset_of_set A \<longleftrightarrow> x \<in> A"
  1132   by (induct A rule: finite_induct) simp_all
  1133 
  1134 context linorder
  1135 begin
  1136 
  1137 definition sorted_list_of_multiset :: "'a multiset \<Rightarrow> 'a list"
  1138 where
  1139   "sorted_list_of_multiset M = fold_mset insort [] M"
  1140 
  1141 lemma sorted_list_of_multiset_empty [simp]:
  1142   "sorted_list_of_multiset {#} = []"
  1143   by (simp add: sorted_list_of_multiset_def)
  1144 
  1145 lemma sorted_list_of_multiset_singleton [simp]:
  1146   "sorted_list_of_multiset {#x#} = [x]"
  1147 proof -
  1148   interpret comp_fun_commute insort by (fact comp_fun_commute_insort)
  1149   show ?thesis by (simp add: sorted_list_of_multiset_def)
  1150 qed
  1151 
  1152 lemma sorted_list_of_multiset_insert [simp]:
  1153   "sorted_list_of_multiset (M + {#x#}) = List.insort x (sorted_list_of_multiset M)"
  1154 proof -
  1155   interpret comp_fun_commute insort by (fact comp_fun_commute_insort)
  1156   show ?thesis by (simp add: sorted_list_of_multiset_def)
  1157 qed
  1158 
  1159 end
  1160 
  1161 lemma multiset_of_sorted_list_of_multiset [simp]:
  1162   "multiset_of (sorted_list_of_multiset M) = M"
  1163   by (induct M) simp_all
  1164 
  1165 lemma sorted_list_of_multiset_multiset_of [simp]:
  1166   "sorted_list_of_multiset (multiset_of xs) = sort xs"
  1167   by (induct xs) simp_all
  1168 
  1169 lemma finite_set_of_multiset_of_set:
  1170   assumes "finite A"
  1171   shows "set_of (multiset_of_set A) = A"
  1172   using assms by (induct A) simp_all
  1173 
  1174 lemma infinite_set_of_multiset_of_set:
  1175   assumes "\<not> finite A"
  1176   shows "set_of (multiset_of_set A) = {}"
  1177   using assms by simp
  1178 
  1179 lemma set_sorted_list_of_multiset [simp]:
  1180   "set (sorted_list_of_multiset M) = set_of M"
  1181   by (induct M) (simp_all add: set_insort)
  1182 
  1183 lemma sorted_list_of_multiset_of_set [simp]:
  1184   "sorted_list_of_multiset (multiset_of_set A) = sorted_list_of_set A"
  1185   by (cases "finite A") (induct A rule: finite_induct, simp_all add: ac_simps)
  1186 
  1187 
  1188 subsection \<open>Big operators\<close>
  1189 
  1190 no_notation times (infixl "*" 70)
  1191 no_notation Groups.one ("1")
  1192 
  1193 locale comm_monoid_mset = comm_monoid
  1194 begin
  1195 
  1196 definition F :: "'a multiset \<Rightarrow> 'a"
  1197 where
  1198   eq_fold: "F M = fold_mset f 1 M"
  1199 
  1200 lemma empty [simp]:
  1201   "F {#} = 1"
  1202   by (simp add: eq_fold)
  1203 
  1204 lemma singleton [simp]:
  1205   "F {#x#} = x"
  1206 proof -
  1207   interpret comp_fun_commute
  1208     by default (simp add: fun_eq_iff left_commute)
  1209   show ?thesis by (simp add: eq_fold)
  1210 qed
  1211 
  1212 lemma union [simp]:
  1213   "F (M + N) = F M * F N"
  1214 proof -
  1215   interpret comp_fun_commute f
  1216     by default (simp add: fun_eq_iff left_commute)
  1217   show ?thesis by (induct N) (simp_all add: left_commute eq_fold)
  1218 qed
  1219 
  1220 end
  1221 
  1222 lemma comp_fun_commute_plus_mset[simp]: "comp_fun_commute (op + \<Colon> 'a multiset \<Rightarrow> _ \<Rightarrow> _)"
  1223   by default (simp add: add_ac comp_def)
  1224 
  1225 declare comp_fun_commute.fold_mset_insert[OF comp_fun_commute_plus_mset, simp]
  1226 
  1227 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)"
  1228   by (induct NN) auto
  1229 
  1230 notation times (infixl "*" 70)
  1231 notation Groups.one ("1")
  1232 
  1233 context comm_monoid_add
  1234 begin
  1235 
  1236 definition msetsum :: "'a multiset \<Rightarrow> 'a"
  1237 where
  1238   "msetsum = comm_monoid_mset.F plus 0"
  1239 
  1240 sublocale msetsum!: comm_monoid_mset plus 0
  1241 where
  1242   "comm_monoid_mset.F plus 0 = msetsum"
  1243 proof -
  1244   show "comm_monoid_mset plus 0" ..
  1245   from msetsum_def show "comm_monoid_mset.F plus 0 = msetsum" ..
  1246 qed
  1247 
  1248 lemma setsum_unfold_msetsum:
  1249   "setsum f A = msetsum (image_mset f (multiset_of_set A))"
  1250   by (cases "finite A") (induct A rule: finite_induct, simp_all)
  1251 
  1252 end
  1253 
  1254 lemma msetsum_diff:
  1255   fixes M N :: "('a \<Colon> ordered_cancel_comm_monoid_diff) multiset"
  1256   shows "N \<le># M \<Longrightarrow> msetsum (M - N) = msetsum M - msetsum N"
  1257   by (metis add_diff_cancel_right' msetsum.union subset_mset.diff_add)
  1258 
  1259 lemma size_eq_msetsum: "size M = msetsum (image_mset (\<lambda>_. 1) M)"
  1260 proof (induct M)
  1261   case empty then show ?case by simp
  1262 next
  1263   case (add M x) then show ?case
  1264     by (cases "x \<in> set_of M")
  1265       (simp_all del: mem_set_of_iff add: size_multiset_overloaded_eq setsum.distrib setsum.delta' insert_absorb, simp)
  1266 qed
  1267 
  1268 
  1269 abbreviation Union_mset :: "'a multiset multiset \<Rightarrow> 'a multiset" where
  1270   "Union_mset MM \<equiv> msetsum MM"
  1271 
  1272 notation (xsymbols) Union_mset ("\<Union>#_" [900] 900)
  1273 
  1274 lemma set_of_Union_mset[simp]: "set_of (\<Union># MM) = (\<Union>M \<in> set_of MM. set_of M)"
  1275   by (induct MM) auto
  1276 
  1277 lemma in_Union_mset_iff[iff]: "x \<in># \<Union># MM \<longleftrightarrow> (\<exists>M. M \<in># MM \<and> x \<in># M)"
  1278   by (induct MM) auto
  1279 
  1280 syntax
  1281   "_msetsum_image" :: "pttrn \<Rightarrow> 'b set \<Rightarrow> 'a \<Rightarrow> 'a::comm_monoid_add"
  1282       ("(3SUM _:#_. _)" [0, 51, 10] 10)
  1283 
  1284 syntax (xsymbols)
  1285   "_msetsum_image" :: "pttrn \<Rightarrow> 'b set \<Rightarrow> 'a \<Rightarrow> 'a::comm_monoid_add"
  1286       ("(3\<Sum>_\<in>#_. _)" [0, 51, 10] 10)
  1287 
  1288 syntax (HTML output)
  1289   "_msetsum_image" :: "pttrn \<Rightarrow> 'b set \<Rightarrow> 'a \<Rightarrow> 'a::comm_monoid_add"
  1290       ("(3\<Sum>_\<in>#_. _)" [0, 51, 10] 10)
  1291 
  1292 translations
  1293   "SUM i :# A. b" == "CONST msetsum (CONST image_mset (\<lambda>i. b) A)"
  1294 
  1295 context comm_monoid_mult
  1296 begin
  1297 
  1298 definition msetprod :: "'a multiset \<Rightarrow> 'a"
  1299 where
  1300   "msetprod = comm_monoid_mset.F times 1"
  1301 
  1302 sublocale msetprod!: comm_monoid_mset times 1
  1303 where
  1304   "comm_monoid_mset.F times 1 = msetprod"
  1305 proof -
  1306   show "comm_monoid_mset times 1" ..
  1307   from msetprod_def show "comm_monoid_mset.F times 1 = msetprod" ..
  1308 qed
  1309 
  1310 lemma msetprod_empty:
  1311   "msetprod {#} = 1"
  1312   by (fact msetprod.empty)
  1313 
  1314 lemma msetprod_singleton:
  1315   "msetprod {#x#} = x"
  1316   by (fact msetprod.singleton)
  1317 
  1318 lemma msetprod_Un:
  1319   "msetprod (A + B) = msetprod A * msetprod B"
  1320   by (fact msetprod.union)
  1321 
  1322 lemma setprod_unfold_msetprod:
  1323   "setprod f A = msetprod (image_mset f (multiset_of_set A))"
  1324   by (cases "finite A") (induct A rule: finite_induct, simp_all)
  1325 
  1326 lemma msetprod_multiplicity:
  1327   "msetprod M = setprod (\<lambda>x. x ^ count M x) (set_of M)"
  1328   by (simp add: fold_mset_def setprod.eq_fold msetprod.eq_fold funpow_times_power comp_def)
  1329 
  1330 end
  1331 
  1332 syntax
  1333   "_msetprod_image" :: "pttrn \<Rightarrow> 'b set \<Rightarrow> 'a \<Rightarrow> 'a::comm_monoid_mult"
  1334       ("(3PROD _:#_. _)" [0, 51, 10] 10)
  1335 
  1336 syntax (xsymbols)
  1337   "_msetprod_image" :: "pttrn \<Rightarrow> 'b set \<Rightarrow> 'a \<Rightarrow> 'a::comm_monoid_mult"
  1338       ("(3\<Prod>_\<in>#_. _)" [0, 51, 10] 10)
  1339 
  1340 syntax (HTML output)
  1341   "_msetprod_image" :: "pttrn \<Rightarrow> 'b set \<Rightarrow> 'a \<Rightarrow> 'a::comm_monoid_mult"
  1342       ("(3\<Prod>_\<in>#_. _)" [0, 51, 10] 10)
  1343 
  1344 translations
  1345   "PROD i :# A. b" == "CONST msetprod (CONST image_mset (\<lambda>i. b) A)"
  1346 
  1347 lemma (in comm_semiring_1) dvd_msetprod:
  1348   assumes "x \<in># A"
  1349   shows "x dvd msetprod A"
  1350 proof -
  1351   from assms have "A = (A - {#x#}) + {#x#}" by simp
  1352   then obtain B where "A = B + {#x#}" ..
  1353   then show ?thesis by simp
  1354 qed
  1355 
  1356 
  1357 subsection \<open>Replicate operation\<close>
  1358 
  1359 definition replicate_mset :: "nat \<Rightarrow> 'a \<Rightarrow> 'a multiset" where
  1360   "replicate_mset n x = ((op + {#x#}) ^^ n) {#}"
  1361 
  1362 lemma replicate_mset_0[simp]: "replicate_mset 0 x = {#}"
  1363   unfolding replicate_mset_def by simp
  1364 
  1365 lemma replicate_mset_Suc[simp]: "replicate_mset (Suc n) x = replicate_mset n x + {#x#}"
  1366   unfolding replicate_mset_def by (induct n) (auto intro: add.commute)
  1367 
  1368 lemma in_replicate_mset[simp]: "x \<in># replicate_mset n y \<longleftrightarrow> n > 0 \<and> x = y"
  1369   unfolding replicate_mset_def by (induct n) simp_all
  1370 
  1371 lemma count_replicate_mset[simp]: "count (replicate_mset n x) y = (if y = x then n else 0)"
  1372   unfolding replicate_mset_def by (induct n) simp_all
  1373 
  1374 lemma set_of_replicate_mset_subset[simp]: "set_of (replicate_mset n x) = (if n = 0 then {} else {x})"
  1375   by (auto split: if_splits)
  1376 
  1377 lemma size_replicate_mset[simp]: "size (replicate_mset n M) = n"
  1378   by (induct n, simp_all)
  1379 
  1380 lemma count_le_replicate_mset_le: "n \<le> count M x \<longleftrightarrow> replicate_mset n x \<le># M"
  1381   by (auto simp add: assms mset_less_eqI) (metis count_replicate_mset subseteq_mset_def)
  1382 
  1383 
  1384 lemma filter_eq_replicate_mset: "{#y \<in># D. y = x#} = replicate_mset (count D x) x"
  1385   by (induct D) simp_all
  1386 
  1387 
  1388 subsection \<open>Alternative representations\<close>
  1389 
  1390 subsubsection \<open>Lists\<close>
  1391 
  1392 context linorder
  1393 begin
  1394 
  1395 lemma multiset_of_insort [simp]:
  1396   "multiset_of (insort_key k x xs) = {#x#} + multiset_of xs"
  1397   by (induct xs) (simp_all add: ac_simps)
  1398 
  1399 lemma multiset_of_sort [simp]:
  1400   "multiset_of (sort_key k xs) = multiset_of xs"
  1401   by (induct xs) (simp_all add: ac_simps)
  1402 
  1403 text \<open>
  1404   This lemma shows which properties suffice to show that a function
  1405   @{text "f"} with @{text "f xs = ys"} behaves like sort.
  1406 \<close>
  1407 
  1408 lemma properties_for_sort_key:
  1409   assumes "multiset_of ys = multiset_of xs"
  1410   and "\<And>k. k \<in> set ys \<Longrightarrow> filter (\<lambda>x. f k = f x) ys = filter (\<lambda>x. f k = f x) xs"
  1411   and "sorted (map f ys)"
  1412   shows "sort_key f xs = ys"
  1413 using assms
  1414 proof (induct xs arbitrary: ys)
  1415   case Nil then show ?case by simp
  1416 next
  1417   case (Cons x xs)
  1418   from Cons.prems(2) have
  1419     "\<forall>k \<in> set ys. filter (\<lambda>x. f k = f x) (remove1 x ys) = filter (\<lambda>x. f k = f x) xs"
  1420     by (simp add: filter_remove1)
  1421   with Cons.prems have "sort_key f xs = remove1 x ys"
  1422     by (auto intro!: Cons.hyps simp add: sorted_map_remove1)
  1423   moreover from Cons.prems have "x \<in> set ys"
  1424     by (auto simp add: mem_set_multiset_eq intro!: ccontr)
  1425   ultimately show ?case using Cons.prems by (simp add: insort_key_remove1)
  1426 qed
  1427 
  1428 lemma properties_for_sort:
  1429   assumes multiset: "multiset_of ys = multiset_of xs"
  1430   and "sorted ys"
  1431   shows "sort xs = ys"
  1432 proof (rule properties_for_sort_key)
  1433   from multiset show "multiset_of ys = multiset_of xs" .
  1434   from \<open>sorted ys\<close> show "sorted (map (\<lambda>x. x) ys)" by simp
  1435   from multiset have "\<And>k. length (filter (\<lambda>y. k = y) ys) = length (filter (\<lambda>x. k = x) xs)"
  1436     by (rule multiset_of_eq_length_filter)
  1437   then have "\<And>k. replicate (length (filter (\<lambda>y. k = y) ys)) k = replicate (length (filter (\<lambda>x. k = x) xs)) k"
  1438     by simp
  1439   then show "\<And>k. k \<in> set ys \<Longrightarrow> filter (\<lambda>y. k = y) ys = filter (\<lambda>x. k = x) xs"
  1440     by (simp add: replicate_length_filter)
  1441 qed
  1442 
  1443 lemma sort_key_by_quicksort:
  1444   "sort_key f xs = sort_key f [x\<leftarrow>xs. f x < f (xs ! (length xs div 2))]
  1445     @ [x\<leftarrow>xs. f x = f (xs ! (length xs div 2))]
  1446     @ sort_key f [x\<leftarrow>xs. f x > f (xs ! (length xs div 2))]" (is "sort_key f ?lhs = ?rhs")
  1447 proof (rule properties_for_sort_key)
  1448   show "multiset_of ?rhs = multiset_of ?lhs"
  1449     by (rule multiset_eqI) (auto simp add: multiset_of_filter)
  1450 next
  1451   show "sorted (map f ?rhs)"
  1452     by (auto simp add: sorted_append intro: sorted_map_same)
  1453 next
  1454   fix l
  1455   assume "l \<in> set ?rhs"
  1456   let ?pivot = "f (xs ! (length xs div 2))"
  1457   have *: "\<And>x. f l = f x \<longleftrightarrow> f x = f l" by auto
  1458   have "[x \<leftarrow> sort_key f xs . f x = f l] = [x \<leftarrow> xs. f x = f l]"
  1459     unfolding filter_sort by (rule properties_for_sort_key) (auto intro: sorted_map_same)
  1460   with * have **: "[x \<leftarrow> sort_key f xs . f l = f x] = [x \<leftarrow> xs. f l = f x]" by simp
  1461   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
  1462   then have "\<And>P. [x \<leftarrow> sort_key f xs . P (f x) ?pivot \<and> f l = f x] =
  1463     [x \<leftarrow> sort_key f xs. P (f l) ?pivot \<and> f l = f x]" by simp
  1464   note *** = this [of "op <"] this [of "op >"] this [of "op ="]
  1465   show "[x \<leftarrow> ?rhs. f l = f x] = [x \<leftarrow> ?lhs. f l = f x]"
  1466   proof (cases "f l" ?pivot rule: linorder_cases)
  1467     case less
  1468     then have "f l \<noteq> ?pivot" and "\<not> f l > ?pivot" by auto
  1469     with less show ?thesis
  1470       by (simp add: filter_sort [symmetric] ** ***)
  1471   next
  1472     case equal then show ?thesis
  1473       by (simp add: * less_le)
  1474   next
  1475     case greater
  1476     then have "f l \<noteq> ?pivot" and "\<not> f l < ?pivot" by auto
  1477     with greater show ?thesis
  1478       by (simp add: filter_sort [symmetric] ** ***)
  1479   qed
  1480 qed
  1481 
  1482 lemma sort_by_quicksort:
  1483   "sort xs = sort [x\<leftarrow>xs. x < xs ! (length xs div 2)]
  1484     @ [x\<leftarrow>xs. x = xs ! (length xs div 2)]
  1485     @ sort [x\<leftarrow>xs. x > xs ! (length xs div 2)]" (is "sort ?lhs = ?rhs")
  1486   using sort_key_by_quicksort [of "\<lambda>x. x", symmetric] by simp
  1487 
  1488 text \<open>A stable parametrized quicksort\<close>
  1489 
  1490 definition part :: "('b \<Rightarrow> 'a) \<Rightarrow> 'a \<Rightarrow> 'b list \<Rightarrow> 'b list \<times> 'b list \<times> 'b list" where
  1491   "part f pivot xs = ([x \<leftarrow> xs. f x < pivot], [x \<leftarrow> xs. f x = pivot], [x \<leftarrow> xs. pivot < f x])"
  1492 
  1493 lemma part_code [code]:
  1494   "part f pivot [] = ([], [], [])"
  1495   "part f pivot (x # xs) = (let (lts, eqs, gts) = part f pivot xs; x' = f x in
  1496      if x' < pivot then (x # lts, eqs, gts)
  1497      else if x' > pivot then (lts, eqs, x # gts)
  1498      else (lts, x # eqs, gts))"
  1499   by (auto simp add: part_def Let_def split_def)
  1500 
  1501 lemma sort_key_by_quicksort_code [code]:
  1502   "sort_key f xs = (case xs of [] \<Rightarrow> []
  1503     | [x] \<Rightarrow> xs
  1504     | [x, y] \<Rightarrow> (if f x \<le> f y then xs else [y, x])
  1505     | _ \<Rightarrow> (let (lts, eqs, gts) = part f (f (xs ! (length xs div 2))) xs
  1506        in sort_key f lts @ eqs @ sort_key f gts))"
  1507 proof (cases xs)
  1508   case Nil then show ?thesis by simp
  1509 next
  1510   case (Cons _ ys) note hyps = Cons show ?thesis
  1511   proof (cases ys)
  1512     case Nil with hyps show ?thesis by simp
  1513   next
  1514     case (Cons _ zs) note hyps = hyps Cons show ?thesis
  1515     proof (cases zs)
  1516       case Nil with hyps show ?thesis by auto
  1517     next
  1518       case Cons
  1519       from sort_key_by_quicksort [of f xs]
  1520       have "sort_key f xs = (let (lts, eqs, gts) = part f (f (xs ! (length xs div 2))) xs
  1521         in sort_key f lts @ eqs @ sort_key f gts)"
  1522       by (simp only: split_def Let_def part_def fst_conv snd_conv)
  1523       with hyps Cons show ?thesis by (simp only: list.cases)
  1524     qed
  1525   qed
  1526 qed
  1527 
  1528 end
  1529 
  1530 hide_const (open) part
  1531 
  1532 lemma multiset_of_remdups_le: "multiset_of (remdups xs) \<le># multiset_of xs"
  1533   by (induct xs) (auto intro: subset_mset.order_trans)
  1534 
  1535 lemma multiset_of_update:
  1536   "i < length ls \<Longrightarrow> multiset_of (ls[i := v]) = multiset_of ls - {#ls ! i#} + {#v#}"
  1537 proof (induct ls arbitrary: i)
  1538   case Nil then show ?case by simp
  1539 next
  1540   case (Cons x xs)
  1541   show ?case
  1542   proof (cases i)
  1543     case 0 then show ?thesis by simp
  1544   next
  1545     case (Suc i')
  1546     with Cons show ?thesis
  1547       apply simp
  1548       apply (subst add.assoc)
  1549       apply (subst add.commute [of "{#v#}" "{#x#}"])
  1550       apply (subst add.assoc [symmetric])
  1551       apply simp
  1552       apply (rule mset_le_multiset_union_diff_commute)
  1553       apply (simp add: mset_le_single nth_mem_multiset_of)
  1554       done
  1555   qed
  1556 qed
  1557 
  1558 lemma multiset_of_swap:
  1559   "i < length ls \<Longrightarrow> j < length ls \<Longrightarrow>
  1560     multiset_of (ls[j := ls ! i, i := ls ! j]) = multiset_of ls"
  1561   by (cases "i = j") (simp_all add: multiset_of_update nth_mem_multiset_of)
  1562 
  1563 
  1564 subsection \<open>The multiset order\<close>
  1565 
  1566 subsubsection \<open>Well-foundedness\<close>
  1567 
  1568 definition mult1 :: "('a \<times> 'a) set => ('a multiset \<times> 'a multiset) set" where
  1569   "mult1 r = {(N, M). \<exists>a M0 K. M = M0 + {#a#} \<and> N = M0 + K \<and>
  1570       (\<forall>b. b :# K --> (b, a) \<in> r)}"
  1571 
  1572 definition mult :: "('a \<times> 'a) set => ('a multiset \<times> 'a multiset) set" where
  1573   "mult r = (mult1 r)\<^sup>+"
  1574 
  1575 lemma not_less_empty [iff]: "(M, {#}) \<notin> mult1 r"
  1576 by (simp add: mult1_def)
  1577 
  1578 lemma less_add: "(N, M0 + {#a#}) \<in> mult1 r ==>
  1579     (\<exists>M. (M, M0) \<in> mult1 r \<and> N = M + {#a#}) \<or>
  1580     (\<exists>K. (\<forall>b. b :# K --> (b, a) \<in> r) \<and> N = M0 + K)"
  1581   (is "_ \<Longrightarrow> ?case1 (mult1 r) \<or> ?case2")
  1582 proof (unfold mult1_def)
  1583   let ?r = "\<lambda>K a. \<forall>b. b :# K --> (b, a) \<in> r"
  1584   let ?R = "\<lambda>N M. \<exists>a M0 K. M = M0 + {#a#} \<and> N = M0 + K \<and> ?r K a"
  1585   let ?case1 = "?case1 {(N, M). ?R N M}"
  1586 
  1587   assume "(N, M0 + {#a#}) \<in> {(N, M). ?R N M}"
  1588   then have "\<exists>a' M0' K.
  1589       M0 + {#a#} = M0' + {#a'#} \<and> N = M0' + K \<and> ?r K a'" by simp
  1590   then show "?case1 \<or> ?case2"
  1591   proof (elim exE conjE)
  1592     fix a' M0' K
  1593     assume N: "N = M0' + K" and r: "?r K a'"
  1594     assume "M0 + {#a#} = M0' + {#a'#}"
  1595     then have "M0 = M0' \<and> a = a' \<or>
  1596         (\<exists>K'. M0 = K' + {#a'#} \<and> M0' = K' + {#a#})"
  1597       by (simp only: add_eq_conv_ex)
  1598     then show ?thesis
  1599     proof (elim disjE conjE exE)
  1600       assume "M0 = M0'" "a = a'"
  1601       with N r have "?r K a \<and> N = M0 + K" by simp
  1602       then have ?case2 .. then show ?thesis ..
  1603     next
  1604       fix K'
  1605       assume "M0' = K' + {#a#}"
  1606       with N have n: "N = K' + K + {#a#}" by (simp add: ac_simps)
  1607 
  1608       assume "M0 = K' + {#a'#}"
  1609       with r have "?R (K' + K) M0" by blast
  1610       with n have ?case1 by simp then show ?thesis ..
  1611     qed
  1612   qed
  1613 qed
  1614 
  1615 lemma all_accessible: "wf r ==> \<forall>M. M \<in> Wellfounded.acc (mult1 r)"
  1616 proof
  1617   let ?R = "mult1 r"
  1618   let ?W = "Wellfounded.acc ?R"
  1619   {
  1620     fix M M0 a
  1621     assume M0: "M0 \<in> ?W"
  1622       and wf_hyp: "!!b. (b, a) \<in> r ==> (\<forall>M \<in> ?W. M + {#b#} \<in> ?W)"
  1623       and acc_hyp: "\<forall>M. (M, M0) \<in> ?R --> M + {#a#} \<in> ?W"
  1624     have "M0 + {#a#} \<in> ?W"
  1625     proof (rule accI [of "M0 + {#a#}"])
  1626       fix N
  1627       assume "(N, M0 + {#a#}) \<in> ?R"
  1628       then have "((\<exists>M. (M, M0) \<in> ?R \<and> N = M + {#a#}) \<or>
  1629           (\<exists>K. (\<forall>b. b :# K --> (b, a) \<in> r) \<and> N = M0 + K))"
  1630         by (rule less_add)
  1631       then show "N \<in> ?W"
  1632       proof (elim exE disjE conjE)
  1633         fix M assume "(M, M0) \<in> ?R" and N: "N = M + {#a#}"
  1634         from acc_hyp have "(M, M0) \<in> ?R --> M + {#a#} \<in> ?W" ..
  1635         from this and \<open>(M, M0) \<in> ?R\<close> have "M + {#a#} \<in> ?W" ..
  1636         then show "N \<in> ?W" by (simp only: N)
  1637       next
  1638         fix K
  1639         assume N: "N = M0 + K"
  1640         assume "\<forall>b. b :# K --> (b, a) \<in> r"
  1641         then have "M0 + K \<in> ?W"
  1642         proof (induct K)
  1643           case empty
  1644           from M0 show "M0 + {#} \<in> ?W" by simp
  1645         next
  1646           case (add K x)
  1647           from add.prems have "(x, a) \<in> r" by simp
  1648           with wf_hyp have "\<forall>M \<in> ?W. M + {#x#} \<in> ?W" by blast
  1649           moreover from add have "M0 + K \<in> ?W" by simp
  1650           ultimately have "(M0 + K) + {#x#} \<in> ?W" ..
  1651           then show "M0 + (K + {#x#}) \<in> ?W" by (simp only: add.assoc)
  1652         qed
  1653         then show "N \<in> ?W" by (simp only: N)
  1654       qed
  1655     qed
  1656   } note tedious_reasoning = this
  1657 
  1658   assume wf: "wf r"
  1659   fix M
  1660   show "M \<in> ?W"
  1661   proof (induct M)
  1662     show "{#} \<in> ?W"
  1663     proof (rule accI)
  1664       fix b assume "(b, {#}) \<in> ?R"
  1665       with not_less_empty show "b \<in> ?W" by contradiction
  1666     qed
  1667 
  1668     fix M a assume "M \<in> ?W"
  1669     from wf have "\<forall>M \<in> ?W. M + {#a#} \<in> ?W"
  1670     proof induct
  1671       fix a
  1672       assume r: "!!b. (b, a) \<in> r ==> (\<forall>M \<in> ?W. M + {#b#} \<in> ?W)"
  1673       show "\<forall>M \<in> ?W. M + {#a#} \<in> ?W"
  1674       proof
  1675         fix M assume "M \<in> ?W"
  1676         then show "M + {#a#} \<in> ?W"
  1677           by (rule acc_induct) (rule tedious_reasoning [OF _ r])
  1678       qed
  1679     qed
  1680     from this and \<open>M \<in> ?W\<close> show "M + {#a#} \<in> ?W" ..
  1681   qed
  1682 qed
  1683 
  1684 theorem wf_mult1: "wf r ==> wf (mult1 r)"
  1685 by (rule acc_wfI) (rule all_accessible)
  1686 
  1687 theorem wf_mult: "wf r ==> wf (mult r)"
  1688 unfolding mult_def by (rule wf_trancl) (rule wf_mult1)
  1689 
  1690 
  1691 subsubsection \<open>Closure-free presentation\<close>
  1692 
  1693 text \<open>One direction.\<close>
  1694 
  1695 lemma mult_implies_one_step:
  1696   "trans r ==> (M, N) \<in> mult r ==>
  1697     \<exists>I J K. N = I + J \<and> M = I + K \<and> J \<noteq> {#} \<and>
  1698     (\<forall>k \<in> set_of K. \<exists>j \<in> set_of J. (k, j) \<in> r)"
  1699 apply (unfold mult_def mult1_def set_of_def)
  1700 apply (erule converse_trancl_induct, clarify)
  1701  apply (rule_tac x = M0 in exI, simp, clarify)
  1702 apply (case_tac "a :# K")
  1703  apply (rule_tac x = I in exI)
  1704  apply (simp (no_asm))
  1705  apply (rule_tac x = "(K - {#a#}) + Ka" in exI)
  1706  apply (simp (no_asm_simp) add: add.assoc [symmetric])
  1707  apply (drule_tac f = "\<lambda>M. M - {#a#}" and x="S + T" for S T in arg_cong)
  1708  apply (simp add: diff_union_single_conv)
  1709  apply (simp (no_asm_use) add: trans_def)
  1710  apply blast
  1711 apply (subgoal_tac "a :# I")
  1712  apply (rule_tac x = "I - {#a#}" in exI)
  1713  apply (rule_tac x = "J + {#a#}" in exI)
  1714  apply (rule_tac x = "K + Ka" in exI)
  1715  apply (rule conjI)
  1716   apply (simp add: multiset_eq_iff split: nat_diff_split)
  1717  apply (rule conjI)
  1718   apply (drule_tac f = "\<lambda>M. M - {#a#}" and x="S + T" for S T in arg_cong, simp)
  1719   apply (simp add: multiset_eq_iff split: nat_diff_split)
  1720  apply (simp (no_asm_use) add: trans_def)
  1721  apply blast
  1722 apply (subgoal_tac "a :# (M0 + {#a#})")
  1723  apply simp
  1724 apply (simp (no_asm))
  1725 done
  1726 
  1727 lemma one_step_implies_mult_aux:
  1728   "trans r ==>
  1729     \<forall>I J K. (size J = n \<and> J \<noteq> {#} \<and> (\<forall>k \<in> set_of K. \<exists>j \<in> set_of J. (k, j) \<in> r))
  1730       --> (I + K, I + J) \<in> mult r"
  1731 apply (induct_tac n, auto)
  1732 apply (frule size_eq_Suc_imp_eq_union, clarify)
  1733 apply (rename_tac "J'", simp)
  1734 apply (erule notE, auto)
  1735 apply (case_tac "J' = {#}")
  1736  apply (simp add: mult_def)
  1737  apply (rule r_into_trancl)
  1738  apply (simp add: mult1_def set_of_def, blast)
  1739 txt \<open>Now we know @{term "J' \<noteq> {#}"}.\<close>
  1740 apply (cut_tac M = K and P = "\<lambda>x. (x, a) \<in> r" in multiset_partition)
  1741 apply (erule_tac P = "\<forall>k \<in> set_of K. P k" for P in rev_mp)
  1742 apply (erule ssubst)
  1743 apply (simp add: Ball_def, auto)
  1744 apply (subgoal_tac
  1745   "((I + {# x :# K. (x, a) \<in> r #}) + {# x :# K. (x, a) \<notin> r #},
  1746     (I + {# x :# K. (x, a) \<in> r #}) + J') \<in> mult r")
  1747  prefer 2
  1748  apply force
  1749 apply (simp (no_asm_use) add: add.assoc [symmetric] mult_def)
  1750 apply (erule trancl_trans)
  1751 apply (rule r_into_trancl)
  1752 apply (simp add: mult1_def set_of_def)
  1753 apply (rule_tac x = a in exI)
  1754 apply (rule_tac x = "I + J'" in exI)
  1755 apply (simp add: ac_simps)
  1756 done
  1757 
  1758 lemma one_step_implies_mult:
  1759   "trans r ==> J \<noteq> {#} ==> \<forall>k \<in> set_of K. \<exists>j \<in> set_of J. (k, j) \<in> r
  1760     ==> (I + K, I + J) \<in> mult r"
  1761 using one_step_implies_mult_aux by blast
  1762 
  1763 
  1764 subsubsection \<open>Partial-order properties\<close>
  1765 
  1766 definition less_multiset :: "'a\<Colon>order multiset \<Rightarrow> 'a multiset \<Rightarrow> bool" (infix "#<#" 50) where
  1767   "M' #<# M \<longleftrightarrow> (M', M) \<in> mult {(x', x). x' < x}"
  1768 
  1769 definition le_multiset :: "'a\<Colon>order multiset \<Rightarrow> 'a multiset \<Rightarrow> bool" (infix "#<=#" 50) where
  1770   "M' #<=# M \<longleftrightarrow> M' #<# M \<or> M' = M"
  1771 
  1772 notation (xsymbols) less_multiset (infix "#\<subset>#" 50)
  1773 notation (xsymbols) le_multiset (infix "#\<subseteq>#" 50)
  1774 
  1775 interpretation multiset_order: order le_multiset less_multiset
  1776 proof -
  1777   have irrefl: "\<And>M :: 'a multiset. \<not> M #\<subset># M"
  1778   proof
  1779     fix M :: "'a multiset"
  1780     assume "M #\<subset># M"
  1781     then have MM: "(M, M) \<in> mult {(x, y). x < y}" by (simp add: less_multiset_def)
  1782     have "trans {(x'::'a, x). x' < x}"
  1783       by (rule transI) simp
  1784     moreover note MM
  1785     ultimately have "\<exists>I J K. M = I + J \<and> M = I + K
  1786       \<and> J \<noteq> {#} \<and> (\<forall>k\<in>set_of K. \<exists>j\<in>set_of J. (k, j) \<in> {(x, y). x < y})"
  1787       by (rule mult_implies_one_step)
  1788     then obtain I J K where "M = I + J" and "M = I + K"
  1789       and "J \<noteq> {#}" and "(\<forall>k\<in>set_of K. \<exists>j\<in>set_of J. (k, j) \<in> {(x, y). x < y})" by blast
  1790     then have aux1: "K \<noteq> {#}" and aux2: "\<forall>k\<in>set_of K. \<exists>j\<in>set_of K. k < j" by auto
  1791     have "finite (set_of K)" by simp
  1792     moreover note aux2
  1793     ultimately have "set_of K = {}"
  1794       by (induct rule: finite_induct) (auto intro: order_less_trans)
  1795     with aux1 show False by simp
  1796   qed
  1797   have trans: "\<And>K M N :: 'a multiset. K #\<subset># M \<Longrightarrow> M #\<subset># N \<Longrightarrow> K #\<subset># N"
  1798     unfolding less_multiset_def mult_def by (blast intro: trancl_trans)
  1799   show "class.order (le_multiset :: 'a multiset \<Rightarrow> _) less_multiset"
  1800     by default (auto simp add: le_multiset_def irrefl dest: trans)
  1801 qed
  1802 
  1803 lemma mult_less_irrefl [elim!]: "M #\<subset># (M::'a::order multiset) ==> R"
  1804   by simp
  1805 
  1806 
  1807 subsubsection \<open>Monotonicity of multiset union\<close>
  1808 
  1809 lemma mult1_union: "(B, D) \<in> mult1 r ==> (C + B, C + D) \<in> mult1 r"
  1810 apply (unfold mult1_def)
  1811 apply auto
  1812 apply (rule_tac x = a in exI)
  1813 apply (rule_tac x = "C + M0" in exI)
  1814 apply (simp add: add.assoc)
  1815 done
  1816 
  1817 lemma union_less_mono2: "B #\<subset># D ==> C + B #\<subset># C + (D::'a::order multiset)"
  1818 apply (unfold less_multiset_def mult_def)
  1819 apply (erule trancl_induct)
  1820  apply (blast intro: mult1_union)
  1821 apply (blast intro: mult1_union trancl_trans)
  1822 done
  1823 
  1824 lemma union_less_mono1: "B #\<subset># D ==> B + C #\<subset># D + (C::'a::order multiset)"
  1825 apply (subst add.commute [of B C])
  1826 apply (subst add.commute [of D C])
  1827 apply (erule union_less_mono2)
  1828 done
  1829 
  1830 lemma union_less_mono:
  1831   "A #\<subset># C ==> B #\<subset># D ==> A + B #\<subset># C + (D::'a::order multiset)"
  1832   by (blast intro!: union_less_mono1 union_less_mono2 multiset_order.less_trans)
  1833 
  1834 interpretation multiset_order: ordered_ab_semigroup_add plus le_multiset less_multiset
  1835 proof
  1836 qed (auto simp add: le_multiset_def intro: union_less_mono2)
  1837 
  1838 
  1839 subsubsection \<open>Termination proofs with multiset orders\<close>
  1840 
  1841 lemma multi_member_skip: "x \<in># XS \<Longrightarrow> x \<in># {# y #} + XS"
  1842   and multi_member_this: "x \<in># {# x #} + XS"
  1843   and multi_member_last: "x \<in># {# x #}"
  1844   by auto
  1845 
  1846 definition "ms_strict = mult pair_less"
  1847 definition "ms_weak = ms_strict \<union> Id"
  1848 
  1849 lemma ms_reduction_pair: "reduction_pair (ms_strict, ms_weak)"
  1850 unfolding reduction_pair_def ms_strict_def ms_weak_def pair_less_def
  1851 by (auto intro: wf_mult1 wf_trancl simp: mult_def)
  1852 
  1853 lemma smsI:
  1854   "(set_of A, set_of B) \<in> max_strict \<Longrightarrow> (Z + A, Z + B) \<in> ms_strict"
  1855   unfolding ms_strict_def
  1856 by (rule one_step_implies_mult) (auto simp add: max_strict_def pair_less_def elim!:max_ext.cases)
  1857 
  1858 lemma wmsI:
  1859   "(set_of A, set_of B) \<in> max_strict \<or> A = {#} \<and> B = {#}
  1860   \<Longrightarrow> (Z + A, Z + B) \<in> ms_weak"
  1861 unfolding ms_weak_def ms_strict_def
  1862 by (auto simp add: pair_less_def max_strict_def elim!:max_ext.cases intro: one_step_implies_mult)
  1863 
  1864 inductive pw_leq
  1865 where
  1866   pw_leq_empty: "pw_leq {#} {#}"
  1867 | pw_leq_step:  "\<lbrakk>(x,y) \<in> pair_leq; pw_leq X Y \<rbrakk> \<Longrightarrow> pw_leq ({#x#} + X) ({#y#} + Y)"
  1868 
  1869 lemma pw_leq_lstep:
  1870   "(x, y) \<in> pair_leq \<Longrightarrow> pw_leq {#x#} {#y#}"
  1871 by (drule pw_leq_step) (rule pw_leq_empty, simp)
  1872 
  1873 lemma pw_leq_split:
  1874   assumes "pw_leq X Y"
  1875   shows "\<exists>A B Z. X = A + Z \<and> Y = B + Z \<and> ((set_of A, set_of B) \<in> max_strict \<or> (B = {#} \<and> A = {#}))"
  1876   using assms
  1877 proof (induct)
  1878   case pw_leq_empty thus ?case by auto
  1879 next
  1880   case (pw_leq_step x y X Y)
  1881   then obtain A B Z where
  1882     [simp]: "X = A + Z" "Y = B + Z"
  1883       and 1[simp]: "(set_of A, set_of B) \<in> max_strict \<or> (B = {#} \<and> A = {#})"
  1884     by auto
  1885   from pw_leq_step have "x = y \<or> (x, y) \<in> pair_less"
  1886     unfolding pair_leq_def by auto
  1887   thus ?case
  1888   proof
  1889     assume [simp]: "x = y"
  1890     have
  1891       "{#x#} + X = A + ({#y#}+Z)
  1892       \<and> {#y#} + Y = B + ({#y#}+Z)
  1893       \<and> ((set_of A, set_of B) \<in> max_strict \<or> (B = {#} \<and> A = {#}))"
  1894       by (auto simp: ac_simps)
  1895     thus ?case by (intro exI)
  1896   next
  1897     assume A: "(x, y) \<in> pair_less"
  1898     let ?A' = "{#x#} + A" and ?B' = "{#y#} + B"
  1899     have "{#x#} + X = ?A' + Z"
  1900       "{#y#} + Y = ?B' + Z"
  1901       by (auto simp add: ac_simps)
  1902     moreover have
  1903       "(set_of ?A', set_of ?B') \<in> max_strict"
  1904       using 1 A unfolding max_strict_def
  1905       by (auto elim!: max_ext.cases)
  1906     ultimately show ?thesis by blast
  1907   qed
  1908 qed
  1909 
  1910 lemma
  1911   assumes pwleq: "pw_leq Z Z'"
  1912   shows ms_strictI: "(set_of A, set_of B) \<in> max_strict \<Longrightarrow> (Z + A, Z' + B) \<in> ms_strict"
  1913   and   ms_weakI1:  "(set_of A, set_of B) \<in> max_strict \<Longrightarrow> (Z + A, Z' + B) \<in> ms_weak"
  1914   and   ms_weakI2:  "(Z + {#}, Z' + {#}) \<in> ms_weak"
  1915 proof -
  1916   from pw_leq_split[OF pwleq]
  1917   obtain A' B' Z''
  1918     where [simp]: "Z = A' + Z''" "Z' = B' + Z''"
  1919     and mx_or_empty: "(set_of A', set_of B') \<in> max_strict \<or> (A' = {#} \<and> B' = {#})"
  1920     by blast
  1921   {
  1922     assume max: "(set_of A, set_of B) \<in> max_strict"
  1923     from mx_or_empty
  1924     have "(Z'' + (A + A'), Z'' + (B + B')) \<in> ms_strict"
  1925     proof
  1926       assume max': "(set_of A', set_of B') \<in> max_strict"
  1927       with max have "(set_of (A + A'), set_of (B + B')) \<in> max_strict"
  1928         by (auto simp: max_strict_def intro: max_ext_additive)
  1929       thus ?thesis by (rule smsI)
  1930     next
  1931       assume [simp]: "A' = {#} \<and> B' = {#}"
  1932       show ?thesis by (rule smsI) (auto intro: max)
  1933     qed
  1934     thus "(Z + A, Z' + B) \<in> ms_strict" by (simp add:ac_simps)
  1935     thus "(Z + A, Z' + B) \<in> ms_weak" by (simp add: ms_weak_def)
  1936   }
  1937   from mx_or_empty
  1938   have "(Z'' + A', Z'' + B') \<in> ms_weak" by (rule wmsI)
  1939   thus "(Z + {#}, Z' + {#}) \<in> ms_weak" by (simp add:ac_simps)
  1940 qed
  1941 
  1942 lemma empty_neutral: "{#} + x = x" "x + {#} = x"
  1943 and nonempty_plus: "{# x #} + rs \<noteq> {#}"
  1944 and nonempty_single: "{# x #} \<noteq> {#}"
  1945 by auto
  1946 
  1947 setup \<open>
  1948 let
  1949   fun msetT T = Type (@{type_name multiset}, [T]);
  1950 
  1951   fun mk_mset T [] = Const (@{const_abbrev Mempty}, msetT T)
  1952     | mk_mset T [x] = Const (@{const_name single}, T --> msetT T) $ x
  1953     | mk_mset T (x :: xs) =
  1954           Const (@{const_name plus}, msetT T --> msetT T --> msetT T) $
  1955                 mk_mset T [x] $ mk_mset T xs
  1956 
  1957   fun mset_member_tac m i =
  1958       (if m <= 0 then
  1959            rtac @{thm multi_member_this} i ORELSE rtac @{thm multi_member_last} i
  1960        else
  1961            rtac @{thm multi_member_skip} i THEN mset_member_tac (m - 1) i)
  1962 
  1963   val mset_nonempty_tac =
  1964       rtac @{thm nonempty_plus} ORELSE' rtac @{thm nonempty_single}
  1965 
  1966   fun regroup_munion_conv ctxt =
  1967     Function_Lib.regroup_conv ctxt @{const_abbrev Mempty} @{const_name plus}
  1968       (map (fn t => t RS eq_reflection) (@{thms ac_simps} @ @{thms empty_neutral}))
  1969 
  1970   fun unfold_pwleq_tac i =
  1971     (rtac @{thm pw_leq_step} i THEN (fn st => unfold_pwleq_tac (i + 1) st))
  1972       ORELSE (rtac @{thm pw_leq_lstep} i)
  1973       ORELSE (rtac @{thm pw_leq_empty} i)
  1974 
  1975   val set_of_simps = [@{thm set_of_empty}, @{thm set_of_single}, @{thm set_of_union},
  1976                       @{thm Un_insert_left}, @{thm Un_empty_left}]
  1977 in
  1978   ScnpReconstruct.multiset_setup (ScnpReconstruct.Multiset
  1979   {
  1980     msetT=msetT, mk_mset=mk_mset, mset_regroup_conv=regroup_munion_conv,
  1981     mset_member_tac=mset_member_tac, mset_nonempty_tac=mset_nonempty_tac,
  1982     mset_pwleq_tac=unfold_pwleq_tac, set_of_simps=set_of_simps,
  1983     smsI'= @{thm ms_strictI}, wmsI2''= @{thm ms_weakI2}, wmsI1= @{thm ms_weakI1},
  1984     reduction_pair= @{thm ms_reduction_pair}
  1985   })
  1986 end
  1987 \<close>
  1988 
  1989 
  1990 subsection \<open>Legacy theorem bindings\<close>
  1991 
  1992 lemmas multi_count_eq = multiset_eq_iff [symmetric]
  1993 
  1994 lemma union_commute: "M + N = N + (M::'a multiset)"
  1995   by (fact add.commute)
  1996 
  1997 lemma union_assoc: "(M + N) + K = M + (N + (K::'a multiset))"
  1998   by (fact add.assoc)
  1999 
  2000 lemma union_lcomm: "M + (N + K) = N + (M + (K::'a multiset))"
  2001   by (fact add.left_commute)
  2002 
  2003 lemmas union_ac = union_assoc union_commute union_lcomm
  2004 
  2005 lemma union_right_cancel: "M + K = N + K \<longleftrightarrow> M = (N::'a multiset)"
  2006   by (fact add_right_cancel)
  2007 
  2008 lemma union_left_cancel: "K + M = K + N \<longleftrightarrow> M = (N::'a multiset)"
  2009   by (fact add_left_cancel)
  2010 
  2011 lemma multi_union_self_other_eq: "(A::'a multiset) + X = A + Y \<Longrightarrow> X = Y"
  2012   by (fact add_left_imp_eq)
  2013 
  2014 lemma mset_less_trans: "(M::'a multiset) <# K \<Longrightarrow> K <# N \<Longrightarrow> M <# N"
  2015   by (fact subset_mset.less_trans)
  2016 
  2017 lemma multiset_inter_commute: "A #\<inter> B = B #\<inter> A"
  2018   by (fact subset_mset.inf.commute)
  2019 
  2020 lemma multiset_inter_assoc: "A #\<inter> (B #\<inter> C) = A #\<inter> B #\<inter> C"
  2021   by (fact subset_mset.inf.assoc [symmetric])
  2022 
  2023 lemma multiset_inter_left_commute: "A #\<inter> (B #\<inter> C) = B #\<inter> (A #\<inter> C)"
  2024   by (fact subset_mset.inf.left_commute)
  2025 
  2026 lemmas multiset_inter_ac =
  2027   multiset_inter_commute
  2028   multiset_inter_assoc
  2029   multiset_inter_left_commute
  2030 
  2031 lemma mult_less_not_refl:
  2032   "\<not> M #\<subset># (M::'a::order multiset)"
  2033   by (fact multiset_order.less_irrefl)
  2034 
  2035 lemma mult_less_trans:
  2036   "K #\<subset># M ==> M #\<subset># N ==> K #\<subset># (N::'a::order multiset)"
  2037   by (fact multiset_order.less_trans)
  2038 
  2039 lemma mult_less_not_sym:
  2040   "M #\<subset># N ==> \<not> N #\<subset># (M::'a::order multiset)"
  2041   by (fact multiset_order.less_not_sym)
  2042 
  2043 lemma mult_less_asym:
  2044   "M #\<subset># N ==> (\<not> P ==> N #\<subset># (M::'a::order multiset)) ==> P"
  2045   by (fact multiset_order.less_asym)
  2046 
  2047 ML \<open>
  2048 fun multiset_postproc _ maybe_name all_values (T as Type (_, [elem_T]))
  2049                       (Const _ $ t') =
  2050     let
  2051       val (maybe_opt, ps) =
  2052         Nitpick_Model.dest_plain_fun t' ||> op ~~
  2053         ||> map (apsnd (snd o HOLogic.dest_number))
  2054       fun elems_for t =
  2055         case AList.lookup (op =) ps t of
  2056           SOME n => replicate n t
  2057         | NONE => [Const (maybe_name, elem_T --> elem_T) $ t]
  2058     in
  2059       case maps elems_for (all_values elem_T) @
  2060            (if maybe_opt then [Const (Nitpick_Model.unrep (), elem_T)]
  2061             else []) of
  2062         [] => Const (@{const_name zero_class.zero}, T)
  2063       | ts => foldl1 (fn (t1, t2) =>
  2064                          Const (@{const_name plus_class.plus}, T --> T --> T)
  2065                          $ t1 $ t2)
  2066                      (map (curry (op $) (Const (@{const_name single},
  2067                                                 elem_T --> T))) ts)
  2068     end
  2069   | multiset_postproc _ _ _ _ t = t
  2070 \<close>
  2071 
  2072 declaration \<open>
  2073 Nitpick_Model.register_term_postprocessor @{typ "'a multiset"}
  2074     multiset_postproc
  2075 \<close>
  2076 
  2077 
  2078 subsection \<open>Naive implementation using lists\<close>
  2079 
  2080 code_datatype multiset_of
  2081 
  2082 lemma [code]:
  2083   "{#} = multiset_of []"
  2084   by simp
  2085 
  2086 lemma [code]:
  2087   "{#x#} = multiset_of [x]"
  2088   by simp
  2089 
  2090 lemma union_code [code]:
  2091   "multiset_of xs + multiset_of ys = multiset_of (xs @ ys)"
  2092   by simp
  2093 
  2094 lemma [code]:
  2095   "image_mset f (multiset_of xs) = multiset_of (map f xs)"
  2096   by (simp add: multiset_of_map)
  2097 
  2098 lemma [code]:
  2099   "filter_mset f (multiset_of xs) = multiset_of (filter f xs)"
  2100   by (simp add: multiset_of_filter)
  2101 
  2102 lemma [code]:
  2103   "multiset_of xs - multiset_of ys = multiset_of (fold remove1 ys xs)"
  2104   by (rule sym, induct ys arbitrary: xs) (simp_all add: diff_add diff_right_commute)
  2105 
  2106 lemma [code]:
  2107   "multiset_of xs #\<inter> multiset_of ys =
  2108     multiset_of (snd (fold (\<lambda>x (ys, zs).
  2109       if x \<in> set ys then (remove1 x ys, x # zs) else (ys, zs)) xs (ys, [])))"
  2110 proof -
  2111   have "\<And>zs. multiset_of (snd (fold (\<lambda>x (ys, zs).
  2112     if x \<in> set ys then (remove1 x ys, x # zs) else (ys, zs)) xs (ys, zs))) =
  2113       (multiset_of xs #\<inter> multiset_of ys) + multiset_of zs"
  2114     by (induct xs arbitrary: ys)
  2115       (auto simp add: mem_set_multiset_eq inter_add_right1 inter_add_right2 ac_simps)
  2116   then show ?thesis by simp
  2117 qed
  2118 
  2119 lemma [code]:
  2120   "multiset_of xs #\<union> multiset_of ys =
  2121     multiset_of (split append (fold (\<lambda>x (ys, zs). (remove1 x ys, x # zs)) xs (ys, [])))"
  2122 proof -
  2123   have "\<And>zs. multiset_of (split append (fold (\<lambda>x (ys, zs). (remove1 x ys, x # zs)) xs (ys, zs))) =
  2124       (multiset_of xs #\<union> multiset_of ys) + multiset_of zs"
  2125     by (induct xs arbitrary: ys) (simp_all add: multiset_eq_iff)
  2126   then show ?thesis by simp
  2127 qed
  2128 
  2129 declare in_multiset_in_set [code_unfold]
  2130 
  2131 lemma [code]:
  2132   "count (multiset_of xs) x = fold (\<lambda>y. if x = y then Suc else id) xs 0"
  2133 proof -
  2134   have "\<And>n. fold (\<lambda>y. if x = y then Suc else id) xs n = count (multiset_of xs) x + n"
  2135     by (induct xs) simp_all
  2136   then show ?thesis by simp
  2137 qed
  2138 
  2139 declare set_of_multiset_of [code]
  2140 
  2141 declare sorted_list_of_multiset_multiset_of [code]
  2142 
  2143 lemma [code]: -- \<open>not very efficient, but representation-ignorant!\<close>
  2144   "multiset_of_set A = multiset_of (sorted_list_of_set A)"
  2145   apply (cases "finite A")
  2146   apply simp_all
  2147   apply (induct A rule: finite_induct)
  2148   apply (simp_all add: add.commute)
  2149   done
  2150 
  2151 declare size_multiset_of [code]
  2152 
  2153 fun ms_lesseq_impl :: "'a list \<Rightarrow> 'a list \<Rightarrow> bool option" where
  2154   "ms_lesseq_impl [] ys = Some (ys \<noteq> [])"
  2155 | "ms_lesseq_impl (Cons x xs) ys = (case List.extract (op = x) ys of
  2156      None \<Rightarrow> None
  2157    | Some (ys1,_,ys2) \<Rightarrow> ms_lesseq_impl xs (ys1 @ ys2))"
  2158 
  2159 lemma ms_lesseq_impl: "(ms_lesseq_impl xs ys = None \<longleftrightarrow> \<not> multiset_of xs \<le># multiset_of ys) \<and>
  2160   (ms_lesseq_impl xs ys = Some True \<longleftrightarrow> multiset_of xs <# multiset_of ys) \<and>
  2161   (ms_lesseq_impl xs ys = Some False \<longrightarrow> multiset_of xs = multiset_of ys)"
  2162 proof (induct xs arbitrary: ys)
  2163   case (Nil ys)
  2164   show ?case by (auto simp: mset_less_empty_nonempty)
  2165 next
  2166   case (Cons x xs ys)
  2167   show ?case
  2168   proof (cases "List.extract (op = x) ys")
  2169     case None
  2170     hence x: "x \<notin> set ys" by (simp add: extract_None_iff)
  2171     {
  2172       assume "multiset_of (x # xs) \<le># multiset_of ys"
  2173       from set_of_mono[OF this] x have False by simp
  2174     } note nle = this
  2175     moreover
  2176     {
  2177       assume "multiset_of (x # xs) <# multiset_of ys"
  2178       hence "multiset_of (x # xs) \<le># multiset_of ys" by auto
  2179       from nle[OF this] have False .
  2180     }
  2181     ultimately show ?thesis using None by auto
  2182   next
  2183     case (Some res)
  2184     obtain ys1 y ys2 where res: "res = (ys1,y,ys2)" by (cases res, auto)
  2185     note Some = Some[unfolded res]
  2186     from extract_SomeE[OF Some] have "ys = ys1 @ x # ys2" by simp
  2187     hence id: "multiset_of ys = multiset_of (ys1 @ ys2) + {#x#}"
  2188       by (auto simp: ac_simps)
  2189     show ?thesis unfolding ms_lesseq_impl.simps
  2190       unfolding Some option.simps split
  2191       unfolding id
  2192       using Cons[of "ys1 @ ys2"]
  2193       unfolding subset_mset_def subseteq_mset_def by auto
  2194   qed
  2195 qed
  2196 
  2197 lemma [code]: "multiset_of xs \<le># multiset_of ys \<longleftrightarrow> ms_lesseq_impl xs ys \<noteq> None"
  2198   using ms_lesseq_impl[of xs ys] by (cases "ms_lesseq_impl xs ys", auto)
  2199 
  2200 lemma [code]: "multiset_of xs <# multiset_of ys \<longleftrightarrow> ms_lesseq_impl xs ys = Some True"
  2201   using ms_lesseq_impl[of xs ys] by (cases "ms_lesseq_impl xs ys", auto)
  2202 
  2203 instantiation multiset :: (equal) equal
  2204 begin
  2205 
  2206 definition
  2207   [code del]: "HOL.equal A (B :: 'a multiset) \<longleftrightarrow> A = B"
  2208 lemma [code]: "HOL.equal (multiset_of xs) (multiset_of ys) \<longleftrightarrow> ms_lesseq_impl xs ys = Some False"
  2209   unfolding equal_multiset_def
  2210   using ms_lesseq_impl[of xs ys] by (cases "ms_lesseq_impl xs ys", auto)
  2211 
  2212 instance
  2213   by default (simp add: equal_multiset_def)
  2214 end
  2215 
  2216 lemma [code]:
  2217   "msetsum (multiset_of xs) = listsum xs"
  2218   by (induct xs) (simp_all add: add.commute)
  2219 
  2220 lemma [code]:
  2221   "msetprod (multiset_of xs) = fold times xs 1"
  2222 proof -
  2223   have "\<And>x. fold times xs x = msetprod (multiset_of xs) * x"
  2224     by (induct xs) (simp_all add: mult.assoc)
  2225   then show ?thesis by simp
  2226 qed
  2227 
  2228 text \<open>
  2229   Exercise for the casual reader: add implementations for @{const le_multiset}
  2230   and @{const less_multiset} (multiset order).
  2231 \<close>
  2232 
  2233 text \<open>Quickcheck generators\<close>
  2234 
  2235 definition (in term_syntax)
  2236   msetify :: "'a\<Colon>typerep list \<times> (unit \<Rightarrow> Code_Evaluation.term)
  2237     \<Rightarrow> 'a multiset \<times> (unit \<Rightarrow> Code_Evaluation.term)" where
  2238   [code_unfold]: "msetify xs = Code_Evaluation.valtermify multiset_of {\<cdot>} xs"
  2239 
  2240 notation fcomp (infixl "\<circ>>" 60)
  2241 notation scomp (infixl "\<circ>\<rightarrow>" 60)
  2242 
  2243 instantiation multiset :: (random) random
  2244 begin
  2245 
  2246 definition
  2247   "Quickcheck_Random.random i = Quickcheck_Random.random i \<circ>\<rightarrow> (\<lambda>xs. Pair (msetify xs))"
  2248 
  2249 instance ..
  2250 
  2251 end
  2252 
  2253 no_notation fcomp (infixl "\<circ>>" 60)
  2254 no_notation scomp (infixl "\<circ>\<rightarrow>" 60)
  2255 
  2256 instantiation multiset :: (full_exhaustive) full_exhaustive
  2257 begin
  2258 
  2259 definition full_exhaustive_multiset :: "('a multiset \<times> (unit \<Rightarrow> term) \<Rightarrow> (bool \<times> term list) option) \<Rightarrow> natural \<Rightarrow> (bool \<times> term list) option"
  2260 where
  2261   "full_exhaustive_multiset f i = Quickcheck_Exhaustive.full_exhaustive (\<lambda>xs. f (msetify xs)) i"
  2262 
  2263 instance ..
  2264 
  2265 end
  2266 
  2267 hide_const (open) msetify
  2268 
  2269 
  2270 subsection \<open>BNF setup\<close>
  2271 
  2272 definition rel_mset where
  2273   "rel_mset R X Y \<longleftrightarrow> (\<exists>xs ys. multiset_of xs = X \<and> multiset_of ys = Y \<and> list_all2 R xs ys)"
  2274 
  2275 lemma multiset_of_zip_take_Cons_drop_twice:
  2276   assumes "length xs = length ys" "j \<le> length xs"
  2277   shows "multiset_of (zip (take j xs @ x # drop j xs) (take j ys @ y # drop j ys)) =
  2278     multiset_of (zip xs ys) + {#(x, y)#}"
  2279 using assms
  2280 proof (induct xs ys arbitrary: x y j rule: list_induct2)
  2281   case Nil
  2282   thus ?case
  2283     by simp
  2284 next
  2285   case (Cons x xs y ys)
  2286   thus ?case
  2287   proof (cases "j = 0")
  2288     case True
  2289     thus ?thesis
  2290       by simp
  2291   next
  2292     case False
  2293     then obtain k where k: "j = Suc k"
  2294       by (case_tac j) simp
  2295     hence "k \<le> length xs"
  2296       using Cons.prems by auto
  2297     hence "multiset_of (zip (take k xs @ x # drop k xs) (take k ys @ y # drop k ys)) =
  2298       multiset_of (zip xs ys) + {#(x, y)#}"
  2299       by (rule Cons.hyps(2))
  2300     thus ?thesis
  2301       unfolding k by (auto simp: add.commute union_lcomm)
  2302   qed
  2303 qed
  2304 
  2305 lemma ex_multiset_of_zip_left:
  2306   assumes "length xs = length ys" "multiset_of xs' = multiset_of xs"
  2307   shows "\<exists>ys'. length ys' = length xs' \<and> multiset_of (zip xs' ys') = multiset_of (zip xs ys)"
  2308 using assms
  2309 proof (induct xs ys arbitrary: xs' rule: list_induct2)
  2310   case Nil
  2311   thus ?case
  2312     by auto
  2313 next
  2314   case (Cons x xs y ys xs')
  2315   obtain j where j_len: "j < length xs'" and nth_j: "xs' ! j = x"
  2316     by (metis Cons.prems in_set_conv_nth list.set_intros(1) multiset_of_eq_setD)
  2317 
  2318   def xsa \<equiv> "take j xs' @ drop (Suc j) xs'"
  2319   have "multiset_of xs' = {#x#} + multiset_of xsa"
  2320     unfolding xsa_def using j_len nth_j
  2321     by (metis (no_types) ab_semigroup_add_class.add_ac(1) append_take_drop_id Cons_nth_drop_Suc
  2322       multiset_of.simps(2) union_code add.commute)
  2323   hence ms_x: "multiset_of xsa = multiset_of xs"
  2324     by (metis Cons.prems add.commute add_right_imp_eq multiset_of.simps(2))
  2325   then obtain ysa where
  2326     len_a: "length ysa = length xsa" and ms_a: "multiset_of (zip xsa ysa) = multiset_of (zip xs ys)"
  2327     using Cons.hyps(2) by blast
  2328 
  2329   def ys' \<equiv> "take j ysa @ y # drop j ysa"
  2330   have xs': "xs' = take j xsa @ x # drop j xsa"
  2331     using ms_x j_len nth_j Cons.prems xsa_def
  2332     by (metis append_eq_append_conv append_take_drop_id diff_Suc_Suc Cons_nth_drop_Suc length_Cons
  2333       length_drop size_multiset_of)
  2334   have j_len': "j \<le> length xsa"
  2335     using j_len xs' xsa_def
  2336     by (metis add_Suc_right append_take_drop_id length_Cons length_append less_eq_Suc_le not_less)
  2337   have "length ys' = length xs'"
  2338     unfolding ys'_def using Cons.prems len_a ms_x
  2339     by (metis add_Suc_right append_take_drop_id length_Cons length_append multiset_of_eq_length)
  2340   moreover have "multiset_of (zip xs' ys') = multiset_of (zip (x # xs) (y # ys))"
  2341     unfolding xs' ys'_def
  2342     by (rule trans[OF multiset_of_zip_take_Cons_drop_twice])
  2343       (auto simp: len_a ms_a j_len' add.commute)
  2344   ultimately show ?case
  2345     by blast
  2346 qed
  2347 
  2348 lemma list_all2_reorder_left_invariance:
  2349   assumes rel: "list_all2 R xs ys" and ms_x: "multiset_of xs' = multiset_of xs"
  2350   shows "\<exists>ys'. list_all2 R xs' ys' \<and> multiset_of ys' = multiset_of ys"
  2351 proof -
  2352   have len: "length xs = length ys"
  2353     using rel list_all2_conv_all_nth by auto
  2354   obtain ys' where
  2355     len': "length xs' = length ys'" and ms_xy: "multiset_of (zip xs' ys') = multiset_of (zip xs ys)"
  2356     using len ms_x by (metis ex_multiset_of_zip_left)
  2357   have "list_all2 R xs' ys'"
  2358     using assms(1) len' ms_xy unfolding list_all2_iff by (blast dest: multiset_of_eq_setD)
  2359   moreover have "multiset_of ys' = multiset_of ys"
  2360     using len len' ms_xy map_snd_zip multiset_of_map by metis
  2361   ultimately show ?thesis
  2362     by blast
  2363 qed
  2364 
  2365 lemma ex_multiset_of: "\<exists>xs. multiset_of xs = X"
  2366   by (induct X) (simp, metis multiset_of.simps(2))
  2367 
  2368 bnf "'a multiset"
  2369   map: image_mset
  2370   sets: set_of
  2371   bd: natLeq
  2372   wits: "{#}"
  2373   rel: rel_mset
  2374 proof -
  2375   show "image_mset id = id"
  2376     by (rule image_mset.id)
  2377 next
  2378   show "\<And>f g. image_mset (g \<circ> f) = image_mset g \<circ> image_mset f"
  2379     unfolding comp_def by (rule ext) (simp add: comp_def image_mset.compositionality)
  2380 next
  2381   fix X :: "'a multiset"
  2382   show "\<And>f g. (\<And>z. z \<in> set_of X \<Longrightarrow> f z = g z) \<Longrightarrow> image_mset f X = image_mset g X"
  2383     by (induct X, (simp (no_asm))+,
  2384       metis One_nat_def Un_iff count_single mem_set_of_iff set_of_union zero_less_Suc)
  2385 next
  2386   show "\<And>f. set_of \<circ> image_mset f = op ` f \<circ> set_of"
  2387     by auto
  2388 next
  2389   show "card_order natLeq"
  2390     by (rule natLeq_card_order)
  2391 next
  2392   show "BNF_Cardinal_Arithmetic.cinfinite natLeq"
  2393     by (rule natLeq_cinfinite)
  2394 next
  2395   show "\<And>X. ordLeq3 (card_of (set_of X)) natLeq"
  2396     by transfer
  2397       (auto intro!: ordLess_imp_ordLeq simp: finite_iff_ordLess_natLeq[symmetric] multiset_def)
  2398 next
  2399   show "\<And>R S. rel_mset R OO rel_mset S \<le> rel_mset (R OO S)"
  2400     unfolding rel_mset_def[abs_def] OO_def
  2401     apply clarify
  2402     apply (rename_tac X Z Y xs ys' ys zs)
  2403     apply (drule_tac xs = ys' and ys = zs and xs' = ys in list_all2_reorder_left_invariance)
  2404     by (auto intro: list_all2_trans)
  2405 next
  2406   show "\<And>R. rel_mset R =
  2407     (BNF_Def.Grp {x. set_of x \<subseteq> {(x, y). R x y}} (image_mset fst))\<inverse>\<inverse> OO
  2408     BNF_Def.Grp {x. set_of x \<subseteq> {(x, y). R x y}} (image_mset snd)"
  2409     unfolding rel_mset_def[abs_def] BNF_Def.Grp_def OO_def
  2410     apply (rule ext)+
  2411     apply auto
  2412      apply (rule_tac x = "multiset_of (zip xs ys)" in exI; auto)
  2413         apply (metis list_all2_lengthD map_fst_zip multiset_of_map)
  2414        apply (auto simp: list_all2_iff)[1]
  2415       apply (metis list_all2_lengthD map_snd_zip multiset_of_map)
  2416      apply (auto simp: list_all2_iff)[1]
  2417     apply (rename_tac XY)
  2418     apply (cut_tac X = XY in ex_multiset_of)
  2419     apply (erule exE)
  2420     apply (rename_tac xys)
  2421     apply (rule_tac x = "map fst xys" in exI)
  2422     apply (auto simp: multiset_of_map)
  2423     apply (rule_tac x = "map snd xys" in exI)
  2424     apply (auto simp: multiset_of_map list_all2I subset_eq zip_map_fst_snd)
  2425     done
  2426 next
  2427   show "\<And>z. z \<in> set_of {#} \<Longrightarrow> False"
  2428     by auto
  2429 qed
  2430 
  2431 inductive rel_mset' where
  2432   Zero[intro]: "rel_mset' R {#} {#}"
  2433 | Plus[intro]: "\<lbrakk>R a b; rel_mset' R M N\<rbrakk> \<Longrightarrow> rel_mset' R (M + {#a#}) (N + {#b#})"
  2434 
  2435 lemma rel_mset_Zero: "rel_mset R {#} {#}"
  2436 unfolding rel_mset_def Grp_def by auto
  2437 
  2438 declare multiset.count[simp]
  2439 declare Abs_multiset_inverse[simp]
  2440 declare multiset.count_inverse[simp]
  2441 declare union_preserves_multiset[simp]
  2442 
  2443 lemma rel_mset_Plus:
  2444 assumes ab: "R a b" and MN: "rel_mset R M N"
  2445 shows "rel_mset R (M + {#a#}) (N + {#b#})"
  2446 proof-
  2447   {fix y assume "R a b" and "set_of y \<subseteq> {(x, y). R x y}"
  2448    hence "\<exists>ya. image_mset fst y + {#a#} = image_mset fst ya \<and>
  2449                image_mset snd y + {#b#} = image_mset snd ya \<and>
  2450                set_of ya \<subseteq> {(x, y). R x y}"
  2451    apply(intro exI[of _ "y + {#(a,b)#}"]) by auto
  2452   }
  2453   thus ?thesis
  2454   using assms
  2455   unfolding multiset.rel_compp_Grp Grp_def by blast
  2456 qed
  2457 
  2458 lemma rel_mset'_imp_rel_mset:
  2459   "rel_mset' R M N \<Longrightarrow> rel_mset R M N"
  2460 apply(induct rule: rel_mset'.induct)
  2461 using rel_mset_Zero rel_mset_Plus by auto
  2462 
  2463 lemma rel_mset_size:
  2464   "rel_mset R M N \<Longrightarrow> size M = size N"
  2465 unfolding multiset.rel_compp_Grp Grp_def by auto
  2466 
  2467 lemma multiset_induct2[case_names empty addL addR]:
  2468 assumes empty: "P {#} {#}"
  2469 and addL: "\<And>M N a. P M N \<Longrightarrow> P (M + {#a#}) N"
  2470 and addR: "\<And>M N a. P M N \<Longrightarrow> P M (N + {#a#})"
  2471 shows "P M N"
  2472 apply(induct N rule: multiset_induct)
  2473   apply(induct M rule: multiset_induct, rule empty, erule addL)
  2474   apply(induct M rule: multiset_induct, erule addR, erule addR)
  2475 done
  2476 
  2477 lemma multiset_induct2_size[consumes 1, case_names empty add]:
  2478 assumes c: "size M = size N"
  2479 and empty: "P {#} {#}"
  2480 and add: "\<And>M N a b. P M N \<Longrightarrow> P (M + {#a#}) (N + {#b#})"
  2481 shows "P M N"
  2482 using c proof(induct M arbitrary: N rule: measure_induct_rule[of size])
  2483   case (less M)  show ?case
  2484   proof(cases "M = {#}")
  2485     case True hence "N = {#}" using less.prems by auto
  2486     thus ?thesis using True empty by auto
  2487   next
  2488     case False then obtain M1 a where M: "M = M1 + {#a#}" by (metis multi_nonempty_split)
  2489     have "N \<noteq> {#}" using False less.prems by auto
  2490     then obtain N1 b where N: "N = N1 + {#b#}" by (metis multi_nonempty_split)
  2491     have "size M1 = size N1" using less.prems unfolding M N by auto
  2492     thus ?thesis using M N less.hyps add by auto
  2493   qed
  2494 qed
  2495 
  2496 lemma msed_map_invL:
  2497 assumes "image_mset f (M + {#a#}) = N"
  2498 shows "\<exists>N1. N = N1 + {#f a#} \<and> image_mset f M = N1"
  2499 proof-
  2500   have "f a \<in># N"
  2501   using assms multiset.set_map[of f "M + {#a#}"] by auto
  2502   then obtain N1 where N: "N = N1 + {#f a#}" using multi_member_split by metis
  2503   have "image_mset f M = N1" using assms unfolding N by simp
  2504   thus ?thesis using N by blast
  2505 qed
  2506 
  2507 lemma msed_map_invR:
  2508 assumes "image_mset f M = N + {#b#}"
  2509 shows "\<exists>M1 a. M = M1 + {#a#} \<and> f a = b \<and> image_mset f M1 = N"
  2510 proof-
  2511   obtain a where a: "a \<in># M" and fa: "f a = b"
  2512   using multiset.set_map[of f M] unfolding assms
  2513   by (metis image_iff mem_set_of_iff union_single_eq_member)
  2514   then obtain M1 where M: "M = M1 + {#a#}" using multi_member_split by metis
  2515   have "image_mset f M1 = N" using assms unfolding M fa[symmetric] by simp
  2516   thus ?thesis using M fa by blast
  2517 qed
  2518 
  2519 lemma msed_rel_invL:
  2520 assumes "rel_mset R (M + {#a#}) N"
  2521 shows "\<exists>N1 b. N = N1 + {#b#} \<and> R a b \<and> rel_mset R M N1"
  2522 proof-
  2523   obtain K where KM: "image_mset fst K = M + {#a#}"
  2524   and KN: "image_mset snd K = N" and sK: "set_of K \<subseteq> {(a, b). R a b}"
  2525   using assms
  2526   unfolding multiset.rel_compp_Grp Grp_def by auto
  2527   obtain K1 ab where K: "K = K1 + {#ab#}" and a: "fst ab = a"
  2528   and K1M: "image_mset fst K1 = M" using msed_map_invR[OF KM] by auto
  2529   obtain N1 where N: "N = N1 + {#snd ab#}" and K1N1: "image_mset snd K1 = N1"
  2530   using msed_map_invL[OF KN[unfolded K]] by auto
  2531   have Rab: "R a (snd ab)" using sK a unfolding K by auto
  2532   have "rel_mset R M N1" using sK K1M K1N1
  2533   unfolding K multiset.rel_compp_Grp Grp_def by auto
  2534   thus ?thesis using N Rab by auto
  2535 qed
  2536 
  2537 lemma msed_rel_invR:
  2538 assumes "rel_mset R M (N + {#b#})"
  2539 shows "\<exists>M1 a. M = M1 + {#a#} \<and> R a b \<and> rel_mset R M1 N"
  2540 proof-
  2541   obtain K where KN: "image_mset snd K = N + {#b#}"
  2542   and KM: "image_mset fst K = M" and sK: "set_of K \<subseteq> {(a, b). R a b}"
  2543   using assms
  2544   unfolding multiset.rel_compp_Grp Grp_def by auto
  2545   obtain K1 ab where K: "K = K1 + {#ab#}" and b: "snd ab = b"
  2546   and K1N: "image_mset snd K1 = N" using msed_map_invR[OF KN] by auto
  2547   obtain M1 where M: "M = M1 + {#fst ab#}" and K1M1: "image_mset fst K1 = M1"
  2548   using msed_map_invL[OF KM[unfolded K]] by auto
  2549   have Rab: "R (fst ab) b" using sK b unfolding K by auto
  2550   have "rel_mset R M1 N" using sK K1N K1M1
  2551   unfolding K multiset.rel_compp_Grp Grp_def by auto
  2552   thus ?thesis using M Rab by auto
  2553 qed
  2554 
  2555 lemma rel_mset_imp_rel_mset':
  2556 assumes "rel_mset R M N"
  2557 shows "rel_mset' R M N"
  2558 using assms proof(induct M arbitrary: N rule: measure_induct_rule[of size])
  2559   case (less M)
  2560   have c: "size M = size N" using rel_mset_size[OF less.prems] .
  2561   show ?case
  2562   proof(cases "M = {#}")
  2563     case True hence "N = {#}" using c by simp
  2564     thus ?thesis using True rel_mset'.Zero by auto
  2565   next
  2566     case False then obtain M1 a where M: "M = M1 + {#a#}" by (metis multi_nonempty_split)
  2567     obtain N1 b where N: "N = N1 + {#b#}" and R: "R a b" and ms: "rel_mset R M1 N1"
  2568     using msed_rel_invL[OF less.prems[unfolded M]] by auto
  2569     have "rel_mset' R M1 N1" using less.hyps[of M1 N1] ms unfolding M by simp
  2570     thus ?thesis using rel_mset'.Plus[of R a b, OF R] unfolding M N by simp
  2571   qed
  2572 qed
  2573 
  2574 lemma rel_mset_rel_mset':
  2575 "rel_mset R M N = rel_mset' R M N"
  2576 using rel_mset_imp_rel_mset' rel_mset'_imp_rel_mset by auto
  2577 
  2578 (* The main end product for rel_mset: inductive characterization *)
  2579 theorems rel_mset_induct[case_names empty add, induct pred: rel_mset] =
  2580          rel_mset'.induct[unfolded rel_mset_rel_mset'[symmetric]]
  2581 
  2582 
  2583 subsection \<open>Size setup\<close>
  2584 
  2585 lemma multiset_size_o_map: "size_multiset g \<circ> image_mset f = size_multiset (g \<circ> f)"
  2586   unfolding o_apply by (rule ext) (induct_tac, auto)
  2587 
  2588 setup \<open>
  2589 BNF_LFP_Size.register_size_global @{type_name multiset} @{const_name size_multiset}
  2590   @{thms size_multiset_empty size_multiset_single size_multiset_union size_empty size_single
  2591     size_union}
  2592   @{thms multiset_size_o_map}
  2593 \<close>
  2594 
  2595 hide_const (open) wcount
  2596 
  2597 end