src/HOL/Library/Multiset.thy
author haftmann
Fri Mar 22 19:18:08 2019 +0000 (4 months ago)
changeset 69946 494934c30f38
parent 69895 6b03a8cf092d
permissions -rw-r--r--
improved code equations taken over from AFP
     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 Cancellation
    13 begin
    14 
    15 subsection \<open>The type of multisets\<close>
    16 
    17 definition "multiset = {f :: 'a \<Rightarrow> nat. finite {x. f x > 0}}"
    18 
    19 typedef 'a multiset = "multiset :: ('a \<Rightarrow> 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 lemma multiset_eq_iff: "M = N \<longleftrightarrow> (\<forall>a. count M a = count N a)"
    29   by (simp only: count_inject [symmetric] fun_eq_iff)
    30 
    31 lemma multiset_eqI: "(\<And>x. count A x = count B x) \<Longrightarrow> A = B"
    32   using multiset_eq_iff by auto
    33 
    34 text \<open>Preservation of the representing set \<^term>\<open>multiset\<close>.\<close>
    35 
    36 lemma const0_in_multiset: "(\<lambda>a. 0) \<in> multiset"
    37   by (simp add: multiset_def)
    38 
    39 lemma only1_in_multiset: "(\<lambda>b. if b = a then n else 0) \<in> multiset"
    40   by (simp add: multiset_def)
    41 
    42 lemma union_preserves_multiset: "M \<in> multiset \<Longrightarrow> N \<in> multiset \<Longrightarrow> (\<lambda>a. M a + N a) \<in> multiset"
    43   by (simp add: multiset_def)
    44 
    45 lemma diff_preserves_multiset:
    46   assumes "M \<in> multiset"
    47   shows "(\<lambda>a. M a - N a) \<in> multiset"
    48 proof -
    49   have "{x. N x < M x} \<subseteq> {x. 0 < M x}"
    50     by auto
    51   with assms show ?thesis
    52     by (auto simp add: multiset_def intro: finite_subset)
    53 qed
    54 
    55 lemma filter_preserves_multiset:
    56   assumes "M \<in> multiset"
    57   shows "(\<lambda>x. if P x then M x else 0) \<in> multiset"
    58 proof -
    59   have "{x. (P x \<longrightarrow> 0 < M x) \<and> P x} \<subseteq> {x. 0 < M x}"
    60     by auto
    61   with assms show ?thesis
    62     by (auto simp add: multiset_def intro: finite_subset)
    63 qed
    64 
    65 lemmas in_multiset = const0_in_multiset only1_in_multiset
    66   union_preserves_multiset diff_preserves_multiset filter_preserves_multiset
    67 
    68 
    69 subsection \<open>Representing multisets\<close>
    70 
    71 text \<open>Multiset enumeration\<close>
    72 
    73 instantiation multiset :: (type) cancel_comm_monoid_add
    74 begin
    75 
    76 lift_definition zero_multiset :: "'a multiset" is "\<lambda>a. 0"
    77 by (rule const0_in_multiset)
    78 
    79 abbreviation Mempty :: "'a multiset" ("{#}") where
    80   "Mempty \<equiv> 0"
    81 
    82 lift_definition plus_multiset :: "'a multiset \<Rightarrow> 'a multiset \<Rightarrow> 'a multiset" is "\<lambda>M N. (\<lambda>a. M a + N a)"
    83 by (rule union_preserves_multiset)
    84 
    85 lift_definition minus_multiset :: "'a multiset \<Rightarrow> 'a multiset \<Rightarrow> 'a multiset" is "\<lambda> M N. \<lambda>a. M a - N a"
    86 by (rule diff_preserves_multiset)
    87 
    88 instance
    89   by (standard; transfer; simp add: fun_eq_iff)
    90 
    91 end
    92 
    93 context
    94 begin
    95 
    96 qualified definition is_empty :: "'a multiset \<Rightarrow> bool" where
    97   [code_abbrev]: "is_empty A \<longleftrightarrow> A = {#}"
    98 
    99 end
   100 
   101 lemma add_mset_in_multiset:
   102   assumes M: \<open>M \<in> multiset\<close>
   103   shows \<open>(\<lambda>b. if b = a then Suc (M b) else M b) \<in> multiset\<close>
   104   using assms by (simp add: multiset_def flip: insert_Collect)
   105 
   106 lift_definition add_mset :: "'a \<Rightarrow> 'a multiset \<Rightarrow> 'a multiset" is
   107   "\<lambda>a M b. if b = a then Suc (M b) else M b"
   108 by (rule add_mset_in_multiset)
   109 
   110 syntax
   111   "_multiset" :: "args \<Rightarrow> 'a multiset"    ("{#(_)#}")
   112 translations
   113   "{#x, xs#}" == "CONST add_mset x {#xs#}"
   114   "{#x#}" == "CONST add_mset x {#}"
   115 
   116 lemma count_empty [simp]: "count {#} a = 0"
   117   by (simp add: zero_multiset.rep_eq)
   118 
   119 lemma count_add_mset [simp]:
   120   "count (add_mset b A) a = (if b = a then Suc (count A a) else count A a)"
   121   by (simp add: add_mset.rep_eq)
   122 
   123 lemma count_single: "count {#b#} a = (if b = a then 1 else 0)"
   124   by simp
   125 
   126 lemma
   127   add_mset_not_empty [simp]: \<open>add_mset a A \<noteq> {#}\<close> and
   128   empty_not_add_mset [simp]: "{#} \<noteq> add_mset a A"
   129   by (auto simp: multiset_eq_iff)
   130 
   131 lemma add_mset_add_mset_same_iff [simp]:
   132   "add_mset a A = add_mset a B \<longleftrightarrow> A = B"
   133   by (auto simp: multiset_eq_iff)
   134 
   135 lemma add_mset_commute:
   136   "add_mset x (add_mset y M) = add_mset y (add_mset x M)"
   137   by (auto simp: multiset_eq_iff)
   138 
   139 
   140 subsection \<open>Basic operations\<close>
   141 
   142 subsubsection \<open>Conversion to set and membership\<close>
   143 
   144 definition set_mset :: "'a multiset \<Rightarrow> 'a set"
   145   where "set_mset M = {x. count M x > 0}"
   146 
   147 abbreviation Melem :: "'a \<Rightarrow> 'a multiset \<Rightarrow> bool"
   148   where "Melem a M \<equiv> a \<in> set_mset M"
   149 
   150 notation
   151   Melem  ("'(\<in>#')") and
   152   Melem  ("(_/ \<in># _)" [51, 51] 50)
   153 
   154 notation  (ASCII)
   155   Melem  ("'(:#')") and
   156   Melem  ("(_/ :# _)" [51, 51] 50)
   157 
   158 abbreviation not_Melem :: "'a \<Rightarrow> 'a multiset \<Rightarrow> bool"
   159   where "not_Melem a M \<equiv> a \<notin> set_mset M"
   160 
   161 notation
   162   not_Melem  ("'(\<notin>#')") and
   163   not_Melem  ("(_/ \<notin># _)" [51, 51] 50)
   164 
   165 notation  (ASCII)
   166   not_Melem  ("'(~:#')") and
   167   not_Melem  ("(_/ ~:# _)" [51, 51] 50)
   168 
   169 context
   170 begin
   171 
   172 qualified abbreviation Ball :: "'a multiset \<Rightarrow> ('a \<Rightarrow> bool) \<Rightarrow> bool"
   173   where "Ball M \<equiv> Set.Ball (set_mset M)"
   174 
   175 qualified abbreviation Bex :: "'a multiset \<Rightarrow> ('a \<Rightarrow> bool) \<Rightarrow> bool"
   176   where "Bex M \<equiv> Set.Bex (set_mset M)"
   177 
   178 end
   179 
   180 syntax
   181   "_MBall"       :: "pttrn \<Rightarrow> 'a set \<Rightarrow> bool \<Rightarrow> bool"      ("(3\<forall>_\<in>#_./ _)" [0, 0, 10] 10)
   182   "_MBex"        :: "pttrn \<Rightarrow> 'a set \<Rightarrow> bool \<Rightarrow> bool"      ("(3\<exists>_\<in>#_./ _)" [0, 0, 10] 10)
   183 
   184 syntax  (ASCII)
   185   "_MBall"       :: "pttrn \<Rightarrow> 'a set \<Rightarrow> bool \<Rightarrow> bool"      ("(3\<forall>_:#_./ _)" [0, 0, 10] 10)
   186   "_MBex"        :: "pttrn \<Rightarrow> 'a set \<Rightarrow> bool \<Rightarrow> bool"      ("(3\<exists>_:#_./ _)" [0, 0, 10] 10)
   187 
   188 translations
   189   "\<forall>x\<in>#A. P" \<rightleftharpoons> "CONST Multiset.Ball A (\<lambda>x. P)"
   190   "\<exists>x\<in>#A. P" \<rightleftharpoons> "CONST Multiset.Bex A (\<lambda>x. P)"
   191 
   192 lemma count_eq_zero_iff:
   193   "count M x = 0 \<longleftrightarrow> x \<notin># M"
   194   by (auto simp add: set_mset_def)
   195 
   196 lemma not_in_iff:
   197   "x \<notin># M \<longleftrightarrow> count M x = 0"
   198   by (auto simp add: count_eq_zero_iff)
   199 
   200 lemma count_greater_zero_iff [simp]:
   201   "count M x > 0 \<longleftrightarrow> x \<in># M"
   202   by (auto simp add: set_mset_def)
   203 
   204 lemma count_inI:
   205   assumes "count M x = 0 \<Longrightarrow> False"
   206   shows "x \<in># M"
   207 proof (rule ccontr)
   208   assume "x \<notin># M"
   209   with assms show False by (simp add: not_in_iff)
   210 qed
   211 
   212 lemma in_countE:
   213   assumes "x \<in># M"
   214   obtains n where "count M x = Suc n"
   215 proof -
   216   from assms have "count M x > 0" by simp
   217   then obtain n where "count M x = Suc n"
   218     using gr0_conv_Suc by blast
   219   with that show thesis .
   220 qed
   221 
   222 lemma count_greater_eq_Suc_zero_iff [simp]:
   223   "count M x \<ge> Suc 0 \<longleftrightarrow> x \<in># M"
   224   by (simp add: Suc_le_eq)
   225 
   226 lemma count_greater_eq_one_iff [simp]:
   227   "count M x \<ge> 1 \<longleftrightarrow> x \<in># M"
   228   by simp
   229 
   230 lemma set_mset_empty [simp]:
   231   "set_mset {#} = {}"
   232   by (simp add: set_mset_def)
   233 
   234 lemma set_mset_single:
   235   "set_mset {#b#} = {b}"
   236   by (simp add: set_mset_def)
   237 
   238 lemma set_mset_eq_empty_iff [simp]:
   239   "set_mset M = {} \<longleftrightarrow> M = {#}"
   240   by (auto simp add: multiset_eq_iff count_eq_zero_iff)
   241 
   242 lemma finite_set_mset [iff]:
   243   "finite (set_mset M)"
   244   using count [of M] by (simp add: multiset_def)
   245 
   246 lemma set_mset_add_mset_insert [simp]: \<open>set_mset (add_mset a A) = insert a (set_mset A)\<close>
   247   by (auto simp flip: count_greater_eq_Suc_zero_iff split: if_splits)
   248 
   249 lemma multiset_nonemptyE [elim]:
   250   assumes "A \<noteq> {#}"
   251   obtains x where "x \<in># A"
   252 proof -
   253   have "\<exists>x. x \<in># A" by (rule ccontr) (insert assms, auto)
   254   with that show ?thesis by blast
   255 qed
   256 
   257 
   258 subsubsection \<open>Union\<close>
   259 
   260 lemma count_union [simp]:
   261   "count (M + N) a = count M a + count N a"
   262   by (simp add: plus_multiset.rep_eq)
   263 
   264 lemma set_mset_union [simp]:
   265   "set_mset (M + N) = set_mset M \<union> set_mset N"
   266   by (simp only: set_eq_iff count_greater_zero_iff [symmetric] count_union) simp
   267 
   268 lemma union_mset_add_mset_left [simp]:
   269   "add_mset a A + B = add_mset a (A + B)"
   270   by (auto simp: multiset_eq_iff)
   271 
   272 lemma union_mset_add_mset_right [simp]:
   273   "A + add_mset a B = add_mset a (A + B)"
   274   by (auto simp: multiset_eq_iff)
   275 
   276 lemma add_mset_add_single: \<open>add_mset a A = A + {#a#}\<close>
   277   by (subst union_mset_add_mset_right, subst add.comm_neutral) standard
   278 
   279 
   280 subsubsection \<open>Difference\<close>
   281 
   282 instance multiset :: (type) comm_monoid_diff
   283   by standard (transfer; simp add: fun_eq_iff)
   284 
   285 lemma count_diff [simp]:
   286   "count (M - N) a = count M a - count N a"
   287   by (simp add: minus_multiset.rep_eq)
   288 
   289 lemma add_mset_diff_bothsides:
   290   \<open>add_mset a M - add_mset a A = M - A\<close>
   291   by (auto simp: multiset_eq_iff)
   292 
   293 lemma in_diff_count:
   294   "a \<in># M - N \<longleftrightarrow> count N a < count M a"
   295   by (simp add: set_mset_def)
   296 
   297 lemma count_in_diffI:
   298   assumes "\<And>n. count N x = n + count M x \<Longrightarrow> False"
   299   shows "x \<in># M - N"
   300 proof (rule ccontr)
   301   assume "x \<notin># M - N"
   302   then have "count N x = (count N x - count M x) + count M x"
   303     by (simp add: in_diff_count not_less)
   304   with assms show False by auto
   305 qed
   306 
   307 lemma in_diff_countE:
   308   assumes "x \<in># M - N"
   309   obtains n where "count M x = Suc n + count N x"
   310 proof -
   311   from assms have "count M x - count N x > 0" by (simp add: in_diff_count)
   312   then have "count M x > count N x" by simp
   313   then obtain n where "count M x = Suc n + count N x"
   314     using less_iff_Suc_add by auto
   315   with that show thesis .
   316 qed
   317 
   318 lemma in_diffD:
   319   assumes "a \<in># M - N"
   320   shows "a \<in># M"
   321 proof -
   322   have "0 \<le> count N a" by simp
   323   also from assms have "count N a < count M a"
   324     by (simp add: in_diff_count)
   325   finally show ?thesis by simp
   326 qed
   327 
   328 lemma set_mset_diff:
   329   "set_mset (M - N) = {a. count N a < count M a}"
   330   by (simp add: set_mset_def)
   331 
   332 lemma diff_empty [simp]: "M - {#} = M \<and> {#} - M = {#}"
   333   by rule (fact Groups.diff_zero, fact Groups.zero_diff)
   334 
   335 lemma diff_cancel: "A - A = {#}"
   336   by (fact Groups.diff_cancel)
   337 
   338 lemma diff_union_cancelR: "M + N - N = (M::'a multiset)"
   339   by (fact add_diff_cancel_right')
   340 
   341 lemma diff_union_cancelL: "N + M - N = (M::'a multiset)"
   342   by (fact add_diff_cancel_left')
   343 
   344 lemma diff_right_commute:
   345   fixes M N Q :: "'a multiset"
   346   shows "M - N - Q = M - Q - N"
   347   by (fact diff_right_commute)
   348 
   349 lemma diff_add:
   350   fixes M N Q :: "'a multiset"
   351   shows "M - (N + Q) = M - N - Q"
   352   by (rule sym) (fact diff_diff_add)
   353 
   354 lemma insert_DiffM [simp]: "x \<in># M \<Longrightarrow> add_mset x (M - {#x#}) = M"
   355   by (clarsimp simp: multiset_eq_iff)
   356 
   357 lemma insert_DiffM2: "x \<in># M \<Longrightarrow> (M - {#x#}) + {#x#} = M"
   358   by simp
   359 
   360 lemma diff_union_swap: "a \<noteq> b \<Longrightarrow> add_mset b (M - {#a#}) = add_mset b M - {#a#}"
   361   by (auto simp add: multiset_eq_iff)
   362 
   363 lemma diff_add_mset_swap [simp]: "b \<notin># A \<Longrightarrow> add_mset b M - A = add_mset b (M - A)"
   364   by (auto simp add: multiset_eq_iff simp: not_in_iff)
   365 
   366 lemma diff_union_swap2 [simp]: "y \<in># M \<Longrightarrow> add_mset x M - {#y#} = add_mset x (M - {#y#})"
   367   by (metis add_mset_diff_bothsides diff_union_swap diff_zero insert_DiffM)
   368 
   369 lemma diff_diff_add_mset [simp]: "(M::'a multiset) - N - P = M - (N + P)"
   370   by (rule diff_diff_add)
   371 
   372 lemma diff_union_single_conv:
   373   "a \<in># J \<Longrightarrow> I + J - {#a#} = I + (J - {#a#})"
   374   by (simp add: multiset_eq_iff Suc_le_eq)
   375 
   376 lemma mset_add [elim?]:
   377   assumes "a \<in># A"
   378   obtains B where "A = add_mset a B"
   379 proof -
   380   from assms have "A = add_mset a (A - {#a#})"
   381     by simp
   382   with that show thesis .
   383 qed
   384 
   385 lemma union_iff:
   386   "a \<in># A + B \<longleftrightarrow> a \<in># A \<or> a \<in># B"
   387   by auto
   388 
   389 
   390 subsubsection \<open>Min and Max\<close>
   391 
   392 abbreviation Min_mset :: "'a::linorder multiset \<Rightarrow> 'a" where
   393 "Min_mset m \<equiv> Min (set_mset m)"
   394 
   395 abbreviation Max_mset :: "'a::linorder multiset \<Rightarrow> 'a" where
   396 "Max_mset m \<equiv> Max (set_mset m)"
   397 
   398 
   399 subsubsection \<open>Equality of multisets\<close>
   400 
   401 lemma single_eq_single [simp]: "{#a#} = {#b#} \<longleftrightarrow> a = b"
   402   by (auto simp add: multiset_eq_iff)
   403 
   404 lemma union_eq_empty [iff]: "M + N = {#} \<longleftrightarrow> M = {#} \<and> N = {#}"
   405   by (auto simp add: multiset_eq_iff)
   406 
   407 lemma empty_eq_union [iff]: "{#} = M + N \<longleftrightarrow> M = {#} \<and> N = {#}"
   408   by (auto simp add: multiset_eq_iff)
   409 
   410 lemma multi_self_add_other_not_self [simp]: "M = add_mset x M \<longleftrightarrow> False"
   411   by (auto simp add: multiset_eq_iff)
   412 
   413 lemma add_mset_remove_trivial [simp]: \<open>add_mset x M - {#x#} = M\<close>
   414   by (auto simp: multiset_eq_iff)
   415 
   416 lemma diff_single_trivial: "\<not> x \<in># M \<Longrightarrow> M - {#x#} = M"
   417   by (auto simp add: multiset_eq_iff not_in_iff)
   418 
   419 lemma diff_single_eq_union: "x \<in># M \<Longrightarrow> M - {#x#} = N \<longleftrightarrow> M = add_mset x N"
   420   by auto
   421 
   422 lemma union_single_eq_diff: "add_mset x M = N \<Longrightarrow> M = N - {#x#}"
   423   unfolding add_mset_add_single[of _ M] by (fact add_implies_diff)
   424 
   425 lemma union_single_eq_member: "add_mset x M = N \<Longrightarrow> x \<in># N"
   426   by auto
   427 
   428 lemma add_mset_remove_trivial_If:
   429   "add_mset a (N - {#a#}) = (if a \<in># N then N else add_mset a N)"
   430   by (simp add: diff_single_trivial)
   431 
   432 lemma add_mset_remove_trivial_eq: \<open>N = add_mset a (N - {#a#}) \<longleftrightarrow> a \<in># N\<close>
   433   by (auto simp: add_mset_remove_trivial_If)
   434 
   435 lemma union_is_single:
   436   "M + N = {#a#} \<longleftrightarrow> M = {#a#} \<and> N = {#} \<or> M = {#} \<and> N = {#a#}"
   437   (is "?lhs = ?rhs")
   438 proof
   439   show ?lhs if ?rhs using that by auto
   440   show ?rhs if ?lhs
   441     by (metis Multiset.diff_cancel add.commute add_diff_cancel_left' diff_add_zero diff_single_trivial insert_DiffM that)
   442 qed
   443 
   444 lemma single_is_union: "{#a#} = M + N \<longleftrightarrow> {#a#} = M \<and> N = {#} \<or> M = {#} \<and> {#a#} = N"
   445   by (auto simp add: eq_commute [of "{#a#}" "M + N"] union_is_single)
   446 
   447 lemma add_eq_conv_diff:
   448   "add_mset a M = add_mset b N \<longleftrightarrow> M = N \<and> a = b \<or> M = add_mset b (N - {#a#}) \<and> N = add_mset a (M - {#b#})"
   449   (is "?lhs \<longleftrightarrow> ?rhs")
   450 (* shorter: by (simp add: multiset_eq_iff) fastforce *)
   451 proof
   452   show ?lhs if ?rhs
   453     using that
   454     by (auto simp add: add_mset_commute[of a b])
   455   show ?rhs if ?lhs
   456   proof (cases "a = b")
   457     case True with \<open>?lhs\<close> show ?thesis by simp
   458   next
   459     case False
   460     from \<open>?lhs\<close> have "a \<in># add_mset b N" by (rule union_single_eq_member)
   461     with False have "a \<in># N" by auto
   462     moreover from \<open>?lhs\<close> have "M = add_mset b N - {#a#}" by (rule union_single_eq_diff)
   463     moreover note False
   464     ultimately show ?thesis by (auto simp add: diff_right_commute [of _ "{#a#}"])
   465   qed
   466 qed
   467 
   468 lemma add_mset_eq_single [iff]: "add_mset b M = {#a#} \<longleftrightarrow> b = a \<and> M = {#}"
   469   by (auto simp: add_eq_conv_diff)
   470 
   471 lemma single_eq_add_mset [iff]: "{#a#} = add_mset b M \<longleftrightarrow> b = a \<and> M = {#}"
   472   by (auto simp: add_eq_conv_diff)
   473 
   474 lemma insert_noteq_member:
   475   assumes BC: "add_mset b B = add_mset c C"
   476    and bnotc: "b \<noteq> c"
   477   shows "c \<in># B"
   478 proof -
   479   have "c \<in># add_mset c C" by simp
   480   have nc: "\<not> c \<in># {#b#}" using bnotc by simp
   481   then have "c \<in># add_mset b B" using BC by simp
   482   then show "c \<in># B" using nc by simp
   483 qed
   484 
   485 lemma add_eq_conv_ex:
   486   "(add_mset a M = add_mset b N) =
   487     (M = N \<and> a = b \<or> (\<exists>K. M = add_mset b K \<and> N = add_mset a K))"
   488   by (auto simp add: add_eq_conv_diff)
   489 
   490 lemma multi_member_split: "x \<in># M \<Longrightarrow> \<exists>A. M = add_mset x A"
   491   by (rule exI [where x = "M - {#x#}"]) simp
   492 
   493 lemma multiset_add_sub_el_shuffle:
   494   assumes "c \<in># B"
   495     and "b \<noteq> c"
   496   shows "add_mset b (B - {#c#}) = add_mset b B - {#c#}"
   497 proof -
   498   from \<open>c \<in># B\<close> obtain A where B: "B = add_mset c A"
   499     by (blast dest: multi_member_split)
   500   have "add_mset b A = add_mset c (add_mset b A) - {#c#}" by simp
   501   then have "add_mset b A = add_mset b (add_mset c A) - {#c#}"
   502     by (simp add: \<open>b \<noteq> c\<close>)
   503   then show ?thesis using B by simp
   504 qed
   505 
   506 lemma add_mset_eq_singleton_iff[iff]:
   507   "add_mset x M = {#y#} \<longleftrightarrow> M = {#} \<and> x = y"
   508   by auto
   509 
   510 
   511 subsubsection \<open>Pointwise ordering induced by count\<close>
   512 
   513 definition subseteq_mset :: "'a multiset \<Rightarrow> 'a multiset \<Rightarrow> bool"  (infix "\<subseteq>#" 50)
   514   where "A \<subseteq># B \<longleftrightarrow> (\<forall>a. count A a \<le> count B a)"
   515 
   516 definition subset_mset :: "'a multiset \<Rightarrow> 'a multiset \<Rightarrow> bool" (infix "\<subset>#" 50)
   517   where "A \<subset># B \<longleftrightarrow> A \<subseteq># B \<and> A \<noteq> B"
   518 
   519 abbreviation (input) supseteq_mset :: "'a multiset \<Rightarrow> 'a multiset \<Rightarrow> bool"  (infix "\<supseteq>#" 50)
   520   where "supseteq_mset A B \<equiv> B \<subseteq># A"
   521 
   522 abbreviation (input) supset_mset :: "'a multiset \<Rightarrow> 'a multiset \<Rightarrow> bool"  (infix "\<supset>#" 50)
   523   where "supset_mset A B \<equiv> B \<subset># A"
   524 
   525 notation (input)
   526   subseteq_mset  (infix "\<le>#" 50) and
   527   supseteq_mset  (infix "\<ge>#" 50)
   528 
   529 notation (ASCII)
   530   subseteq_mset  (infix "<=#" 50) and
   531   subset_mset  (infix "<#" 50) and
   532   supseteq_mset  (infix ">=#" 50) and
   533   supset_mset  (infix ">#" 50)
   534 
   535 interpretation subset_mset: ordered_ab_semigroup_add_imp_le "(+)" "(-)" "(\<subseteq>#)" "(\<subset>#)"
   536   by standard (auto simp add: subset_mset_def subseteq_mset_def multiset_eq_iff intro: order_trans antisym)
   537     \<comment> \<open>FIXME: avoid junk stemming from type class interpretation\<close>
   538 
   539 interpretation subset_mset: ordered_ab_semigroup_monoid_add_imp_le "(+)" 0 "(-)" "(\<subseteq>#)" "(\<subset>#)"
   540   by standard
   541     \<comment> \<open>FIXME: avoid junk stemming from type class interpretation\<close>
   542 
   543 lemma mset_subset_eqI:
   544   "(\<And>a. count A a \<le> count B a) \<Longrightarrow> A \<subseteq># B"
   545   by (simp add: subseteq_mset_def)
   546 
   547 lemma mset_subset_eq_count:
   548   "A \<subseteq># B \<Longrightarrow> count A a \<le> count B a"
   549   by (simp add: subseteq_mset_def)
   550 
   551 lemma mset_subset_eq_exists_conv: "(A::'a multiset) \<subseteq># B \<longleftrightarrow> (\<exists>C. B = A + C)"
   552   unfolding subseteq_mset_def
   553   apply (rule iffI)
   554    apply (rule exI [where x = "B - A"])
   555    apply (auto intro: multiset_eq_iff [THEN iffD2])
   556   done
   557 
   558 interpretation subset_mset: ordered_cancel_comm_monoid_diff "(+)" 0 "(\<subseteq>#)" "(\<subset>#)" "(-)"
   559   by standard (simp, fact mset_subset_eq_exists_conv)
   560     \<comment> \<open>FIXME: avoid junk stemming from type class interpretation\<close>
   561 
   562 declare subset_mset.add_diff_assoc[simp] subset_mset.add_diff_assoc2[simp]
   563 
   564 lemma mset_subset_eq_mono_add_right_cancel: "(A::'a multiset) + C \<subseteq># B + C \<longleftrightarrow> A \<subseteq># B"
   565    by (fact subset_mset.add_le_cancel_right)
   566 
   567 lemma mset_subset_eq_mono_add_left_cancel: "C + (A::'a multiset) \<subseteq># C + B \<longleftrightarrow> A \<subseteq># B"
   568    by (fact subset_mset.add_le_cancel_left)
   569 
   570 lemma mset_subset_eq_mono_add: "(A::'a multiset) \<subseteq># B \<Longrightarrow> C \<subseteq># D \<Longrightarrow> A + C \<subseteq># B + D"
   571    by (fact subset_mset.add_mono)
   572 
   573 lemma mset_subset_eq_add_left: "(A::'a multiset) \<subseteq># A + B"
   574    by simp
   575 
   576 lemma mset_subset_eq_add_right: "B \<subseteq># (A::'a multiset) + B"
   577    by simp
   578 
   579 lemma single_subset_iff [simp]:
   580   "{#a#} \<subseteq># M \<longleftrightarrow> a \<in># M"
   581   by (auto simp add: subseteq_mset_def Suc_le_eq)
   582 
   583 lemma mset_subset_eq_single: "a \<in># B \<Longrightarrow> {#a#} \<subseteq># B"
   584   by simp
   585 
   586 lemma mset_subset_eq_add_mset_cancel: \<open>add_mset a A \<subseteq># add_mset a B \<longleftrightarrow> A \<subseteq># B\<close>
   587   unfolding add_mset_add_single[of _ A] add_mset_add_single[of _ B]
   588   by (rule mset_subset_eq_mono_add_right_cancel)
   589 
   590 lemma multiset_diff_union_assoc:
   591   fixes A B C D :: "'a multiset"
   592   shows "C \<subseteq># B \<Longrightarrow> A + B - C = A + (B - C)"
   593   by (fact subset_mset.diff_add_assoc)
   594 
   595 lemma mset_subset_eq_multiset_union_diff_commute:
   596   fixes A B C D :: "'a multiset"
   597   shows "B \<subseteq># A \<Longrightarrow> A - B + C = A + C - B"
   598   by (fact subset_mset.add_diff_assoc2)
   599 
   600 lemma diff_subset_eq_self[simp]:
   601   "(M::'a multiset) - N \<subseteq># M"
   602   by (simp add: subseteq_mset_def)
   603 
   604 lemma mset_subset_eqD:
   605   assumes "A \<subseteq># B" and "x \<in># A"
   606   shows "x \<in># B"
   607 proof -
   608   from \<open>x \<in># A\<close> have "count A x > 0" by simp
   609   also from \<open>A \<subseteq># B\<close> have "count A x \<le> count B x"
   610     by (simp add: subseteq_mset_def)
   611   finally show ?thesis by simp
   612 qed
   613 
   614 lemma mset_subsetD:
   615   "A \<subset># B \<Longrightarrow> x \<in># A \<Longrightarrow> x \<in># B"
   616   by (auto intro: mset_subset_eqD [of A])
   617 
   618 lemma set_mset_mono:
   619   "A \<subseteq># B \<Longrightarrow> set_mset A \<subseteq> set_mset B"
   620   by (metis mset_subset_eqD subsetI)
   621 
   622 lemma mset_subset_eq_insertD:
   623   "add_mset x A \<subseteq># B \<Longrightarrow> x \<in># B \<and> A \<subset># B"
   624 apply (rule conjI)
   625  apply (simp add: mset_subset_eqD)
   626  apply (clarsimp simp: subset_mset_def subseteq_mset_def)
   627  apply safe
   628   apply (erule_tac x = a in allE)
   629   apply (auto split: if_split_asm)
   630 done
   631 
   632 lemma mset_subset_insertD:
   633   "add_mset x A \<subset># B \<Longrightarrow> x \<in># B \<and> A \<subset># B"
   634   by (rule mset_subset_eq_insertD) simp
   635 
   636 lemma mset_subset_of_empty[simp]: "A \<subset># {#} \<longleftrightarrow> False"
   637   by (simp only: subset_mset.not_less_zero)
   638 
   639 lemma empty_subset_add_mset[simp]: "{#} \<subset># add_mset x M"
   640   by (auto intro: subset_mset.gr_zeroI)
   641 
   642 lemma empty_le: "{#} \<subseteq># A"
   643   by (fact subset_mset.zero_le)
   644 
   645 lemma insert_subset_eq_iff:
   646   "add_mset a A \<subseteq># B \<longleftrightarrow> a \<in># B \<and> A \<subseteq># B - {#a#}"
   647   using le_diff_conv2 [of "Suc 0" "count B a" "count A a"]
   648   apply (auto simp add: subseteq_mset_def not_in_iff Suc_le_eq)
   649   apply (rule ccontr)
   650   apply (auto simp add: not_in_iff)
   651   done
   652 
   653 lemma insert_union_subset_iff:
   654   "add_mset a A \<subset># B \<longleftrightarrow> a \<in># B \<and> A \<subset># B - {#a#}"
   655   by (auto simp add: insert_subset_eq_iff subset_mset_def)
   656 
   657 lemma subset_eq_diff_conv:
   658   "A - C \<subseteq># B \<longleftrightarrow> A \<subseteq># B + C"
   659   by (simp add: subseteq_mset_def le_diff_conv)
   660 
   661 lemma multi_psub_of_add_self [simp]: "A \<subset># add_mset x A"
   662   by (auto simp: subset_mset_def subseteq_mset_def)
   663 
   664 lemma multi_psub_self: "A \<subset># A = False"
   665   by simp
   666 
   667 lemma mset_subset_add_mset [simp]: "add_mset x N \<subset># add_mset x M \<longleftrightarrow> N \<subset># M"
   668   unfolding add_mset_add_single[of _ N] add_mset_add_single[of _ M]
   669   by (fact subset_mset.add_less_cancel_right)
   670 
   671 lemma mset_subset_diff_self: "c \<in># B \<Longrightarrow> B - {#c#} \<subset># B"
   672   by (auto simp: subset_mset_def elim: mset_add)
   673 
   674 lemma Diff_eq_empty_iff_mset: "A - B = {#} \<longleftrightarrow> A \<subseteq># B"
   675   by (auto simp: multiset_eq_iff subseteq_mset_def)
   676 
   677 lemma add_mset_subseteq_single_iff[iff]: "add_mset a M \<subseteq># {#b#} \<longleftrightarrow> M = {#} \<and> a = b"
   678 proof
   679   assume A: "add_mset a M \<subseteq># {#b#}"
   680   then have \<open>a = b\<close>
   681     by (auto dest: mset_subset_eq_insertD)
   682   then show "M={#} \<and> a=b"
   683     using A by (simp add: mset_subset_eq_add_mset_cancel)
   684 qed simp
   685 
   686 
   687 subsubsection \<open>Intersection and bounded union\<close>
   688 
   689 definition inf_subset_mset :: "'a multiset \<Rightarrow> 'a multiset \<Rightarrow> 'a multiset" (infixl "\<inter>#" 70) where
   690   multiset_inter_def: "inf_subset_mset A B = A - (A - B)"
   691 
   692 interpretation subset_mset: semilattice_inf inf_subset_mset "(\<subseteq>#)" "(\<subset>#)"
   693 proof -
   694   have [simp]: "m \<le> n \<Longrightarrow> m \<le> q \<Longrightarrow> m \<le> n - (n - q)" for m n q :: nat
   695     by arith
   696   show "class.semilattice_inf (\<inter>#) (\<subseteq>#) (\<subset>#)"
   697     by standard (auto simp add: multiset_inter_def subseteq_mset_def)
   698 qed \<comment> \<open>FIXME: avoid junk stemming from type class interpretation\<close>
   699 
   700 definition sup_subset_mset :: "'a multiset \<Rightarrow> 'a multiset \<Rightarrow> 'a multiset"(infixl "\<union>#" 70)
   701   where "sup_subset_mset A B = A + (B - A)" \<comment> \<open>FIXME irregular fact name\<close>
   702 
   703 interpretation subset_mset: semilattice_sup sup_subset_mset "(\<subseteq>#)" "(\<subset>#)"
   704 proof -
   705   have [simp]: "m \<le> n \<Longrightarrow> q \<le> n \<Longrightarrow> m + (q - m) \<le> n" for m n q :: nat
   706     by arith
   707   show "class.semilattice_sup (\<union>#) (\<subseteq>#) (\<subset>#)"
   708     by standard (auto simp add: sup_subset_mset_def subseteq_mset_def)
   709 qed \<comment> \<open>FIXME: avoid junk stemming from type class interpretation\<close>
   710 
   711 interpretation subset_mset: bounded_lattice_bot "(\<inter>#)" "(\<subseteq>#)" "(\<subset>#)"
   712   "(\<union>#)" "{#}"
   713   by standard auto
   714     \<comment> \<open>FIXME: avoid junk stemming from type class interpretation\<close>
   715 
   716 
   717 subsubsection \<open>Additional intersection facts\<close>
   718 
   719 lemma multiset_inter_count [simp]:
   720   fixes A B :: "'a multiset"
   721   shows "count (A \<inter># B) x = min (count A x) (count B x)"
   722   by (simp add: multiset_inter_def)
   723 
   724 lemma set_mset_inter [simp]:
   725   "set_mset (A \<inter># B) = set_mset A \<inter> set_mset B"
   726   by (simp only: set_eq_iff count_greater_zero_iff [symmetric] multiset_inter_count) simp
   727 
   728 lemma diff_intersect_left_idem [simp]:
   729   "M - M \<inter># N = M - N"
   730   by (simp add: multiset_eq_iff min_def)
   731 
   732 lemma diff_intersect_right_idem [simp]:
   733   "M - N \<inter># M = M - N"
   734   by (simp add: multiset_eq_iff min_def)
   735 
   736 lemma multiset_inter_single[simp]: "a \<noteq> b \<Longrightarrow> {#a#} \<inter># {#b#} = {#}"
   737   by (rule multiset_eqI) auto
   738 
   739 lemma multiset_union_diff_commute:
   740   assumes "B \<inter># C = {#}"
   741   shows "A + B - C = A - C + B"
   742 proof (rule multiset_eqI)
   743   fix x
   744   from assms have "min (count B x) (count C x) = 0"
   745     by (auto simp add: multiset_eq_iff)
   746   then have "count B x = 0 \<or> count C x = 0"
   747     unfolding min_def by (auto split: if_splits)
   748   then show "count (A + B - C) x = count (A - C + B) x"
   749     by auto
   750 qed
   751 
   752 lemma disjunct_not_in:
   753   "A \<inter># B = {#} \<longleftrightarrow> (\<forall>a. a \<notin># A \<or> a \<notin># B)" (is "?P \<longleftrightarrow> ?Q")
   754 proof
   755   assume ?P
   756   show ?Q
   757   proof
   758     fix a
   759     from \<open>?P\<close> have "min (count A a) (count B a) = 0"
   760       by (simp add: multiset_eq_iff)
   761     then have "count A a = 0 \<or> count B a = 0"
   762       by (cases "count A a \<le> count B a") (simp_all add: min_def)
   763     then show "a \<notin># A \<or> a \<notin># B"
   764       by (simp add: not_in_iff)
   765   qed
   766 next
   767   assume ?Q
   768   show ?P
   769   proof (rule multiset_eqI)
   770     fix a
   771     from \<open>?Q\<close> have "count A a = 0 \<or> count B a = 0"
   772       by (auto simp add: not_in_iff)
   773     then show "count (A \<inter># B) a = count {#} a"
   774       by auto
   775   qed
   776 qed
   777 
   778 lemma inter_mset_empty_distrib_right: "A \<inter># (B + C) = {#} \<longleftrightarrow> A \<inter># B = {#} \<and> A \<inter># C = {#}"
   779   by (meson disjunct_not_in union_iff)
   780 
   781 lemma inter_mset_empty_distrib_left: "(A + B) \<inter># C = {#} \<longleftrightarrow> A \<inter># C = {#} \<and> B \<inter># C = {#}"
   782   by (meson disjunct_not_in union_iff)
   783 
   784 lemma add_mset_inter_add_mset[simp]:
   785   "add_mset a A \<inter># add_mset a B = add_mset a (A \<inter># B)"
   786   by (metis add_mset_add_single add_mset_diff_bothsides diff_subset_eq_self multiset_inter_def
   787       subset_mset.diff_add_assoc2)
   788 
   789 lemma add_mset_disjoint [simp]:
   790   "add_mset a A \<inter># B = {#} \<longleftrightarrow> a \<notin># B \<and> A \<inter># B = {#}"
   791   "{#} = add_mset a A \<inter># B \<longleftrightarrow> a \<notin># B \<and> {#} = A \<inter># B"
   792   by (auto simp: disjunct_not_in)
   793 
   794 lemma disjoint_add_mset [simp]:
   795   "B \<inter># add_mset a A = {#} \<longleftrightarrow> a \<notin># B \<and> B \<inter># A = {#}"
   796   "{#} = A \<inter># add_mset b B \<longleftrightarrow> b \<notin># A \<and> {#} = A \<inter># B"
   797   by (auto simp: disjunct_not_in)
   798 
   799 lemma inter_add_left1: "\<not> x \<in># N \<Longrightarrow> (add_mset x M) \<inter># N = M \<inter># N"
   800   by (simp add: multiset_eq_iff not_in_iff)
   801 
   802 lemma inter_add_left2: "x \<in># N \<Longrightarrow> (add_mset x M) \<inter># N = add_mset x (M \<inter># (N - {#x#}))"
   803   by (auto simp add: multiset_eq_iff elim: mset_add)
   804 
   805 lemma inter_add_right1: "\<not> x \<in># N \<Longrightarrow> N \<inter># (add_mset x M) = N \<inter># M"
   806   by (simp add: multiset_eq_iff not_in_iff)
   807 
   808 lemma inter_add_right2: "x \<in># N \<Longrightarrow> N \<inter># (add_mset x M) = add_mset x ((N - {#x#}) \<inter># M)"
   809   by (auto simp add: multiset_eq_iff elim: mset_add)
   810 
   811 lemma disjunct_set_mset_diff:
   812   assumes "M \<inter># N = {#}"
   813   shows "set_mset (M - N) = set_mset M"
   814 proof (rule set_eqI)
   815   fix a
   816   from assms have "a \<notin># M \<or> a \<notin># N"
   817     by (simp add: disjunct_not_in)
   818   then show "a \<in># M - N \<longleftrightarrow> a \<in># M"
   819     by (auto dest: in_diffD) (simp add: in_diff_count not_in_iff)
   820 qed
   821 
   822 lemma at_most_one_mset_mset_diff:
   823   assumes "a \<notin># M - {#a#}"
   824   shows "set_mset (M - {#a#}) = set_mset M - {a}"
   825   using assms by (auto simp add: not_in_iff in_diff_count set_eq_iff)
   826 
   827 lemma more_than_one_mset_mset_diff:
   828   assumes "a \<in># M - {#a#}"
   829   shows "set_mset (M - {#a#}) = set_mset M"
   830 proof (rule set_eqI)
   831   fix b
   832   have "Suc 0 < count M b \<Longrightarrow> count M b > 0" by arith
   833   then show "b \<in># M - {#a#} \<longleftrightarrow> b \<in># M"
   834     using assms by (auto simp add: in_diff_count)
   835 qed
   836 
   837 lemma inter_iff:
   838   "a \<in># A \<inter># B \<longleftrightarrow> a \<in># A \<and> a \<in># B"
   839   by simp
   840 
   841 lemma inter_union_distrib_left:
   842   "A \<inter># B + C = (A + C) \<inter># (B + C)"
   843   by (simp add: multiset_eq_iff min_add_distrib_left)
   844 
   845 lemma inter_union_distrib_right:
   846   "C + A \<inter># B = (C + A) \<inter># (C + B)"
   847   using inter_union_distrib_left [of A B C] by (simp add: ac_simps)
   848 
   849 lemma inter_subset_eq_union:
   850   "A \<inter># B \<subseteq># A + B"
   851   by (auto simp add: subseteq_mset_def)
   852 
   853 
   854 subsubsection \<open>Additional bounded union facts\<close>
   855 
   856 lemma sup_subset_mset_count [simp]: \<comment> \<open>FIXME irregular fact name\<close>
   857   "count (A \<union># B) x = max (count A x) (count B x)"
   858   by (simp add: sup_subset_mset_def)
   859 
   860 lemma set_mset_sup [simp]:
   861   "set_mset (A \<union># B) = set_mset A \<union> set_mset B"
   862   by (simp only: set_eq_iff count_greater_zero_iff [symmetric] sup_subset_mset_count)
   863     (auto simp add: not_in_iff elim: mset_add)
   864 
   865 lemma sup_union_left1 [simp]: "\<not> x \<in># N \<Longrightarrow> (add_mset x M) \<union># N = add_mset x (M \<union># N)"
   866   by (simp add: multiset_eq_iff not_in_iff)
   867 
   868 lemma sup_union_left2: "x \<in># N \<Longrightarrow> (add_mset x M) \<union># N = add_mset x (M \<union># (N - {#x#}))"
   869   by (simp add: multiset_eq_iff)
   870 
   871 lemma sup_union_right1 [simp]: "\<not> x \<in># N \<Longrightarrow> N \<union># (add_mset x M) = add_mset x (N \<union># M)"
   872   by (simp add: multiset_eq_iff not_in_iff)
   873 
   874 lemma sup_union_right2: "x \<in># N \<Longrightarrow> N \<union># (add_mset x M) = add_mset x ((N - {#x#}) \<union># M)"
   875   by (simp add: multiset_eq_iff)
   876 
   877 lemma sup_union_distrib_left:
   878   "A \<union># B + C = (A + C) \<union># (B + C)"
   879   by (simp add: multiset_eq_iff max_add_distrib_left)
   880 
   881 lemma union_sup_distrib_right:
   882   "C + A \<union># B = (C + A) \<union># (C + B)"
   883   using sup_union_distrib_left [of A B C] by (simp add: ac_simps)
   884 
   885 lemma union_diff_inter_eq_sup:
   886   "A + B - A \<inter># B = A \<union># B"
   887   by (auto simp add: multiset_eq_iff)
   888 
   889 lemma union_diff_sup_eq_inter:
   890   "A + B - A \<union># B = A \<inter># B"
   891   by (auto simp add: multiset_eq_iff)
   892 
   893 lemma add_mset_union:
   894   \<open>add_mset a A \<union># add_mset a B = add_mset a (A \<union># B)\<close>
   895   by (auto simp: multiset_eq_iff max_def)
   896 
   897 
   898 subsection \<open>Replicate and repeat operations\<close>
   899 
   900 definition replicate_mset :: "nat \<Rightarrow> 'a \<Rightarrow> 'a multiset" where
   901   "replicate_mset n x = (add_mset x ^^ n) {#}"
   902 
   903 lemma replicate_mset_0[simp]: "replicate_mset 0 x = {#}"
   904   unfolding replicate_mset_def by simp
   905 
   906 lemma replicate_mset_Suc [simp]: "replicate_mset (Suc n) x = add_mset x (replicate_mset n x)"
   907   unfolding replicate_mset_def by (induct n) (auto intro: add.commute)
   908 
   909 lemma count_replicate_mset[simp]: "count (replicate_mset n x) y = (if y = x then n else 0)"
   910   unfolding replicate_mset_def by (induct n) auto
   911 
   912 fun repeat_mset :: "nat \<Rightarrow> 'a multiset \<Rightarrow> 'a multiset" where
   913   "repeat_mset 0 _ = {#}" |
   914   "repeat_mset (Suc n) A = A + repeat_mset n A"
   915 
   916 lemma count_repeat_mset [simp]: "count (repeat_mset i A) a = i * count A a"
   917   by (induction i) auto
   918 
   919 lemma repeat_mset_right [simp]: "repeat_mset a (repeat_mset b A) = repeat_mset (a * b) A"
   920   by (auto simp: multiset_eq_iff left_diff_distrib')
   921 
   922 lemma left_diff_repeat_mset_distrib': \<open>repeat_mset (i - j) u = repeat_mset i u - repeat_mset j u\<close>
   923   by (auto simp: multiset_eq_iff left_diff_distrib')
   924 
   925 lemma left_add_mult_distrib_mset:
   926   "repeat_mset i u + (repeat_mset j u + k) = repeat_mset (i+j) u + k"
   927   by (auto simp: multiset_eq_iff add_mult_distrib)
   928 
   929 lemma repeat_mset_distrib:
   930   "repeat_mset (m + n) A = repeat_mset m A + repeat_mset n A"
   931   by (auto simp: multiset_eq_iff Nat.add_mult_distrib)
   932 
   933 lemma repeat_mset_distrib2[simp]:
   934   "repeat_mset n (A + B) = repeat_mset n A + repeat_mset n B"
   935   by (auto simp: multiset_eq_iff add_mult_distrib2)
   936 
   937 lemma repeat_mset_replicate_mset[simp]:
   938   "repeat_mset n {#a#} = replicate_mset n a"
   939   by (auto simp: multiset_eq_iff)
   940 
   941 lemma repeat_mset_distrib_add_mset[simp]:
   942   "repeat_mset n (add_mset a A) = replicate_mset n a + repeat_mset n A"
   943   by (auto simp: multiset_eq_iff)
   944 
   945 lemma repeat_mset_empty[simp]: "repeat_mset n {#} = {#}"
   946   by (induction n) simp_all
   947 
   948 
   949 subsubsection \<open>Simprocs\<close>
   950 
   951 lemma repeat_mset_iterate_add: \<open>repeat_mset n M = iterate_add n M\<close>
   952   unfolding iterate_add_def by (induction n) auto
   953 
   954 lemma mset_subseteq_add_iff1:
   955   "j \<le> (i::nat) \<Longrightarrow> (repeat_mset i u + m \<subseteq># repeat_mset j u + n) = (repeat_mset (i-j) u + m \<subseteq># n)"
   956   by (auto simp add: subseteq_mset_def nat_le_add_iff1)
   957 
   958 lemma mset_subseteq_add_iff2:
   959   "i \<le> (j::nat) \<Longrightarrow> (repeat_mset i u + m \<subseteq># repeat_mset j u + n) = (m \<subseteq># repeat_mset (j-i) u + n)"
   960   by (auto simp add: subseteq_mset_def nat_le_add_iff2)
   961 
   962 lemma mset_subset_add_iff1:
   963   "j \<le> (i::nat) \<Longrightarrow> (repeat_mset i u + m \<subset># repeat_mset j u + n) = (repeat_mset (i-j) u + m \<subset># n)"
   964   unfolding subset_mset_def repeat_mset_iterate_add
   965   by (simp add: iterate_add_eq_add_iff1 mset_subseteq_add_iff1[unfolded repeat_mset_iterate_add])
   966 
   967 lemma mset_subset_add_iff2:
   968   "i \<le> (j::nat) \<Longrightarrow> (repeat_mset i u + m \<subset># repeat_mset j u + n) = (m \<subset># repeat_mset (j-i) u + n)"
   969   unfolding subset_mset_def repeat_mset_iterate_add
   970   by (simp add: iterate_add_eq_add_iff2 mset_subseteq_add_iff2[unfolded repeat_mset_iterate_add])
   971 
   972 ML_file \<open>multiset_simprocs.ML\<close>
   973 
   974 lemma add_mset_replicate_mset_safe[cancelation_simproc_pre]: \<open>NO_MATCH {#} M \<Longrightarrow> add_mset a M = {#a#} + M\<close>
   975   by simp
   976 
   977 declare repeat_mset_iterate_add[cancelation_simproc_pre]
   978 
   979 declare iterate_add_distrib[cancelation_simproc_pre]
   980 declare repeat_mset_iterate_add[symmetric, cancelation_simproc_post]
   981 
   982 declare add_mset_not_empty[cancelation_simproc_eq_elim]
   983     empty_not_add_mset[cancelation_simproc_eq_elim]
   984     subset_mset.le_zero_eq[cancelation_simproc_eq_elim]
   985     empty_not_add_mset[cancelation_simproc_eq_elim]
   986     add_mset_not_empty[cancelation_simproc_eq_elim]
   987     subset_mset.le_zero_eq[cancelation_simproc_eq_elim]
   988     le_zero_eq[cancelation_simproc_eq_elim]
   989 
   990 simproc_setup mseteq_cancel
   991   ("(l::'a multiset) + m = n" | "(l::'a multiset) = m + n" |
   992    "add_mset a m = n" | "m = add_mset a n" |
   993    "replicate_mset p a = n" | "m = replicate_mset p a" |
   994    "repeat_mset p m = n" | "m = repeat_mset p m") =
   995   \<open>fn phi => Cancel_Simprocs.eq_cancel\<close>
   996 
   997 simproc_setup msetsubset_cancel
   998   ("(l::'a multiset) + m \<subset># n" | "(l::'a multiset) \<subset># m + n" |
   999    "add_mset a m \<subset># n" | "m \<subset># add_mset a n" |
  1000    "replicate_mset p r \<subset># n" | "m \<subset># replicate_mset p r" |
  1001    "repeat_mset p m \<subset># n" | "m \<subset># repeat_mset p m") =
  1002   \<open>fn phi => Multiset_Simprocs.subset_cancel_msets\<close>
  1003 
  1004 simproc_setup msetsubset_eq_cancel
  1005   ("(l::'a multiset) + m \<subseteq># n" | "(l::'a multiset) \<subseteq># m + n" |
  1006    "add_mset a m \<subseteq># n" | "m \<subseteq># add_mset a n" |
  1007    "replicate_mset p r \<subseteq># n" | "m \<subseteq># replicate_mset p r" |
  1008    "repeat_mset p m \<subseteq># n" | "m \<subseteq># repeat_mset p m") =
  1009   \<open>fn phi => Multiset_Simprocs.subseteq_cancel_msets\<close>
  1010 
  1011 simproc_setup msetdiff_cancel
  1012   ("((l::'a multiset) + m) - n" | "(l::'a multiset) - (m + n)" |
  1013    "add_mset a m - n" | "m - add_mset a n" |
  1014    "replicate_mset p r - n" | "m - replicate_mset p r" |
  1015    "repeat_mset p m - n" | "m - repeat_mset p m") =
  1016   \<open>fn phi => Cancel_Simprocs.diff_cancel\<close>
  1017 
  1018 
  1019 subsubsection \<open>Conditionally complete lattice\<close>
  1020 
  1021 instantiation multiset :: (type) Inf
  1022 begin
  1023 
  1024 lift_definition Inf_multiset :: "'a multiset set \<Rightarrow> 'a multiset" is
  1025   "\<lambda>A i. if A = {} then 0 else Inf ((\<lambda>f. f i) ` A)"
  1026 proof -
  1027   fix A :: "('a \<Rightarrow> nat) set" assume *: "\<And>x. x \<in> A \<Longrightarrow> x \<in> multiset"
  1028   have "finite {i. (if A = {} then 0 else Inf ((\<lambda>f. f i) ` A)) > 0}" unfolding multiset_def
  1029   proof (cases "A = {}")
  1030     case False
  1031     then obtain f where "f \<in> A" by blast
  1032     hence "{i. Inf ((\<lambda>f. f i) ` A) > 0} \<subseteq> {i. f i > 0}"
  1033       by (auto intro: less_le_trans[OF _ cInf_lower])
  1034     moreover from \<open>f \<in> A\<close> * have "finite \<dots>" by (simp add: multiset_def)
  1035     ultimately have "finite {i. Inf ((\<lambda>f. f i) ` A) > 0}" by (rule finite_subset)
  1036     with False show ?thesis by simp
  1037   qed simp_all
  1038   thus "(\<lambda>i. if A = {} then 0 else INF f\<in>A. f i) \<in> multiset" by (simp add: multiset_def)
  1039 qed
  1040 
  1041 instance ..
  1042 
  1043 end
  1044 
  1045 lemma Inf_multiset_empty: "Inf {} = {#}"
  1046   by transfer simp_all
  1047 
  1048 lemma count_Inf_multiset_nonempty: "A \<noteq> {} \<Longrightarrow> count (Inf A) x = Inf ((\<lambda>X. count X x) ` A)"
  1049   by transfer simp_all
  1050 
  1051 
  1052 instantiation multiset :: (type) Sup
  1053 begin
  1054 
  1055 definition Sup_multiset :: "'a multiset set \<Rightarrow> 'a multiset" where
  1056   "Sup_multiset A = (if A \<noteq> {} \<and> subset_mset.bdd_above A then
  1057            Abs_multiset (\<lambda>i. Sup ((\<lambda>X. count X i) ` A)) else {#})"
  1058 
  1059 lemma Sup_multiset_empty: "Sup {} = {#}"
  1060   by (simp add: Sup_multiset_def)
  1061 
  1062 lemma Sup_multiset_unbounded: "\<not>subset_mset.bdd_above A \<Longrightarrow> Sup A = {#}"
  1063   by (simp add: Sup_multiset_def)
  1064 
  1065 instance ..
  1066 
  1067 end
  1068 
  1069 
  1070 lemma bdd_above_multiset_imp_bdd_above_count:
  1071   assumes "subset_mset.bdd_above (A :: 'a multiset set)"
  1072   shows   "bdd_above ((\<lambda>X. count X x) ` A)"
  1073 proof -
  1074   from assms obtain Y where Y: "\<forall>X\<in>A. X \<subseteq># Y"
  1075     by (auto simp: subset_mset.bdd_above_def)
  1076   hence "count X x \<le> count Y x" if "X \<in> A" for X
  1077     using that by (auto intro: mset_subset_eq_count)
  1078   thus ?thesis by (intro bdd_aboveI[of _ "count Y x"]) auto
  1079 qed
  1080 
  1081 lemma bdd_above_multiset_imp_finite_support:
  1082   assumes "A \<noteq> {}" "subset_mset.bdd_above (A :: 'a multiset set)"
  1083   shows   "finite (\<Union>X\<in>A. {x. count X x > 0})"
  1084 proof -
  1085   from assms obtain Y where Y: "\<forall>X\<in>A. X \<subseteq># Y"
  1086     by (auto simp: subset_mset.bdd_above_def)
  1087   hence "count X x \<le> count Y x" if "X \<in> A" for X x
  1088     using that by (auto intro: mset_subset_eq_count)
  1089   hence "(\<Union>X\<in>A. {x. count X x > 0}) \<subseteq> {x. count Y x > 0}"
  1090     by safe (erule less_le_trans)
  1091   moreover have "finite \<dots>" by simp
  1092   ultimately show ?thesis by (rule finite_subset)
  1093 qed
  1094 
  1095 lemma Sup_multiset_in_multiset:
  1096   assumes "A \<noteq> {}" "subset_mset.bdd_above A"
  1097   shows   "(\<lambda>i. SUP X\<in>A. count X i) \<in> multiset"
  1098   unfolding multiset_def
  1099 proof
  1100   have "{i. Sup ((\<lambda>X. count X i) ` A) > 0} \<subseteq> (\<Union>X\<in>A. {i. 0 < count X i})"
  1101   proof safe
  1102     fix i assume pos: "(SUP X\<in>A. count X i) > 0"
  1103     show "i \<in> (\<Union>X\<in>A. {i. 0 < count X i})"
  1104     proof (rule ccontr)
  1105       assume "i \<notin> (\<Union>X\<in>A. {i. 0 < count X i})"
  1106       hence "\<forall>X\<in>A. count X i \<le> 0" by (auto simp: count_eq_zero_iff)
  1107       with assms have "(SUP X\<in>A. count X i) \<le> 0"
  1108         by (intro cSup_least bdd_above_multiset_imp_bdd_above_count) auto
  1109       with pos show False by simp
  1110     qed
  1111   qed
  1112   moreover from assms have "finite \<dots>" by (rule bdd_above_multiset_imp_finite_support)
  1113   ultimately show "finite {i. Sup ((\<lambda>X. count X i) ` A) > 0}" by (rule finite_subset)
  1114 qed
  1115 
  1116 lemma count_Sup_multiset_nonempty:
  1117   assumes "A \<noteq> {}" "subset_mset.bdd_above A"
  1118   shows   "count (Sup A) x = (SUP X\<in>A. count X x)"
  1119   using assms by (simp add: Sup_multiset_def Abs_multiset_inverse Sup_multiset_in_multiset)
  1120 
  1121 
  1122 interpretation subset_mset: conditionally_complete_lattice Inf Sup "(\<inter>#)" "(\<subseteq>#)" "(\<subset>#)" "(\<union>#)"
  1123 proof
  1124   fix X :: "'a multiset" and A
  1125   assume "X \<in> A"
  1126   show "Inf A \<subseteq># X"
  1127   proof (rule mset_subset_eqI)
  1128     fix x
  1129     from \<open>X \<in> A\<close> have "A \<noteq> {}" by auto
  1130     hence "count (Inf A) x = (INF X\<in>A. count X x)"
  1131       by (simp add: count_Inf_multiset_nonempty)
  1132     also from \<open>X \<in> A\<close> have "\<dots> \<le> count X x"
  1133       by (intro cInf_lower) simp_all
  1134     finally show "count (Inf A) x \<le> count X x" .
  1135   qed
  1136 next
  1137   fix X :: "'a multiset" and A
  1138   assume nonempty: "A \<noteq> {}" and le: "\<And>Y. Y \<in> A \<Longrightarrow> X \<subseteq># Y"
  1139   show "X \<subseteq># Inf A"
  1140   proof (rule mset_subset_eqI)
  1141     fix x
  1142     from nonempty have "count X x \<le> (INF X\<in>A. count X x)"
  1143       by (intro cInf_greatest) (auto intro: mset_subset_eq_count le)
  1144     also from nonempty have "\<dots> = count (Inf A) x" by (simp add: count_Inf_multiset_nonempty)
  1145     finally show "count X x \<le> count (Inf A) x" .
  1146   qed
  1147 next
  1148   fix X :: "'a multiset" and A
  1149   assume X: "X \<in> A" and bdd: "subset_mset.bdd_above A"
  1150   show "X \<subseteq># Sup A"
  1151   proof (rule mset_subset_eqI)
  1152     fix x
  1153     from X have "A \<noteq> {}" by auto
  1154     have "count X x \<le> (SUP X\<in>A. count X x)"
  1155       by (intro cSUP_upper X bdd_above_multiset_imp_bdd_above_count bdd)
  1156     also from count_Sup_multiset_nonempty[OF \<open>A \<noteq> {}\<close> bdd]
  1157       have "(SUP X\<in>A. count X x) = count (Sup A) x" by simp
  1158     finally show "count X x \<le> count (Sup A) x" .
  1159   qed
  1160 next
  1161   fix X :: "'a multiset" and A
  1162   assume nonempty: "A \<noteq> {}" and ge: "\<And>Y. Y \<in> A \<Longrightarrow> Y \<subseteq># X"
  1163   from ge have bdd: "subset_mset.bdd_above A" by (rule subset_mset.bdd_aboveI[of _ X])
  1164   show "Sup A \<subseteq># X"
  1165   proof (rule mset_subset_eqI)
  1166     fix x
  1167     from count_Sup_multiset_nonempty[OF \<open>A \<noteq> {}\<close> bdd]
  1168       have "count (Sup A) x = (SUP X\<in>A. count X x)" .
  1169     also from nonempty have "\<dots> \<le> count X x"
  1170       by (intro cSup_least) (auto intro: mset_subset_eq_count ge)
  1171     finally show "count (Sup A) x \<le> count X x" .
  1172   qed
  1173 qed \<comment> \<open>FIXME: avoid junk stemming from type class interpretation\<close>
  1174 
  1175 lemma set_mset_Inf:
  1176   assumes "A \<noteq> {}"
  1177   shows   "set_mset (Inf A) = (\<Inter>X\<in>A. set_mset X)"
  1178 proof safe
  1179   fix x X assume "x \<in># Inf A" "X \<in> A"
  1180   hence nonempty: "A \<noteq> {}" by (auto simp: Inf_multiset_empty)
  1181   from \<open>x \<in># Inf A\<close> have "{#x#} \<subseteq># Inf A" by auto
  1182   also from \<open>X \<in> A\<close> have "\<dots> \<subseteq># X" by (rule subset_mset.cInf_lower) simp_all
  1183   finally show "x \<in># X" by simp
  1184 next
  1185   fix x assume x: "x \<in> (\<Inter>X\<in>A. set_mset X)"
  1186   hence "{#x#} \<subseteq># X" if "X \<in> A" for X using that by auto
  1187   from assms and this have "{#x#} \<subseteq># Inf A" by (rule subset_mset.cInf_greatest)
  1188   thus "x \<in># Inf A" by simp
  1189 qed
  1190 
  1191 lemma in_Inf_multiset_iff:
  1192   assumes "A \<noteq> {}"
  1193   shows   "x \<in># Inf A \<longleftrightarrow> (\<forall>X\<in>A. x \<in># X)"
  1194 proof -
  1195   from assms have "set_mset (Inf A) = (\<Inter>X\<in>A. set_mset X)" by (rule set_mset_Inf)
  1196   also have "x \<in> \<dots> \<longleftrightarrow> (\<forall>X\<in>A. x \<in># X)" by simp
  1197   finally show ?thesis .
  1198 qed
  1199 
  1200 lemma in_Inf_multisetD: "x \<in># Inf A \<Longrightarrow> X \<in> A \<Longrightarrow> x \<in># X"
  1201   by (subst (asm) in_Inf_multiset_iff) auto
  1202 
  1203 lemma set_mset_Sup:
  1204   assumes "subset_mset.bdd_above A"
  1205   shows   "set_mset (Sup A) = (\<Union>X\<in>A. set_mset X)"
  1206 proof safe
  1207   fix x assume "x \<in># Sup A"
  1208   hence nonempty: "A \<noteq> {}" by (auto simp: Sup_multiset_empty)
  1209   show "x \<in> (\<Union>X\<in>A. set_mset X)"
  1210   proof (rule ccontr)
  1211     assume x: "x \<notin> (\<Union>X\<in>A. set_mset X)"
  1212     have "count X x \<le> count (Sup A) x" if "X \<in> A" for X x
  1213       using that by (intro mset_subset_eq_count subset_mset.cSup_upper assms)
  1214     with x have "X \<subseteq># Sup A - {#x#}" if "X \<in> A" for X
  1215       using that by (auto simp: subseteq_mset_def algebra_simps not_in_iff)
  1216     hence "Sup A \<subseteq># Sup A - {#x#}" by (intro subset_mset.cSup_least nonempty)
  1217     with \<open>x \<in># Sup A\<close> show False
  1218       by (auto simp: subseteq_mset_def simp flip: count_greater_zero_iff
  1219                dest!: spec[of _ x])
  1220   qed
  1221 next
  1222   fix x X assume "x \<in> set_mset X" "X \<in> A"
  1223   hence "{#x#} \<subseteq># X" by auto
  1224   also have "X \<subseteq># Sup A" by (intro subset_mset.cSup_upper \<open>X \<in> A\<close> assms)
  1225   finally show "x \<in> set_mset (Sup A)" by simp
  1226 qed
  1227 
  1228 lemma in_Sup_multiset_iff:
  1229   assumes "subset_mset.bdd_above A"
  1230   shows   "x \<in># Sup A \<longleftrightarrow> (\<exists>X\<in>A. x \<in># X)"
  1231 proof -
  1232   from assms have "set_mset (Sup A) = (\<Union>X\<in>A. set_mset X)" by (rule set_mset_Sup)
  1233   also have "x \<in> \<dots> \<longleftrightarrow> (\<exists>X\<in>A. x \<in># X)" by simp
  1234   finally show ?thesis .
  1235 qed
  1236 
  1237 lemma in_Sup_multisetD:
  1238   assumes "x \<in># Sup A"
  1239   shows   "\<exists>X\<in>A. x \<in># X"
  1240 proof -
  1241   have "subset_mset.bdd_above A"
  1242     by (rule ccontr) (insert assms, simp_all add: Sup_multiset_unbounded)
  1243   with assms show ?thesis by (simp add: in_Sup_multiset_iff)
  1244 qed
  1245 
  1246 interpretation subset_mset: distrib_lattice "(\<inter>#)" "(\<subseteq>#)" "(\<subset>#)" "(\<union>#)"
  1247 proof
  1248   fix A B C :: "'a multiset"
  1249   show "A \<union># (B \<inter># C) = A \<union># B \<inter># (A \<union># C)"
  1250     by (intro multiset_eqI) simp_all
  1251 qed \<comment> \<open>FIXME: avoid junk stemming from type class interpretation\<close>
  1252 
  1253 
  1254 subsubsection \<open>Filter (with comprehension syntax)\<close>
  1255 
  1256 text \<open>Multiset comprehension\<close>
  1257 
  1258 lift_definition filter_mset :: "('a \<Rightarrow> bool) \<Rightarrow> 'a multiset \<Rightarrow> 'a multiset"
  1259 is "\<lambda>P M. \<lambda>x. if P x then M x else 0"
  1260 by (rule filter_preserves_multiset)
  1261 
  1262 syntax (ASCII)
  1263   "_MCollect" :: "pttrn \<Rightarrow> 'a multiset \<Rightarrow> bool \<Rightarrow> 'a multiset"    ("(1{#_ :# _./ _#})")
  1264 syntax
  1265   "_MCollect" :: "pttrn \<Rightarrow> 'a multiset \<Rightarrow> bool \<Rightarrow> 'a multiset"    ("(1{#_ \<in># _./ _#})")
  1266 translations
  1267   "{#x \<in># M. P#}" == "CONST filter_mset (\<lambda>x. P) M"
  1268 
  1269 lemma count_filter_mset [simp]:
  1270   "count (filter_mset P M) a = (if P a then count M a else 0)"
  1271   by (simp add: filter_mset.rep_eq)
  1272 
  1273 lemma set_mset_filter [simp]:
  1274   "set_mset (filter_mset P M) = {a \<in> set_mset M. P a}"
  1275   by (simp only: set_eq_iff count_greater_zero_iff [symmetric] count_filter_mset) simp
  1276 
  1277 lemma filter_empty_mset [simp]: "filter_mset P {#} = {#}"
  1278   by (rule multiset_eqI) simp
  1279 
  1280 lemma filter_single_mset: "filter_mset P {#x#} = (if P x then {#x#} else {#})"
  1281   by (rule multiset_eqI) simp
  1282 
  1283 lemma filter_union_mset [simp]: "filter_mset P (M + N) = filter_mset P M + filter_mset P N"
  1284   by (rule multiset_eqI) simp
  1285 
  1286 lemma filter_diff_mset [simp]: "filter_mset P (M - N) = filter_mset P M - filter_mset P N"
  1287   by (rule multiset_eqI) simp
  1288 
  1289 lemma filter_inter_mset [simp]: "filter_mset P (M \<inter># N) = filter_mset P M \<inter># filter_mset P N"
  1290   by (rule multiset_eqI) simp
  1291 
  1292 lemma filter_sup_mset[simp]: "filter_mset P (A \<union># B) = filter_mset P A \<union># filter_mset P B"
  1293   by (rule multiset_eqI) simp
  1294 
  1295 lemma filter_mset_add_mset [simp]:
  1296    "filter_mset P (add_mset x A) =
  1297      (if P x then add_mset x (filter_mset P A) else filter_mset P A)"
  1298    by (auto simp: multiset_eq_iff)
  1299 
  1300 lemma multiset_filter_subset[simp]: "filter_mset f M \<subseteq># M"
  1301   by (simp add: mset_subset_eqI)
  1302 
  1303 lemma multiset_filter_mono:
  1304   assumes "A \<subseteq># B"
  1305   shows "filter_mset f A \<subseteq># filter_mset f B"
  1306 proof -
  1307   from assms[unfolded mset_subset_eq_exists_conv]
  1308   obtain C where B: "B = A + C" by auto
  1309   show ?thesis unfolding B by auto
  1310 qed
  1311 
  1312 lemma filter_mset_eq_conv:
  1313   "filter_mset P M = N \<longleftrightarrow> N \<subseteq># M \<and> (\<forall>b\<in>#N. P b) \<and> (\<forall>a\<in>#M - N. \<not> P a)" (is "?P \<longleftrightarrow> ?Q")
  1314 proof
  1315   assume ?P then show ?Q by auto (simp add: multiset_eq_iff in_diff_count)
  1316 next
  1317   assume ?Q
  1318   then obtain Q where M: "M = N + Q"
  1319     by (auto simp add: mset_subset_eq_exists_conv)
  1320   then have MN: "M - N = Q" by simp
  1321   show ?P
  1322   proof (rule multiset_eqI)
  1323     fix a
  1324     from \<open>?Q\<close> MN have *: "\<not> P a \<Longrightarrow> a \<notin># N" "P a \<Longrightarrow> a \<notin># Q"
  1325       by auto
  1326     show "count (filter_mset P M) a = count N a"
  1327     proof (cases "a \<in># M")
  1328       case True
  1329       with * show ?thesis
  1330         by (simp add: not_in_iff M)
  1331     next
  1332       case False then have "count M a = 0"
  1333         by (simp add: not_in_iff)
  1334       with M show ?thesis by simp
  1335     qed
  1336   qed
  1337 qed
  1338 
  1339 lemma filter_filter_mset: "filter_mset P (filter_mset Q M) = {#x \<in># M. Q x \<and> P x#}"
  1340   by (auto simp: multiset_eq_iff)
  1341 
  1342 lemma
  1343   filter_mset_True[simp]: "{#y \<in># M. True#} = M" and
  1344   filter_mset_False[simp]: "{#y \<in># M. False#} = {#}"
  1345   by (auto simp: multiset_eq_iff)
  1346 
  1347 
  1348 subsubsection \<open>Size\<close>
  1349 
  1350 definition wcount where "wcount f M = (\<lambda>x. count M x * Suc (f x))"
  1351 
  1352 lemma wcount_union: "wcount f (M + N) a = wcount f M a + wcount f N a"
  1353   by (auto simp: wcount_def add_mult_distrib)
  1354 
  1355 lemma wcount_add_mset:
  1356   "wcount f (add_mset x M) a = (if x = a then Suc (f a) else 0) + wcount f M a"
  1357   unfolding add_mset_add_single[of _ M] wcount_union by (auto simp: wcount_def)
  1358 
  1359 definition size_multiset :: "('a \<Rightarrow> nat) \<Rightarrow> 'a multiset \<Rightarrow> nat" where
  1360   "size_multiset f M = sum (wcount f M) (set_mset M)"
  1361 
  1362 lemmas size_multiset_eq = size_multiset_def[unfolded wcount_def]
  1363 
  1364 instantiation multiset :: (type) size
  1365 begin
  1366 
  1367 definition size_multiset where
  1368   size_multiset_overloaded_def: "size_multiset = Multiset.size_multiset (\<lambda>_. 0)"
  1369 instance ..
  1370 
  1371 end
  1372 
  1373 lemmas size_multiset_overloaded_eq =
  1374   size_multiset_overloaded_def[THEN fun_cong, unfolded size_multiset_eq, simplified]
  1375 
  1376 lemma size_multiset_empty [simp]: "size_multiset f {#} = 0"
  1377 by (simp add: size_multiset_def)
  1378 
  1379 lemma size_empty [simp]: "size {#} = 0"
  1380 by (simp add: size_multiset_overloaded_def)
  1381 
  1382 lemma size_multiset_single : "size_multiset f {#b#} = Suc (f b)"
  1383 by (simp add: size_multiset_eq)
  1384 
  1385 lemma size_single: "size {#b#} = 1"
  1386 by (simp add: size_multiset_overloaded_def size_multiset_single)
  1387 
  1388 lemma sum_wcount_Int:
  1389   "finite A \<Longrightarrow> sum (wcount f N) (A \<inter> set_mset N) = sum (wcount f N) A"
  1390   by (induct rule: finite_induct)
  1391     (simp_all add: Int_insert_left wcount_def count_eq_zero_iff)
  1392 
  1393 lemma size_multiset_union [simp]:
  1394   "size_multiset f (M + N::'a multiset) = size_multiset f M + size_multiset f N"
  1395 apply (simp add: size_multiset_def sum_Un_nat sum.distrib sum_wcount_Int wcount_union)
  1396 apply (subst Int_commute)
  1397 apply (simp add: sum_wcount_Int)
  1398 done
  1399 
  1400 lemma size_multiset_add_mset [simp]:
  1401   "size_multiset f (add_mset a M) = Suc (f a) + size_multiset f M"
  1402   unfolding add_mset_add_single[of _ M] size_multiset_union by (auto simp: size_multiset_single)
  1403 
  1404 lemma size_add_mset [simp]: "size (add_mset a A) = Suc (size A)"
  1405 by (simp add: size_multiset_overloaded_def wcount_add_mset)
  1406 
  1407 lemma size_union [simp]: "size (M + N::'a multiset) = size M + size N"
  1408 by (auto simp add: size_multiset_overloaded_def)
  1409 
  1410 lemma size_multiset_eq_0_iff_empty [iff]:
  1411   "size_multiset f M = 0 \<longleftrightarrow> M = {#}"
  1412   by (auto simp add: size_multiset_eq count_eq_zero_iff)
  1413 
  1414 lemma size_eq_0_iff_empty [iff]: "(size M = 0) = (M = {#})"
  1415 by (auto simp add: size_multiset_overloaded_def)
  1416 
  1417 lemma nonempty_has_size: "(S \<noteq> {#}) = (0 < size S)"
  1418 by (metis gr0I gr_implies_not0 size_empty size_eq_0_iff_empty)
  1419 
  1420 lemma size_eq_Suc_imp_elem: "size M = Suc n \<Longrightarrow> \<exists>a. a \<in># M"
  1421 apply (unfold size_multiset_overloaded_eq)
  1422 apply (drule sum_SucD)
  1423 apply auto
  1424 done
  1425 
  1426 lemma size_eq_Suc_imp_eq_union:
  1427   assumes "size M = Suc n"
  1428   shows "\<exists>a N. M = add_mset a N"
  1429 proof -
  1430   from assms obtain a where "a \<in># M"
  1431     by (erule size_eq_Suc_imp_elem [THEN exE])
  1432   then have "M = add_mset a (M - {#a#})" by simp
  1433   then show ?thesis by blast
  1434 qed
  1435 
  1436 lemma size_mset_mono:
  1437   fixes A B :: "'a multiset"
  1438   assumes "A \<subseteq># B"
  1439   shows "size A \<le> size B"
  1440 proof -
  1441   from assms[unfolded mset_subset_eq_exists_conv]
  1442   obtain C where B: "B = A + C" by auto
  1443   show ?thesis unfolding B by (induct C) auto
  1444 qed
  1445 
  1446 lemma size_filter_mset_lesseq[simp]: "size (filter_mset f M) \<le> size M"
  1447 by (rule size_mset_mono[OF multiset_filter_subset])
  1448 
  1449 lemma size_Diff_submset:
  1450   "M \<subseteq># M' \<Longrightarrow> size (M' - M) = size M' - size(M::'a multiset)"
  1451 by (metis add_diff_cancel_left' size_union mset_subset_eq_exists_conv)
  1452 
  1453 
  1454 subsection \<open>Induction and case splits\<close>
  1455 
  1456 theorem multiset_induct [case_names empty add, induct type: multiset]:
  1457   assumes empty: "P {#}"
  1458   assumes add: "\<And>x M. P M \<Longrightarrow> P (add_mset x M)"
  1459   shows "P M"
  1460 proof (induct "size M" arbitrary: M)
  1461   case 0 thus "P M" by (simp add: empty)
  1462 next
  1463   case (Suc k)
  1464   obtain N x where "M = add_mset x N"
  1465     using \<open>Suc k = size M\<close> [symmetric]
  1466     using size_eq_Suc_imp_eq_union by fast
  1467   with Suc add show "P M" by simp
  1468 qed
  1469 
  1470 lemma multiset_induct_min[case_names empty add]:
  1471   fixes M :: "'a::linorder multiset"
  1472   assumes
  1473     empty: "P {#}" and
  1474     add: "\<And>x M. P M \<Longrightarrow> (\<forall>y \<in># M. y \<ge> x) \<Longrightarrow> P (add_mset x M)"
  1475   shows "P M"
  1476 proof (induct "size M" arbitrary: M)
  1477   case (Suc k)
  1478   note ih = this(1) and Sk_eq_sz_M = this(2)
  1479 
  1480   let ?y = "Min_mset M"
  1481   let ?N = "M - {#?y#}"
  1482 
  1483   have M: "M = add_mset ?y ?N"
  1484     by (metis Min_in Sk_eq_sz_M finite_set_mset insert_DiffM lessI not_less_zero
  1485       set_mset_eq_empty_iff size_empty)
  1486   show ?case
  1487     by (subst M, rule add, rule ih, metis M Sk_eq_sz_M nat.inject size_add_mset,
  1488       meson Min_le finite_set_mset in_diffD)
  1489 qed (simp add: empty)
  1490 
  1491 lemma multiset_induct_max[case_names empty add]:
  1492   fixes M :: "'a::linorder multiset"
  1493   assumes
  1494     empty: "P {#}" and
  1495     add: "\<And>x M. P M \<Longrightarrow> (\<forall>y \<in># M. y \<le> x) \<Longrightarrow> P (add_mset x M)"
  1496   shows "P M"
  1497 proof (induct "size M" arbitrary: M)
  1498   case (Suc k)
  1499   note ih = this(1) and Sk_eq_sz_M = this(2)
  1500 
  1501   let ?y = "Max_mset M"
  1502   let ?N = "M - {#?y#}"
  1503 
  1504   have M: "M = add_mset ?y ?N"
  1505     by (metis Max_in Sk_eq_sz_M finite_set_mset insert_DiffM lessI not_less_zero
  1506       set_mset_eq_empty_iff size_empty)
  1507   show ?case
  1508     by (subst M, rule add, rule ih, metis M Sk_eq_sz_M nat.inject size_add_mset,
  1509       meson Max_ge finite_set_mset in_diffD)
  1510 qed (simp add: empty)
  1511 
  1512 lemma multi_nonempty_split: "M \<noteq> {#} \<Longrightarrow> \<exists>A a. M = add_mset a A"
  1513 by (induct M) auto
  1514 
  1515 lemma multiset_cases [cases type]:
  1516   obtains (empty) "M = {#}"
  1517     | (add) x N where "M = add_mset x N"
  1518   by (induct M) simp_all
  1519 
  1520 lemma multi_drop_mem_not_eq: "c \<in># B \<Longrightarrow> B - {#c#} \<noteq> B"
  1521 by (cases "B = {#}") (auto dest: multi_member_split)
  1522 
  1523 lemma union_filter_mset_complement[simp]:
  1524   "\<forall>x. P x = (\<not> Q x) \<Longrightarrow> filter_mset P M + filter_mset Q M = M"
  1525 by (subst multiset_eq_iff) auto
  1526 
  1527 lemma multiset_partition: "M = {#x \<in># M. P x#} + {#x \<in># M. \<not> P x#}"
  1528 by simp
  1529 
  1530 lemma mset_subset_size: "A \<subset># B \<Longrightarrow> size A < size B"
  1531 proof (induct A arbitrary: B)
  1532   case empty
  1533   then show ?case
  1534     using nonempty_has_size by auto
  1535 next
  1536   case (add x A)
  1537   have "add_mset x A \<subseteq># B"
  1538     by (meson add.prems subset_mset_def)
  1539   then show ?case
  1540     by (metis (no_types) add.prems add.right_neutral add_diff_cancel_left' leD nat_neq_iff
  1541       size_Diff_submset size_eq_0_iff_empty size_mset_mono subset_mset.le_iff_add subset_mset_def)
  1542 qed
  1543 
  1544 lemma size_1_singleton_mset: "size M = 1 \<Longrightarrow> \<exists>a. M = {#a#}"
  1545   by (cases M) auto
  1546 
  1547 
  1548 subsubsection \<open>Strong induction and subset induction for multisets\<close>
  1549 
  1550 text \<open>Well-foundedness of strict subset relation\<close>
  1551 
  1552 lemma wf_subset_mset_rel: "wf {(M, N :: 'a multiset). M \<subset># N}"
  1553 apply (rule wf_measure [THEN wf_subset, where f1=size])
  1554 apply (clarsimp simp: measure_def inv_image_def mset_subset_size)
  1555 done
  1556 
  1557 lemma full_multiset_induct [case_names less]:
  1558 assumes ih: "\<And>B. \<forall>(A::'a multiset). A \<subset># B \<longrightarrow> P A \<Longrightarrow> P B"
  1559 shows "P B"
  1560 apply (rule wf_subset_mset_rel [THEN wf_induct])
  1561 apply (rule ih, auto)
  1562 done
  1563 
  1564 lemma multi_subset_induct [consumes 2, case_names empty add]:
  1565   assumes "F \<subseteq># A"
  1566     and empty: "P {#}"
  1567     and insert: "\<And>a F. a \<in># A \<Longrightarrow> P F \<Longrightarrow> P (add_mset a F)"
  1568   shows "P F"
  1569 proof -
  1570   from \<open>F \<subseteq># A\<close>
  1571   show ?thesis
  1572   proof (induct F)
  1573     show "P {#}" by fact
  1574   next
  1575     fix x F
  1576     assume P: "F \<subseteq># A \<Longrightarrow> P F" and i: "add_mset x F \<subseteq># A"
  1577     show "P (add_mset x F)"
  1578     proof (rule insert)
  1579       from i show "x \<in># A" by (auto dest: mset_subset_eq_insertD)
  1580       from i have "F \<subseteq># A" by (auto dest: mset_subset_eq_insertD)
  1581       with P show "P F" .
  1582     qed
  1583   qed
  1584 qed
  1585 
  1586 
  1587 subsection \<open>The fold combinator\<close>
  1588 
  1589 definition fold_mset :: "('a \<Rightarrow> 'b \<Rightarrow> 'b) \<Rightarrow> 'b \<Rightarrow> 'a multiset \<Rightarrow> 'b"
  1590 where
  1591   "fold_mset f s M = Finite_Set.fold (\<lambda>x. f x ^^ count M x) s (set_mset M)"
  1592 
  1593 lemma fold_mset_empty [simp]: "fold_mset f s {#} = s"
  1594   by (simp add: fold_mset_def)
  1595 
  1596 context comp_fun_commute
  1597 begin
  1598 
  1599 lemma fold_mset_add_mset [simp]: "fold_mset f s (add_mset x M) = f x (fold_mset f s M)"
  1600 proof -
  1601   interpret mset: comp_fun_commute "\<lambda>y. f y ^^ count M y"
  1602     by (fact comp_fun_commute_funpow)
  1603   interpret mset_union: comp_fun_commute "\<lambda>y. f y ^^ count (add_mset x M) y"
  1604     by (fact comp_fun_commute_funpow)
  1605   show ?thesis
  1606   proof (cases "x \<in> set_mset M")
  1607     case False
  1608     then have *: "count (add_mset x M) x = 1"
  1609       by (simp add: not_in_iff)
  1610     from False have "Finite_Set.fold (\<lambda>y. f y ^^ count (add_mset x M) y) s (set_mset M) =
  1611       Finite_Set.fold (\<lambda>y. f y ^^ count M y) s (set_mset M)"
  1612       by (auto intro!: Finite_Set.fold_cong comp_fun_commute_funpow)
  1613     with False * show ?thesis
  1614       by (simp add: fold_mset_def del: count_add_mset)
  1615   next
  1616     case True
  1617     define N where "N = set_mset M - {x}"
  1618     from N_def True have *: "set_mset M = insert x N" "x \<notin> N" "finite N" by auto
  1619     then have "Finite_Set.fold (\<lambda>y. f y ^^ count (add_mset x M) y) s N =
  1620       Finite_Set.fold (\<lambda>y. f y ^^ count M y) s N"
  1621       by (auto intro!: Finite_Set.fold_cong comp_fun_commute_funpow)
  1622     with * show ?thesis by (simp add: fold_mset_def del: count_add_mset) simp
  1623   qed
  1624 qed
  1625 
  1626 corollary fold_mset_single: "fold_mset f s {#x#} = f x s"
  1627   by simp
  1628 
  1629 lemma fold_mset_fun_left_comm: "f x (fold_mset f s M) = fold_mset f (f x s) M"
  1630   by (induct M) (simp_all add: fun_left_comm)
  1631 
  1632 lemma fold_mset_union [simp]: "fold_mset f s (M + N) = fold_mset f (fold_mset f s M) N"
  1633   by (induct M) (simp_all add: fold_mset_fun_left_comm)
  1634 
  1635 lemma fold_mset_fusion:
  1636   assumes "comp_fun_commute g"
  1637     and *: "\<And>x y. h (g x y) = f x (h y)"
  1638   shows "h (fold_mset g w A) = fold_mset f (h w) A"
  1639 proof -
  1640   interpret comp_fun_commute g by (fact assms)
  1641   from * show ?thesis by (induct A) auto
  1642 qed
  1643 
  1644 end
  1645 
  1646 lemma union_fold_mset_add_mset: "A + B = fold_mset add_mset A B"
  1647 proof -
  1648   interpret comp_fun_commute add_mset
  1649     by standard auto
  1650   show ?thesis
  1651     by (induction B) auto
  1652 qed
  1653 
  1654 text \<open>
  1655   A note on code generation: When defining some function containing a
  1656   subterm \<^term>\<open>fold_mset F\<close>, code generation is not automatic. When
  1657   interpreting locale \<open>left_commutative\<close> with \<open>F\<close>, the
  1658   would be code thms for \<^const>\<open>fold_mset\<close> become thms like
  1659   \<^term>\<open>fold_mset F z {#} = z\<close> where \<open>F\<close> is not a pattern but
  1660   contains defined symbols, i.e.\ is not a code thm. Hence a separate
  1661   constant with its own code thms needs to be introduced for \<open>F\<close>. See the image operator below.
  1662 \<close>
  1663 
  1664 
  1665 subsection \<open>Image\<close>
  1666 
  1667 definition image_mset :: "('a \<Rightarrow> 'b) \<Rightarrow> 'a multiset \<Rightarrow> 'b multiset" where
  1668   "image_mset f = fold_mset (add_mset \<circ> f) {#}"
  1669 
  1670 lemma comp_fun_commute_mset_image: "comp_fun_commute (add_mset \<circ> f)"
  1671   by unfold_locales (simp add: fun_eq_iff)
  1672 
  1673 lemma image_mset_empty [simp]: "image_mset f {#} = {#}"
  1674   by (simp add: image_mset_def)
  1675 
  1676 lemma image_mset_single: "image_mset f {#x#} = {#f x#}"
  1677   by (simp add: comp_fun_commute.fold_mset_add_mset comp_fun_commute_mset_image image_mset_def)
  1678 
  1679 lemma image_mset_union [simp]: "image_mset f (M + N) = image_mset f M + image_mset f N"
  1680 proof -
  1681   interpret comp_fun_commute "add_mset \<circ> f"
  1682     by (fact comp_fun_commute_mset_image)
  1683   show ?thesis by (induct N) (simp_all add: image_mset_def)
  1684 qed
  1685 
  1686 corollary image_mset_add_mset [simp]:
  1687   "image_mset f (add_mset a M) = add_mset (f a) (image_mset f M)"
  1688   unfolding image_mset_union add_mset_add_single[of a M] by (simp add: image_mset_single)
  1689 
  1690 lemma set_image_mset [simp]: "set_mset (image_mset f M) = image f (set_mset M)"
  1691   by (induct M) simp_all
  1692 
  1693 lemma size_image_mset [simp]: "size (image_mset f M) = size M"
  1694   by (induct M) simp_all
  1695 
  1696 lemma image_mset_is_empty_iff [simp]: "image_mset f M = {#} \<longleftrightarrow> M = {#}"
  1697   by (cases M) auto
  1698 
  1699 lemma image_mset_If:
  1700   "image_mset (\<lambda>x. if P x then f x else g x) A =
  1701      image_mset f (filter_mset P A) + image_mset g (filter_mset (\<lambda>x. \<not>P x) A)"
  1702   by (induction A) auto
  1703 
  1704 lemma image_mset_Diff:
  1705   assumes "B \<subseteq># A"
  1706   shows   "image_mset f (A - B) = image_mset f A - image_mset f B"
  1707 proof -
  1708   have "image_mset f (A - B + B) = image_mset f (A - B) + image_mset f B"
  1709     by simp
  1710   also from assms have "A - B + B = A"
  1711     by (simp add: subset_mset.diff_add)
  1712   finally show ?thesis by simp
  1713 qed
  1714 
  1715 lemma count_image_mset: "count (image_mset f A) x = (\<Sum>y\<in>f -` {x} \<inter> set_mset A. count A y)"
  1716 proof (induction A)
  1717   case empty
  1718   then show ?case by simp
  1719 next
  1720   case (add x A)
  1721   moreover have *: "(if x = y then Suc n else n) = n + (if x = y then 1 else 0)" for n y
  1722     by simp
  1723   ultimately show ?case
  1724     by (auto simp: sum.distrib intro!: sum.mono_neutral_left)
  1725 qed
  1726 
  1727 lemma image_mset_subseteq_mono: "A \<subseteq># B \<Longrightarrow> image_mset f A \<subseteq># image_mset f B"
  1728   by (metis image_mset_union subset_mset.le_iff_add)
  1729 
  1730 lemma image_mset_subset_mono: "M \<subset># N \<Longrightarrow> image_mset f M \<subset># image_mset f N"
  1731   by (metis (no_types) Diff_eq_empty_iff_mset image_mset_Diff image_mset_is_empty_iff
  1732     image_mset_subseteq_mono subset_mset.less_le_not_le)
  1733 
  1734 syntax (ASCII)
  1735   "_comprehension_mset" :: "'a \<Rightarrow> 'b \<Rightarrow> 'b multiset \<Rightarrow> 'a multiset"  ("({#_/. _ :# _#})")
  1736 syntax
  1737   "_comprehension_mset" :: "'a \<Rightarrow> 'b \<Rightarrow> 'b multiset \<Rightarrow> 'a multiset"  ("({#_/. _ \<in># _#})")
  1738 translations
  1739   "{#e. x \<in># M#}" \<rightleftharpoons> "CONST image_mset (\<lambda>x. e) M"
  1740 
  1741 syntax (ASCII)
  1742   "_comprehension_mset'" :: "'a \<Rightarrow> 'b \<Rightarrow> 'b multiset \<Rightarrow> bool \<Rightarrow> 'a multiset"  ("({#_/ | _ :# _./ _#})")
  1743 syntax
  1744   "_comprehension_mset'" :: "'a \<Rightarrow> 'b \<Rightarrow> 'b multiset \<Rightarrow> bool \<Rightarrow> 'a multiset"  ("({#_/ | _ \<in># _./ _#})")
  1745 translations
  1746   "{#e | x\<in>#M. P#}" \<rightharpoonup> "{#e. x \<in># {# x\<in>#M. P#}#}"
  1747 
  1748 text \<open>
  1749   This allows to write not just filters like \<^term>\<open>{#x\<in>#M. x<c#}\<close>
  1750   but also images like \<^term>\<open>{#x+x. x\<in>#M #}\<close> and @{term [source]
  1751   "{#x+x|x\<in>#M. x<c#}"}, where the latter is currently displayed as
  1752   \<^term>\<open>{#x+x|x\<in>#M. x<c#}\<close>.
  1753 \<close>
  1754 
  1755 lemma in_image_mset: "y \<in># {#f x. x \<in># M#} \<longleftrightarrow> y \<in> f ` set_mset M"
  1756   by simp
  1757 
  1758 functor image_mset: image_mset
  1759 proof -
  1760   fix f g show "image_mset f \<circ> image_mset g = image_mset (f \<circ> g)"
  1761   proof
  1762     fix A
  1763     show "(image_mset f \<circ> image_mset g) A = image_mset (f \<circ> g) A"
  1764       by (induct A) simp_all
  1765   qed
  1766   show "image_mset id = id"
  1767   proof
  1768     fix A
  1769     show "image_mset id A = id A"
  1770       by (induct A) simp_all
  1771   qed
  1772 qed
  1773 
  1774 declare
  1775   image_mset.id [simp]
  1776   image_mset.identity [simp]
  1777 
  1778 lemma image_mset_id[simp]: "image_mset id x = x"
  1779   unfolding id_def by auto
  1780 
  1781 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#}"
  1782   by (induct M) auto
  1783 
  1784 lemma image_mset_cong_pair:
  1785   "(\<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#}"
  1786   by (metis image_mset_cong split_cong)
  1787 
  1788 lemma image_mset_const_eq:
  1789   "{#c. a \<in># M#} = replicate_mset (size M) c"
  1790   by (induct M) simp_all
  1791 
  1792 
  1793 subsection \<open>Further conversions\<close>
  1794 
  1795 primrec mset :: "'a list \<Rightarrow> 'a multiset" where
  1796   "mset [] = {#}" |
  1797   "mset (a # x) = add_mset a (mset x)"
  1798 
  1799 lemma in_multiset_in_set:
  1800   "x \<in># mset xs \<longleftrightarrow> x \<in> set xs"
  1801   by (induct xs) simp_all
  1802 
  1803 lemma count_mset:
  1804   "count (mset xs) x = length (filter (\<lambda>y. x = y) xs)"
  1805   by (induct xs) simp_all
  1806 
  1807 lemma mset_zero_iff[simp]: "(mset x = {#}) = (x = [])"
  1808   by (induct x) auto
  1809 
  1810 lemma mset_zero_iff_right[simp]: "({#} = mset x) = (x = [])"
  1811 by (induct x) auto
  1812 
  1813 lemma count_mset_gt_0: "x \<in> set xs \<Longrightarrow> count (mset xs) x > 0"
  1814   by (induction xs) auto
  1815 
  1816 lemma count_mset_0_iff [simp]: "count (mset xs) x = 0 \<longleftrightarrow> x \<notin> set xs"
  1817   by (induction xs) auto
  1818 
  1819 lemma mset_single_iff[iff]: "mset xs = {#x#} \<longleftrightarrow> xs = [x]"
  1820   by (cases xs) auto
  1821 
  1822 lemma mset_single_iff_right[iff]: "{#x#} = mset xs \<longleftrightarrow> xs = [x]"
  1823   by (cases xs) auto
  1824 
  1825 lemma set_mset_mset[simp]: "set_mset (mset xs) = set xs"
  1826   by (induct xs) auto
  1827 
  1828 lemma set_mset_comp_mset [simp]: "set_mset \<circ> mset = set"
  1829   by (simp add: fun_eq_iff)
  1830 
  1831 lemma size_mset [simp]: "size (mset xs) = length xs"
  1832   by (induct xs) simp_all
  1833 
  1834 lemma mset_append [simp]: "mset (xs @ ys) = mset xs + mset ys"
  1835   by (induct xs arbitrary: ys) auto
  1836 
  1837 lemma mset_filter[simp]: "mset (filter P xs) = {#x \<in># mset xs. P x #}"
  1838   by (induct xs) simp_all
  1839 
  1840 lemma mset_rev [simp]:
  1841   "mset (rev xs) = mset xs"
  1842   by (induct xs) simp_all
  1843 
  1844 lemma surj_mset: "surj mset"
  1845 apply (unfold surj_def)
  1846 apply (rule allI)
  1847 apply (rule_tac M = y in multiset_induct)
  1848  apply auto
  1849 apply (rule_tac x = "x # xa" in exI)
  1850 apply auto
  1851 done
  1852 
  1853 lemma distinct_count_atmost_1:
  1854   "distinct x = (\<forall>a. count (mset x) a = (if a \<in> set x then 1 else 0))"
  1855 proof (induct x)
  1856   case Nil then show ?case by simp
  1857 next
  1858   case (Cons x xs) show ?case (is "?lhs \<longleftrightarrow> ?rhs")
  1859   proof
  1860     assume ?lhs then show ?rhs using Cons by simp
  1861   next
  1862     assume ?rhs then have "x \<notin> set xs"
  1863       by (simp split: if_splits)
  1864     moreover from \<open>?rhs\<close> have "(\<forall>a. count (mset xs) a =
  1865        (if a \<in> set xs then 1 else 0))"
  1866       by (auto split: if_splits simp add: count_eq_zero_iff)
  1867     ultimately show ?lhs using Cons by simp
  1868   qed
  1869 qed
  1870 
  1871 lemma mset_eq_setD:
  1872   assumes "mset xs = mset ys"
  1873   shows "set xs = set ys"
  1874 proof -
  1875   from assms have "set_mset (mset xs) = set_mset (mset ys)"
  1876     by simp
  1877   then show ?thesis by simp
  1878 qed
  1879 
  1880 lemma set_eq_iff_mset_eq_distinct:
  1881   "distinct x \<Longrightarrow> distinct y \<Longrightarrow>
  1882     (set x = set y) = (mset x = mset y)"
  1883 by (auto simp: multiset_eq_iff distinct_count_atmost_1)
  1884 
  1885 lemma set_eq_iff_mset_remdups_eq:
  1886    "(set x = set y) = (mset (remdups x) = mset (remdups y))"
  1887 apply (rule iffI)
  1888 apply (simp add: set_eq_iff_mset_eq_distinct[THEN iffD1])
  1889 apply (drule distinct_remdups [THEN distinct_remdups
  1890       [THEN set_eq_iff_mset_eq_distinct [THEN iffD2]]])
  1891 apply simp
  1892 done
  1893 
  1894 lemma nth_mem_mset: "i < length ls \<Longrightarrow> (ls ! i) \<in># mset ls"
  1895 proof (induct ls arbitrary: i)
  1896   case Nil
  1897   then show ?case by simp
  1898 next
  1899   case Cons
  1900   then show ?case by (cases i) auto
  1901 qed
  1902 
  1903 lemma mset_remove1[simp]: "mset (remove1 a xs) = mset xs - {#a#}"
  1904   by (induct xs) (auto simp add: multiset_eq_iff)
  1905 
  1906 lemma mset_eq_length:
  1907   assumes "mset xs = mset ys"
  1908   shows "length xs = length ys"
  1909   using assms by (metis size_mset)
  1910 
  1911 lemma mset_eq_length_filter:
  1912   assumes "mset xs = mset ys"
  1913   shows "length (filter (\<lambda>x. z = x) xs) = length (filter (\<lambda>y. z = y) ys)"
  1914   using assms by (metis count_mset)
  1915 
  1916 lemma fold_multiset_equiv:
  1917   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"
  1918     and equiv: "mset xs = mset ys"
  1919   shows "List.fold f xs = List.fold f ys"
  1920   using f equiv [symmetric]
  1921 proof (induct xs arbitrary: ys)
  1922   case Nil
  1923   then show ?case by simp
  1924 next
  1925   case (Cons x xs)
  1926   then have *: "set ys = set (x # xs)"
  1927     by (blast dest: mset_eq_setD)
  1928   have "\<And>x y. x \<in> set ys \<Longrightarrow> y \<in> set ys \<Longrightarrow> f x \<circ> f y = f y \<circ> f x"
  1929     by (rule Cons.prems(1)) (simp_all add: *)
  1930   moreover from * have "x \<in> set ys"
  1931     by simp
  1932   ultimately have "List.fold f ys = List.fold f (remove1 x ys) \<circ> f x"
  1933     by (fact fold_remove1_split)
  1934   moreover from Cons.prems have "List.fold f xs = List.fold f (remove1 x ys)"
  1935     by (auto intro: Cons.hyps)
  1936   ultimately show ?case by simp
  1937 qed
  1938 
  1939 lemma mset_shuffles: "zs \<in> shuffles xs ys \<Longrightarrow> mset zs = mset xs + mset ys"
  1940   by (induction xs ys arbitrary: zs rule: shuffles.induct) auto
  1941 
  1942 lemma mset_insort [simp]: "mset (insort x xs) = add_mset x (mset xs)"
  1943   by (induct xs) simp_all
  1944 
  1945 lemma mset_map[simp]: "mset (map f xs) = image_mset f (mset xs)"
  1946   by (induct xs) simp_all
  1947 
  1948 global_interpretation mset_set: folding add_mset "{#}"
  1949   defines mset_set = "folding.F add_mset {#}"
  1950   by standard (simp add: fun_eq_iff)
  1951 
  1952 lemma sum_multiset_singleton [simp]: "sum (\<lambda>n. {#n#}) A = mset_set A"
  1953   by (induction A rule: infinite_finite_induct) auto
  1954 
  1955 lemma count_mset_set [simp]:
  1956   "finite A \<Longrightarrow> x \<in> A \<Longrightarrow> count (mset_set A) x = 1" (is "PROP ?P")
  1957   "\<not> finite A \<Longrightarrow> count (mset_set A) x = 0" (is "PROP ?Q")
  1958   "x \<notin> A \<Longrightarrow> count (mset_set A) x = 0" (is "PROP ?R")
  1959 proof -
  1960   have *: "count (mset_set A) x = 0" if "x \<notin> A" for A
  1961   proof (cases "finite A")
  1962     case False then show ?thesis by simp
  1963   next
  1964     case True from True \<open>x \<notin> A\<close> show ?thesis by (induct A) auto
  1965   qed
  1966   then show "PROP ?P" "PROP ?Q" "PROP ?R"
  1967   by (auto elim!: Set.set_insert)
  1968 qed \<comment> \<open>TODO: maybe define \<^const>\<open>mset_set\<close> also in terms of \<^const>\<open>Abs_multiset\<close>\<close>
  1969 
  1970 lemma elem_mset_set[simp, intro]: "finite A \<Longrightarrow> x \<in># mset_set A \<longleftrightarrow> x \<in> A"
  1971   by (induct A rule: finite_induct) simp_all
  1972 
  1973 lemma mset_set_Union:
  1974   "finite A \<Longrightarrow> finite B \<Longrightarrow> A \<inter> B = {} \<Longrightarrow> mset_set (A \<union> B) = mset_set A + mset_set B"
  1975   by (induction A rule: finite_induct) auto
  1976 
  1977 lemma filter_mset_mset_set [simp]:
  1978   "finite A \<Longrightarrow> filter_mset P (mset_set A) = mset_set {x\<in>A. P x}"
  1979 proof (induction A rule: finite_induct)
  1980   case (insert x A)
  1981   from insert.hyps have "filter_mset P (mset_set (insert x A)) =
  1982       filter_mset P (mset_set A) + mset_set (if P x then {x} else {})"
  1983     by simp
  1984   also have "filter_mset P (mset_set A) = mset_set {x\<in>A. P x}"
  1985     by (rule insert.IH)
  1986   also from insert.hyps
  1987     have "\<dots> + mset_set (if P x then {x} else {}) =
  1988             mset_set ({x \<in> A. P x} \<union> (if P x then {x} else {}))" (is "_ = mset_set ?A")
  1989      by (intro mset_set_Union [symmetric]) simp_all
  1990   also from insert.hyps have "?A = {y\<in>insert x A. P y}" by auto
  1991   finally show ?case .
  1992 qed simp_all
  1993 
  1994 lemma mset_set_Diff:
  1995   assumes "finite A" "B \<subseteq> A"
  1996   shows  "mset_set (A - B) = mset_set A - mset_set B"
  1997 proof -
  1998   from assms have "mset_set ((A - B) \<union> B) = mset_set (A - B) + mset_set B"
  1999     by (intro mset_set_Union) (auto dest: finite_subset)
  2000   also from assms have "A - B \<union> B = A" by blast
  2001   finally show ?thesis by simp
  2002 qed
  2003 
  2004 lemma mset_set_set: "distinct xs \<Longrightarrow> mset_set (set xs) = mset xs"
  2005   by (induction xs) simp_all
  2006 
  2007 lemma count_mset_set': "count (mset_set A) x = (if finite A \<and> x \<in> A then 1 else 0)"
  2008   by auto
  2009 
  2010 lemma subset_imp_msubset_mset_set: 
  2011   assumes "A \<subseteq> B" "finite B"
  2012   shows   "mset_set A \<subseteq># mset_set B"
  2013 proof (rule mset_subset_eqI)
  2014   fix x :: 'a
  2015   from assms have "finite A" by (rule finite_subset)
  2016   with assms show "count (mset_set A) x \<le> count (mset_set B) x"
  2017     by (cases "x \<in> A"; cases "x \<in> B") auto
  2018 qed
  2019 
  2020 lemma mset_set_set_mset_msubset: "mset_set (set_mset A) \<subseteq># A"
  2021 proof (rule mset_subset_eqI)
  2022   fix x show "count (mset_set (set_mset A)) x \<le> count A x"
  2023     by (cases "x \<in># A") simp_all
  2024 qed
  2025 
  2026 context linorder
  2027 begin
  2028 
  2029 definition sorted_list_of_multiset :: "'a multiset \<Rightarrow> 'a list"
  2030 where
  2031   "sorted_list_of_multiset M = fold_mset insort [] M"
  2032 
  2033 lemma sorted_list_of_multiset_empty [simp]:
  2034   "sorted_list_of_multiset {#} = []"
  2035   by (simp add: sorted_list_of_multiset_def)
  2036 
  2037 lemma sorted_list_of_multiset_singleton [simp]:
  2038   "sorted_list_of_multiset {#x#} = [x]"
  2039 proof -
  2040   interpret comp_fun_commute insort by (fact comp_fun_commute_insort)
  2041   show ?thesis by (simp add: sorted_list_of_multiset_def)
  2042 qed
  2043 
  2044 lemma sorted_list_of_multiset_insert [simp]:
  2045   "sorted_list_of_multiset (add_mset x M) = List.insort x (sorted_list_of_multiset M)"
  2046 proof -
  2047   interpret comp_fun_commute insort by (fact comp_fun_commute_insort)
  2048   show ?thesis by (simp add: sorted_list_of_multiset_def)
  2049 qed
  2050 
  2051 end
  2052 
  2053 lemma mset_sorted_list_of_multiset[simp]: "mset (sorted_list_of_multiset M) = M"
  2054   by (induct M) simp_all
  2055 
  2056 lemma sorted_list_of_multiset_mset[simp]: "sorted_list_of_multiset (mset xs) = sort xs"
  2057   by (induct xs) simp_all
  2058 
  2059 lemma finite_set_mset_mset_set[simp]: "finite A \<Longrightarrow> set_mset (mset_set A) = A"
  2060   by auto
  2061 
  2062 lemma mset_set_empty_iff: "mset_set A = {#} \<longleftrightarrow> A = {} \<or> infinite A"
  2063   using finite_set_mset_mset_set by fastforce
  2064 
  2065 lemma infinite_set_mset_mset_set: "\<not> finite A \<Longrightarrow> set_mset (mset_set A) = {}"
  2066   by simp
  2067 
  2068 lemma set_sorted_list_of_multiset [simp]:
  2069   "set (sorted_list_of_multiset M) = set_mset M"
  2070 by (induct M) (simp_all add: set_insort_key)
  2071 
  2072 lemma sorted_list_of_mset_set [simp]:
  2073   "sorted_list_of_multiset (mset_set A) = sorted_list_of_set A"
  2074 by (cases "finite A") (induct A rule: finite_induct, simp_all)
  2075 
  2076 lemma mset_upt [simp]: "mset [m..<n] = mset_set {m..<n}"
  2077   by (induction n) (simp_all add: atLeastLessThanSuc)
  2078 
  2079 lemma image_mset_map_of:
  2080   "distinct (map fst xs) \<Longrightarrow> {#the (map_of xs i). i \<in># mset (map fst xs)#} = mset (map snd xs)"
  2081 proof (induction xs)
  2082   case (Cons x xs)
  2083   have "{#the (map_of (x # xs) i). i \<in># mset (map fst (x # xs))#} =
  2084           add_mset (snd x) {#the (if i = fst x then Some (snd x) else map_of xs i).
  2085              i \<in># mset (map fst xs)#}" (is "_ = add_mset _ ?A") by simp
  2086   also from Cons.prems have "?A = {#the (map_of xs i). i :# mset (map fst xs)#}"
  2087     by (cases x, intro image_mset_cong) (auto simp: in_multiset_in_set)
  2088   also from Cons.prems have "\<dots> = mset (map snd xs)" by (intro Cons.IH) simp_all
  2089   finally show ?case by simp
  2090 qed simp_all
  2091 
  2092 lemma msubset_mset_set_iff[simp]:
  2093   assumes "finite A" "finite B"
  2094   shows "mset_set A \<subseteq># mset_set B \<longleftrightarrow> A \<subseteq> B"
  2095   using assms set_mset_mono subset_imp_msubset_mset_set by fastforce
  2096 
  2097 lemma mset_set_eq_iff[simp]:
  2098   assumes "finite A" "finite B"
  2099   shows "mset_set A = mset_set B \<longleftrightarrow> A = B"
  2100   using assms by (fastforce dest: finite_set_mset_mset_set)
  2101 
  2102 lemma image_mset_mset_set: \<^marker>\<open>contributor \<open>Lukas Bulwahn\<close>\<close>
  2103   assumes "inj_on f A"
  2104   shows "image_mset f (mset_set A) = mset_set (f ` A)"
  2105 proof cases
  2106   assume "finite A"
  2107   from this \<open>inj_on f A\<close> show ?thesis
  2108     by (induct A) auto
  2109 next
  2110   assume "infinite A"
  2111   from this \<open>inj_on f A\<close> have "infinite (f ` A)"
  2112     using finite_imageD by blast
  2113   from \<open>infinite A\<close> \<open>infinite (f ` A)\<close> show ?thesis by simp
  2114 qed
  2115 
  2116 
  2117 subsection \<open>More properties of the replicate and repeat operations\<close>
  2118 
  2119 lemma in_replicate_mset[simp]: "x \<in># replicate_mset n y \<longleftrightarrow> n > 0 \<and> x = y"
  2120   unfolding replicate_mset_def by (induct n) auto
  2121 
  2122 lemma set_mset_replicate_mset_subset[simp]: "set_mset (replicate_mset n x) = (if n = 0 then {} else {x})"
  2123   by (auto split: if_splits)
  2124 
  2125 lemma size_replicate_mset[simp]: "size (replicate_mset n M) = n"
  2126   by (induct n, simp_all)
  2127 
  2128 lemma count_le_replicate_mset_subset_eq: "n \<le> count M x \<longleftrightarrow> replicate_mset n x \<subseteq># M"
  2129   by (auto simp add: mset_subset_eqI) (metis count_replicate_mset subseteq_mset_def)
  2130 
  2131 lemma filter_eq_replicate_mset: "{#y \<in># D. y = x#} = replicate_mset (count D x) x"
  2132   by (induct D) simp_all
  2133 
  2134 lemma replicate_count_mset_eq_filter_eq: "replicate (count (mset xs) k) k = filter (HOL.eq k) xs"
  2135   by (induct xs) auto
  2136 
  2137 lemma replicate_mset_eq_empty_iff [simp]: "replicate_mset n a = {#} \<longleftrightarrow> n = 0"
  2138   by (induct n) simp_all
  2139 
  2140 lemma replicate_mset_eq_iff:
  2141   "replicate_mset m a = replicate_mset n b \<longleftrightarrow> m = 0 \<and> n = 0 \<or> m = n \<and> a = b"
  2142   by (auto simp add: multiset_eq_iff)
  2143 
  2144 lemma repeat_mset_cancel1: "repeat_mset a A = repeat_mset a B \<longleftrightarrow> A = B \<or> a = 0"
  2145   by (auto simp: multiset_eq_iff)
  2146 
  2147 lemma repeat_mset_cancel2: "repeat_mset a A = repeat_mset b A \<longleftrightarrow> a = b \<or> A = {#}"
  2148   by (auto simp: multiset_eq_iff)
  2149 
  2150 lemma repeat_mset_eq_empty_iff: "repeat_mset n A = {#} \<longleftrightarrow> n = 0 \<or> A = {#}"
  2151   by (cases n) auto
  2152 
  2153 lemma image_replicate_mset [simp]:
  2154   "image_mset f (replicate_mset n a) = replicate_mset n (f a)"
  2155   by (induct n) simp_all
  2156 
  2157 lemma replicate_mset_msubseteq_iff:
  2158   "replicate_mset m a \<subseteq># replicate_mset n b \<longleftrightarrow> m = 0 \<or> a = b \<and> m \<le> n"
  2159   by (cases m)
  2160     (auto simp: insert_subset_eq_iff simp flip: count_le_replicate_mset_subset_eq)
  2161 
  2162 lemma msubseteq_replicate_msetE:
  2163   assumes "A \<subseteq># replicate_mset n a"
  2164   obtains m where "m \<le> n" and "A = replicate_mset m a"
  2165 proof (cases "n = 0")
  2166   case True
  2167   with assms that show thesis
  2168     by simp
  2169 next
  2170   case False
  2171   from assms have "set_mset A \<subseteq> set_mset (replicate_mset n a)"
  2172     by (rule set_mset_mono)
  2173   with False have "set_mset A \<subseteq> {a}"
  2174     by simp
  2175   then have "\<exists>m. A = replicate_mset m a"
  2176   proof (induction A)
  2177     case empty
  2178     then show ?case
  2179       by simp
  2180   next
  2181     case (add b A)
  2182     then obtain m where "A = replicate_mset m a"
  2183       by auto
  2184     with add.prems show ?case
  2185       by (auto intro: exI [of _ "Suc m"])
  2186   qed
  2187   then obtain m where A: "A = replicate_mset m a" ..
  2188   with assms have "m \<le> n"
  2189     by (auto simp add: replicate_mset_msubseteq_iff)
  2190   then show thesis using A ..
  2191 qed
  2192 
  2193 
  2194 subsection \<open>Big operators\<close>
  2195 
  2196 locale comm_monoid_mset = comm_monoid
  2197 begin
  2198 
  2199 interpretation comp_fun_commute f
  2200   by standard (simp add: fun_eq_iff left_commute)
  2201 
  2202 interpretation comp?: comp_fun_commute "f \<circ> g"
  2203   by (fact comp_comp_fun_commute)
  2204 
  2205 context
  2206 begin
  2207 
  2208 definition F :: "'a multiset \<Rightarrow> 'a"
  2209   where eq_fold: "F M = fold_mset f \<^bold>1 M"
  2210 
  2211 lemma empty [simp]: "F {#} = \<^bold>1"
  2212   by (simp add: eq_fold)
  2213 
  2214 lemma singleton [simp]: "F {#x#} = x"
  2215 proof -
  2216   interpret comp_fun_commute
  2217     by standard (simp add: fun_eq_iff left_commute)
  2218   show ?thesis by (simp add: eq_fold)
  2219 qed
  2220 
  2221 lemma union [simp]: "F (M + N) = F M \<^bold>* F N"
  2222 proof -
  2223   interpret comp_fun_commute f
  2224     by standard (simp add: fun_eq_iff left_commute)
  2225   show ?thesis
  2226     by (induct N) (simp_all add: left_commute eq_fold)
  2227 qed
  2228 
  2229 lemma add_mset [simp]: "F (add_mset x N) = x \<^bold>* F N"
  2230   unfolding add_mset_add_single[of x N] union by (simp add: ac_simps)
  2231 
  2232 lemma insert [simp]:
  2233   shows "F (image_mset g (add_mset x A)) = g x \<^bold>* F (image_mset g A)"
  2234   by (simp add: eq_fold)
  2235 
  2236 lemma remove:
  2237   assumes "x \<in># A"
  2238   shows "F A = x \<^bold>* F (A - {#x#})"
  2239   using multi_member_split[OF assms] by auto
  2240 
  2241 lemma neutral:
  2242   "\<forall>x\<in>#A. x = \<^bold>1 \<Longrightarrow> F A = \<^bold>1"
  2243   by (induct A) simp_all
  2244 
  2245 lemma neutral_const [simp]:
  2246   "F (image_mset (\<lambda>_. \<^bold>1) A) = \<^bold>1"
  2247   by (simp add: neutral)
  2248 
  2249 private lemma F_image_mset_product:
  2250   "F {#g x j \<^bold>* F {#g i j. i \<in># A#}. j \<in># B#} =
  2251     F (image_mset (g x) B) \<^bold>* F {#F {#g i j. i \<in># A#}. j \<in># B#}"
  2252   by (induction B) (simp_all add: left_commute semigroup.assoc semigroup_axioms)
  2253 
  2254 lemma swap:
  2255   "F (image_mset (\<lambda>i. F (image_mset (g i) B)) A) =
  2256     F (image_mset (\<lambda>j. F (image_mset (\<lambda>i. g i j) A)) B)"
  2257   apply (induction A, simp)
  2258   apply (induction B, auto simp add: F_image_mset_product ac_simps)
  2259   done
  2260 
  2261 lemma distrib: "F (image_mset (\<lambda>x. g x \<^bold>* h x) A) = F (image_mset g A) \<^bold>* F (image_mset h A)"
  2262   by (induction A) (auto simp: ac_simps)
  2263 
  2264 lemma union_disjoint:
  2265   "A \<inter># B = {#} \<Longrightarrow> F (image_mset g (A \<union># B)) = F (image_mset g A) \<^bold>* F (image_mset g B)"
  2266   by (induction A) (auto simp: ac_simps)
  2267 
  2268 end
  2269 end
  2270 
  2271 lemma comp_fun_commute_plus_mset[simp]: "comp_fun_commute ((+) :: 'a multiset \<Rightarrow> _ \<Rightarrow> _)"
  2272   by standard (simp add: add_ac comp_def)
  2273 
  2274 declare comp_fun_commute.fold_mset_add_mset[OF comp_fun_commute_plus_mset, simp]
  2275 
  2276 lemma in_mset_fold_plus_iff[iff]: "x \<in># fold_mset (+) M NN \<longleftrightarrow> x \<in># M \<or> (\<exists>N. N \<in># NN \<and> x \<in># N)"
  2277   by (induct NN) auto
  2278 
  2279 context comm_monoid_add
  2280 begin
  2281 
  2282 sublocale sum_mset: comm_monoid_mset plus 0
  2283   defines sum_mset = sum_mset.F ..
  2284 
  2285 lemma sum_unfold_sum_mset:
  2286   "sum f A = sum_mset (image_mset f (mset_set A))"
  2287   by (cases "finite A") (induct A rule: finite_induct, simp_all)
  2288 
  2289 end
  2290 
  2291 syntax (ASCII)
  2292   "_sum_mset_image" :: "pttrn \<Rightarrow> 'b set \<Rightarrow> 'a \<Rightarrow> 'a::comm_monoid_add"  ("(3SUM _:#_. _)" [0, 51, 10] 10)
  2293 syntax
  2294   "_sum_mset_image" :: "pttrn \<Rightarrow> 'b set \<Rightarrow> 'a \<Rightarrow> 'a::comm_monoid_add"  ("(3\<Sum>_\<in>#_. _)" [0, 51, 10] 10)
  2295 translations
  2296   "\<Sum>i \<in># A. b" \<rightleftharpoons> "CONST sum_mset (CONST image_mset (\<lambda>i. b) A)"
  2297 
  2298 context comm_monoid_add
  2299 begin
  2300 
  2301 lemma sum_mset_sum_list:
  2302   "sum_mset (mset xs) = sum_list xs"
  2303   by (induction xs) auto
  2304 
  2305 end
  2306 
  2307 context canonically_ordered_monoid_add
  2308 begin
  2309 
  2310 lemma sum_mset_0_iff [simp]:
  2311   "sum_mset M = 0  \<longleftrightarrow> (\<forall>x \<in> set_mset M. x = 0)"
  2312   by (induction M) auto
  2313 
  2314 end
  2315 
  2316 context ordered_comm_monoid_add
  2317 begin
  2318 
  2319 lemma sum_mset_mono:
  2320   "sum_mset (image_mset f K) \<le> sum_mset (image_mset g K)"
  2321   if "\<And>i. i \<in># K \<Longrightarrow> f i \<le> g i"
  2322   using that by (induction K) (simp_all add: add_mono)
  2323 
  2324 end
  2325 
  2326 context ordered_cancel_comm_monoid_diff
  2327 begin
  2328 
  2329 lemma sum_mset_diff:
  2330   "sum_mset (M - N) = sum_mset M - sum_mset N" if "N \<subseteq># M" for M N :: "'a multiset"
  2331   using that by (auto simp add: subset_mset.le_iff_add)
  2332 
  2333 end
  2334 
  2335 context semiring_0
  2336 begin
  2337 
  2338 lemma sum_mset_distrib_left:
  2339   "c * (\<Sum>x \<in># M. f x) = (\<Sum>x \<in># M. c * f(x))"
  2340   by (induction M) (simp_all add: algebra_simps)
  2341 
  2342 lemma sum_mset_distrib_right:
  2343   "(\<Sum>x \<in># M. f x) * c = (\<Sum>x \<in># M. f x * c)"
  2344   by (induction M) (simp_all add: algebra_simps)
  2345 
  2346 end
  2347 
  2348 lemma sum_mset_product:
  2349   fixes f :: "'a::{comm_monoid_add,times} \<Rightarrow> 'b::semiring_0"
  2350   shows "(\<Sum>i \<in># A. f i) * (\<Sum>i \<in># B. g i) = (\<Sum>i\<in>#A. \<Sum>j\<in>#B. f i * g j)"
  2351   by (subst sum_mset.swap) (simp add: sum_mset_distrib_left sum_mset_distrib_right)
  2352 
  2353 context semiring_1
  2354 begin
  2355 
  2356 lemma sum_mset_replicate_mset [simp]:
  2357   "sum_mset (replicate_mset n a) = of_nat n * a"
  2358   by (induction n) (simp_all add: algebra_simps)
  2359 
  2360 lemma sum_mset_delta:
  2361   "sum_mset (image_mset (\<lambda>x. if x = y then c else 0) A) = c * of_nat (count A y)"
  2362   by (induction A) (simp_all add: algebra_simps)
  2363 
  2364 lemma sum_mset_delta':
  2365   "sum_mset (image_mset (\<lambda>x. if y = x then c else 0) A) = c * of_nat (count A y)"
  2366   by (induction A) (simp_all add: algebra_simps)
  2367 
  2368 end
  2369 
  2370 lemma of_nat_sum_mset [simp]:
  2371   "of_nat (sum_mset A) = sum_mset (image_mset of_nat A)"
  2372   by (induction A) auto
  2373 
  2374 lemma size_eq_sum_mset:
  2375   "size M = (\<Sum>a\<in>#M. 1)"
  2376   using image_mset_const_eq [of "1::nat" M] by simp
  2377 
  2378 lemma size_mset_set [simp]:
  2379   "size (mset_set A) = card A"
  2380   by (simp only: size_eq_sum_mset card_eq_sum sum_unfold_sum_mset)
  2381 
  2382 lemma sum_mset_constant [simp]:
  2383   fixes y :: "'b::semiring_1"
  2384   shows \<open>(\<Sum>x\<in>#A. y) = of_nat (size A) * y\<close>
  2385   by (induction A) (auto simp: algebra_simps)
  2386 
  2387 abbreviation Union_mset :: "'a multiset multiset \<Rightarrow> 'a multiset"  ("\<Union>#")
  2388   where "\<Union># MM \<equiv> sum_mset MM" \<comment> \<open>FIXME ambiguous notation --
  2389     could likewise refer to \<open>\<Squnion>#\<close>\<close>
  2390 
  2391 lemma set_mset_Union_mset[simp]: "set_mset (\<Union># MM) = (\<Union>M \<in> set_mset MM. set_mset M)"
  2392   by (induct MM) auto
  2393 
  2394 lemma in_Union_mset_iff[iff]: "x \<in># \<Union># MM \<longleftrightarrow> (\<exists>M. M \<in># MM \<and> x \<in># M)"
  2395   by (induct MM) auto
  2396 
  2397 lemma count_sum:
  2398   "count (sum f A) x = sum (\<lambda>a. count (f a) x) A"
  2399   by (induct A rule: infinite_finite_induct) simp_all
  2400 
  2401 lemma sum_eq_empty_iff:
  2402   assumes "finite A"
  2403   shows "sum f A = {#} \<longleftrightarrow> (\<forall>a\<in>A. f a = {#})"
  2404   using assms by induct simp_all
  2405 
  2406 lemma Union_mset_empty_conv[simp]: "\<Union># M = {#} \<longleftrightarrow> (\<forall>i\<in>#M. i = {#})"
  2407   by (induction M) auto
  2408 
  2409 lemma Union_image_single_mset[simp]: "\<Union># (image_mset (\<lambda>x. {#x#}) m) = m"
  2410 by(induction m) auto
  2411 
  2412 
  2413 context comm_monoid_mult
  2414 begin
  2415 
  2416 sublocale prod_mset: comm_monoid_mset times 1
  2417   defines prod_mset = prod_mset.F ..
  2418 
  2419 lemma prod_mset_empty:
  2420   "prod_mset {#} = 1"
  2421   by (fact prod_mset.empty)
  2422 
  2423 lemma prod_mset_singleton:
  2424   "prod_mset {#x#} = x"
  2425   by (fact prod_mset.singleton)
  2426 
  2427 lemma prod_mset_Un:
  2428   "prod_mset (A + B) = prod_mset A * prod_mset B"
  2429   by (fact prod_mset.union)
  2430 
  2431 lemma prod_mset_prod_list:
  2432   "prod_mset (mset xs) = prod_list xs"
  2433   by (induct xs) auto
  2434 
  2435 lemma prod_mset_replicate_mset [simp]:
  2436   "prod_mset (replicate_mset n a) = a ^ n"
  2437   by (induct n) simp_all
  2438 
  2439 lemma prod_unfold_prod_mset:
  2440   "prod f A = prod_mset (image_mset f (mset_set A))"
  2441   by (cases "finite A") (induct A rule: finite_induct, simp_all)
  2442 
  2443 lemma prod_mset_multiplicity:
  2444   "prod_mset M = prod (\<lambda>x. x ^ count M x) (set_mset M)"
  2445   by (simp add: fold_mset_def prod.eq_fold prod_mset.eq_fold funpow_times_power comp_def)
  2446 
  2447 lemma prod_mset_delta: "prod_mset (image_mset (\<lambda>x. if x = y then c else 1) A) = c ^ count A y"
  2448   by (induction A) simp_all
  2449 
  2450 lemma prod_mset_delta': "prod_mset (image_mset (\<lambda>x. if y = x then c else 1) A) = c ^ count A y"
  2451   by (induction A) simp_all
  2452 
  2453 lemma prod_mset_subset_imp_dvd:
  2454   assumes "A \<subseteq># B"
  2455   shows   "prod_mset A dvd prod_mset B"
  2456 proof -
  2457   from assms have "B = (B - A) + A" by (simp add: subset_mset.diff_add)
  2458   also have "prod_mset \<dots> = prod_mset (B - A) * prod_mset A" by simp
  2459   also have "prod_mset A dvd \<dots>" by simp
  2460   finally show ?thesis .
  2461 qed
  2462 
  2463 lemma dvd_prod_mset:
  2464   assumes "x \<in># A"
  2465   shows "x dvd prod_mset A"
  2466   using assms prod_mset_subset_imp_dvd [of "{#x#}" A] by simp
  2467 
  2468 end
  2469 
  2470 syntax (ASCII)
  2471   "_prod_mset_image" :: "pttrn \<Rightarrow> 'b set \<Rightarrow> 'a \<Rightarrow> 'a::comm_monoid_mult"  ("(3PROD _:#_. _)" [0, 51, 10] 10)
  2472 syntax
  2473   "_prod_mset_image" :: "pttrn \<Rightarrow> 'b set \<Rightarrow> 'a \<Rightarrow> 'a::comm_monoid_mult"  ("(3\<Prod>_\<in>#_. _)" [0, 51, 10] 10)
  2474 translations
  2475   "\<Prod>i \<in># A. b" \<rightleftharpoons> "CONST prod_mset (CONST image_mset (\<lambda>i. b) A)"
  2476 
  2477 lemma prod_mset_constant [simp]: "(\<Prod>_\<in>#A. c) = c ^ size A"
  2478   by (simp add: image_mset_const_eq)
  2479 
  2480 lemma (in semidom) prod_mset_zero_iff [iff]:
  2481   "prod_mset A = 0 \<longleftrightarrow> 0 \<in># A"
  2482   by (induct A) auto
  2483 
  2484 lemma (in semidom_divide) prod_mset_diff:
  2485   assumes "B \<subseteq># A" and "0 \<notin># B"
  2486   shows "prod_mset (A - B) = prod_mset A div prod_mset B"
  2487 proof -
  2488   from assms obtain C where "A = B + C"
  2489     by (metis subset_mset.add_diff_inverse)
  2490   with assms show ?thesis by simp
  2491 qed
  2492 
  2493 lemma (in semidom_divide) prod_mset_minus:
  2494   assumes "a \<in># A" and "a \<noteq> 0"
  2495   shows "prod_mset (A - {#a#}) = prod_mset A div a"
  2496   using assms prod_mset_diff [of "{#a#}" A] by auto
  2497 
  2498 lemma (in algebraic_semidom) is_unit_prod_mset_iff:
  2499   "is_unit (prod_mset A) \<longleftrightarrow> (\<forall>x \<in># A. is_unit x)"
  2500   by (induct A) (auto simp: is_unit_mult_iff)
  2501 
  2502 lemma (in normalization_semidom) normalize_prod_mset:
  2503   "normalize (prod_mset A) = prod_mset (image_mset normalize A)"
  2504   by (induct A) (simp_all add: normalize_mult)
  2505 
  2506 lemma (in normalization_semidom) normalized_prod_msetI:
  2507   assumes "\<And>a. a \<in># A \<Longrightarrow> normalize a = a"
  2508   shows "normalize (prod_mset A) = prod_mset A"
  2509 proof -
  2510   from assms have "image_mset normalize A = A"
  2511     by (induct A) simp_all
  2512   then show ?thesis by (simp add: normalize_prod_mset)
  2513 qed
  2514 
  2515 
  2516 subsection \<open>Alternative representations\<close>
  2517 
  2518 subsubsection \<open>Lists\<close>
  2519 
  2520 context linorder
  2521 begin
  2522 
  2523 lemma mset_insort [simp]:
  2524   "mset (insort_key k x xs) = add_mset x (mset xs)"
  2525   by (induct xs) simp_all
  2526 
  2527 lemma mset_sort [simp]:
  2528   "mset (sort_key k xs) = mset xs"
  2529   by (induct xs) simp_all
  2530 
  2531 text \<open>
  2532   This lemma shows which properties suffice to show that a function
  2533   \<open>f\<close> with \<open>f xs = ys\<close> behaves like sort.
  2534 \<close>
  2535 
  2536 lemma properties_for_sort_key:
  2537   assumes "mset ys = mset xs"
  2538     and "\<And>k. k \<in> set ys \<Longrightarrow> filter (\<lambda>x. f k = f x) ys = filter (\<lambda>x. f k = f x) xs"
  2539     and "sorted (map f ys)"
  2540   shows "sort_key f xs = ys"
  2541   using assms
  2542 proof (induct xs arbitrary: ys)
  2543   case Nil then show ?case by simp
  2544 next
  2545   case (Cons x xs)
  2546   from Cons.prems(2) have
  2547     "\<forall>k \<in> set ys. filter (\<lambda>x. f k = f x) (remove1 x ys) = filter (\<lambda>x. f k = f x) xs"
  2548     by (simp add: filter_remove1)
  2549   with Cons.prems have "sort_key f xs = remove1 x ys"
  2550     by (auto intro!: Cons.hyps simp add: sorted_map_remove1)
  2551   moreover from Cons.prems have "x \<in># mset ys"
  2552     by auto
  2553   then have "x \<in> set ys"
  2554     by simp
  2555   ultimately show ?case using Cons.prems by (simp add: insort_key_remove1)
  2556 qed
  2557 
  2558 lemma properties_for_sort:
  2559   assumes multiset: "mset ys = mset xs"
  2560     and "sorted ys"
  2561   shows "sort xs = ys"
  2562 proof (rule properties_for_sort_key)
  2563   from multiset show "mset ys = mset xs" .
  2564   from \<open>sorted ys\<close> show "sorted (map (\<lambda>x. x) ys)" by simp
  2565   from multiset have "length (filter (\<lambda>y. k = y) ys) = length (filter (\<lambda>x. k = x) xs)" for k
  2566     by (rule mset_eq_length_filter)
  2567   then have "replicate (length (filter (\<lambda>y. k = y) ys)) k =
  2568     replicate (length (filter (\<lambda>x. k = x) xs)) k" for k
  2569     by simp
  2570   then show "k \<in> set ys \<Longrightarrow> filter (\<lambda>y. k = y) ys = filter (\<lambda>x. k = x) xs" for k
  2571     by (simp add: replicate_length_filter)
  2572 qed
  2573 
  2574 lemma sort_key_inj_key_eq:
  2575   assumes mset_equal: "mset xs = mset ys"
  2576     and "inj_on f (set xs)"
  2577     and "sorted (map f ys)"
  2578   shows "sort_key f xs = ys"
  2579 proof (rule properties_for_sort_key)
  2580   from mset_equal
  2581   show "mset ys = mset xs" by simp
  2582   from \<open>sorted (map f ys)\<close>
  2583   show "sorted (map f ys)" .
  2584   show "[x\<leftarrow>ys . f k = f x] = [x\<leftarrow>xs . f k = f x]" if "k \<in> set ys" for k
  2585   proof -
  2586     from mset_equal
  2587     have set_equal: "set xs = set ys" by (rule mset_eq_setD)
  2588     with that have "insert k (set ys) = set ys" by auto
  2589     with \<open>inj_on f (set xs)\<close> have inj: "inj_on f (insert k (set ys))"
  2590       by (simp add: set_equal)
  2591     from inj have "[x\<leftarrow>ys . f k = f x] = filter (HOL.eq k) ys"
  2592       by (auto intro!: inj_on_filter_key_eq)
  2593     also have "\<dots> = replicate (count (mset ys) k) k"
  2594       by (simp add: replicate_count_mset_eq_filter_eq)
  2595     also have "\<dots> = replicate (count (mset xs) k) k"
  2596       using mset_equal by simp
  2597     also have "\<dots> = filter (HOL.eq k) xs"
  2598       by (simp add: replicate_count_mset_eq_filter_eq)
  2599     also have "\<dots> = [x\<leftarrow>xs . f k = f x]"
  2600       using inj by (auto intro!: inj_on_filter_key_eq [symmetric] simp add: set_equal)
  2601     finally show ?thesis .
  2602   qed
  2603 qed
  2604 
  2605 lemma sort_key_eq_sort_key:
  2606   assumes "mset xs = mset ys"
  2607     and "inj_on f (set xs)"
  2608   shows "sort_key f xs = sort_key f ys"
  2609   by (rule sort_key_inj_key_eq) (simp_all add: assms)
  2610 
  2611 lemma sort_key_by_quicksort:
  2612   "sort_key f xs = sort_key f [x\<leftarrow>xs. f x < f (xs ! (length xs div 2))]
  2613     @ [x\<leftarrow>xs. f x = f (xs ! (length xs div 2))]
  2614     @ sort_key f [x\<leftarrow>xs. f x > f (xs ! (length xs div 2))]" (is "sort_key f ?lhs = ?rhs")
  2615 proof (rule properties_for_sort_key)
  2616   show "mset ?rhs = mset ?lhs"
  2617     by (rule multiset_eqI) auto
  2618   show "sorted (map f ?rhs)"
  2619     by (auto simp add: sorted_append intro: sorted_map_same)
  2620 next
  2621   fix l
  2622   assume "l \<in> set ?rhs"
  2623   let ?pivot = "f (xs ! (length xs div 2))"
  2624   have *: "\<And>x. f l = f x \<longleftrightarrow> f x = f l" by auto
  2625   have "[x \<leftarrow> sort_key f xs . f x = f l] = [x \<leftarrow> xs. f x = f l]"
  2626     unfolding filter_sort by (rule properties_for_sort_key) (auto intro: sorted_map_same)
  2627   with * have **: "[x \<leftarrow> sort_key f xs . f l = f x] = [x \<leftarrow> xs. f l = f x]" by simp
  2628   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
  2629   then have "\<And>P. [x \<leftarrow> sort_key f xs . P (f x) ?pivot \<and> f l = f x] =
  2630     [x \<leftarrow> sort_key f xs. P (f l) ?pivot \<and> f l = f x]" by simp
  2631   note *** = this [of "(<)"] this [of "(>)"] this [of "(=)"]
  2632   show "[x \<leftarrow> ?rhs. f l = f x] = [x \<leftarrow> ?lhs. f l = f x]"
  2633   proof (cases "f l" ?pivot rule: linorder_cases)
  2634     case less
  2635     then have "f l \<noteq> ?pivot" and "\<not> f l > ?pivot" by auto
  2636     with less show ?thesis
  2637       by (simp add: filter_sort [symmetric] ** ***)
  2638   next
  2639     case equal then show ?thesis
  2640       by (simp add: * less_le)
  2641   next
  2642     case greater
  2643     then have "f l \<noteq> ?pivot" and "\<not> f l < ?pivot" by auto
  2644     with greater show ?thesis
  2645       by (simp add: filter_sort [symmetric] ** ***)
  2646   qed
  2647 qed
  2648 
  2649 lemma sort_by_quicksort:
  2650   "sort xs = sort [x\<leftarrow>xs. x < xs ! (length xs div 2)]
  2651     @ [x\<leftarrow>xs. x = xs ! (length xs div 2)]
  2652     @ sort [x\<leftarrow>xs. x > xs ! (length xs div 2)]" (is "sort ?lhs = ?rhs")
  2653   using sort_key_by_quicksort [of "\<lambda>x. x", symmetric] by simp
  2654 
  2655 text \<open>A stable parameterized quicksort\<close>
  2656 
  2657 definition part :: "('b \<Rightarrow> 'a) \<Rightarrow> 'a \<Rightarrow> 'b list \<Rightarrow> 'b list \<times> 'b list \<times> 'b list" where
  2658   "part f pivot xs = ([x \<leftarrow> xs. f x < pivot], [x \<leftarrow> xs. f x = pivot], [x \<leftarrow> xs. pivot < f x])"
  2659 
  2660 lemma part_code [code]:
  2661   "part f pivot [] = ([], [], [])"
  2662   "part f pivot (x # xs) = (let (lts, eqs, gts) = part f pivot xs; x' = f x in
  2663      if x' < pivot then (x # lts, eqs, gts)
  2664      else if x' > pivot then (lts, eqs, x # gts)
  2665      else (lts, x # eqs, gts))"
  2666   by (auto simp add: part_def Let_def split_def)
  2667 
  2668 lemma sort_key_by_quicksort_code [code]:
  2669   "sort_key f xs =
  2670     (case xs of
  2671       [] \<Rightarrow> []
  2672     | [x] \<Rightarrow> xs
  2673     | [x, y] \<Rightarrow> (if f x \<le> f y then xs else [y, x])
  2674     | _ \<Rightarrow>
  2675         let (lts, eqs, gts) = part f (f (xs ! (length xs div 2))) xs
  2676         in sort_key f lts @ eqs @ sort_key f gts)"
  2677 proof (cases xs)
  2678   case Nil then show ?thesis by simp
  2679 next
  2680   case (Cons _ ys) note hyps = Cons show ?thesis
  2681   proof (cases ys)
  2682     case Nil with hyps show ?thesis by simp
  2683   next
  2684     case (Cons _ zs) note hyps = hyps Cons show ?thesis
  2685     proof (cases zs)
  2686       case Nil with hyps show ?thesis by auto
  2687     next
  2688       case Cons
  2689       from sort_key_by_quicksort [of f xs]
  2690       have "sort_key f xs = (let (lts, eqs, gts) = part f (f (xs ! (length xs div 2))) xs
  2691         in sort_key f lts @ eqs @ sort_key f gts)"
  2692       by (simp only: split_def Let_def part_def fst_conv snd_conv)
  2693       with hyps Cons show ?thesis by (simp only: list.cases)
  2694     qed
  2695   qed
  2696 qed
  2697 
  2698 end
  2699 
  2700 hide_const (open) part
  2701 
  2702 lemma mset_remdups_subset_eq: "mset (remdups xs) \<subseteq># mset xs"
  2703   by (induct xs) (auto intro: subset_mset.order_trans)
  2704 
  2705 lemma mset_update:
  2706   "i < length ls \<Longrightarrow> mset (ls[i := v]) = add_mset v (mset ls - {#ls ! i#})"
  2707 proof (induct ls arbitrary: i)
  2708   case Nil then show ?case by simp
  2709 next
  2710   case (Cons x xs)
  2711   show ?case
  2712   proof (cases i)
  2713     case 0 then show ?thesis by simp
  2714   next
  2715     case (Suc i')
  2716     with Cons show ?thesis
  2717       by (cases \<open>x = xs ! i'\<close>) auto
  2718   qed
  2719 qed
  2720 
  2721 lemma mset_swap:
  2722   "i < length ls \<Longrightarrow> j < length ls \<Longrightarrow>
  2723     mset (ls[j := ls ! i, i := ls ! j]) = mset ls"
  2724   by (cases "i = j") (simp_all add: mset_update nth_mem_mset)
  2725 
  2726 
  2727 subsection \<open>The multiset order\<close>
  2728 
  2729 subsubsection \<open>Well-foundedness\<close>
  2730 
  2731 definition mult1 :: "('a \<times> 'a) set \<Rightarrow> ('a multiset \<times> 'a multiset) set" where
  2732   "mult1 r = {(N, M). \<exists>a M0 K. M = add_mset a M0 \<and> N = M0 + K \<and>
  2733       (\<forall>b. b \<in># K \<longrightarrow> (b, a) \<in> r)}"
  2734 
  2735 definition mult :: "('a \<times> 'a) set \<Rightarrow> ('a multiset \<times> 'a multiset) set" where
  2736   "mult r = (mult1 r)\<^sup>+"
  2737 
  2738 lemma mult1I:
  2739   assumes "M = add_mset a M0" and "N = M0 + K" and "\<And>b. b \<in># K \<Longrightarrow> (b, a) \<in> r"
  2740   shows "(N, M) \<in> mult1 r"
  2741   using assms unfolding mult1_def by blast
  2742 
  2743 lemma mult1E:
  2744   assumes "(N, M) \<in> mult1 r"
  2745   obtains a M0 K where "M = add_mset a M0" "N = M0 + K" "\<And>b. b \<in># K \<Longrightarrow> (b, a) \<in> r"
  2746   using assms unfolding mult1_def by blast
  2747 
  2748 lemma mono_mult1:
  2749   assumes "r \<subseteq> r'" shows "mult1 r \<subseteq> mult1 r'"
  2750 unfolding mult1_def using assms by blast
  2751 
  2752 lemma mono_mult:
  2753   assumes "r \<subseteq> r'" shows "mult r \<subseteq> mult r'"
  2754 unfolding mult_def using mono_mult1[OF assms] trancl_mono by blast
  2755 
  2756 lemma not_less_empty [iff]: "(M, {#}) \<notin> mult1 r"
  2757 by (simp add: mult1_def)
  2758 
  2759 lemma less_add:
  2760   assumes mult1: "(N, add_mset a M0) \<in> mult1 r"
  2761   shows
  2762     "(\<exists>M. (M, M0) \<in> mult1 r \<and> N = add_mset a M) \<or>
  2763      (\<exists>K. (\<forall>b. b \<in># K \<longrightarrow> (b, a) \<in> r) \<and> N = M0 + K)"
  2764 proof -
  2765   let ?r = "\<lambda>K a. \<forall>b. b \<in># K \<longrightarrow> (b, a) \<in> r"
  2766   let ?R = "\<lambda>N M. \<exists>a M0 K. M = add_mset a M0 \<and> N = M0 + K \<and> ?r K a"
  2767   obtain a' M0' K where M0: "add_mset a M0 = add_mset a' M0'"
  2768     and N: "N = M0' + K"
  2769     and r: "?r K a'"
  2770     using mult1 unfolding mult1_def by auto
  2771   show ?thesis (is "?case1 \<or> ?case2")
  2772   proof -
  2773     from M0 consider "M0 = M0'" "a = a'"
  2774       | K' where "M0 = add_mset a' K'" "M0' = add_mset a K'"
  2775       by atomize_elim (simp only: add_eq_conv_ex)
  2776     then show ?thesis
  2777     proof cases
  2778       case 1
  2779       with N r have "?r K a \<and> N = M0 + K" by simp
  2780       then have ?case2 ..
  2781       then show ?thesis ..
  2782     next
  2783       case 2
  2784       from N 2(2) have n: "N = add_mset a (K' + K)" by simp
  2785       with r 2(1) have "?R (K' + K) M0" by blast
  2786       with n have ?case1 by (simp add: mult1_def)
  2787       then show ?thesis ..
  2788     qed
  2789   qed
  2790 qed
  2791 
  2792 lemma all_accessible:
  2793   assumes "wf r"
  2794   shows "\<forall>M. M \<in> Wellfounded.acc (mult1 r)"
  2795 proof
  2796   let ?R = "mult1 r"
  2797   let ?W = "Wellfounded.acc ?R"
  2798   {
  2799     fix M M0 a
  2800     assume M0: "M0 \<in> ?W"
  2801       and wf_hyp: "\<And>b. (b, a) \<in> r \<Longrightarrow> (\<forall>M \<in> ?W. add_mset b M \<in> ?W)"
  2802       and acc_hyp: "\<forall>M. (M, M0) \<in> ?R \<longrightarrow> add_mset a M \<in> ?W"
  2803     have "add_mset a M0 \<in> ?W"
  2804     proof (rule accI [of "add_mset a M0"])
  2805       fix N
  2806       assume "(N, add_mset a M0) \<in> ?R"
  2807       then consider M where "(M, M0) \<in> ?R" "N = add_mset a M"
  2808         | K where "\<forall>b. b \<in># K \<longrightarrow> (b, a) \<in> r" "N = M0 + K"
  2809         by atomize_elim (rule less_add)
  2810       then show "N \<in> ?W"
  2811       proof cases
  2812         case 1
  2813         from acc_hyp have "(M, M0) \<in> ?R \<longrightarrow> add_mset a M \<in> ?W" ..
  2814         from this and \<open>(M, M0) \<in> ?R\<close> have "add_mset a M \<in> ?W" ..
  2815         then show "N \<in> ?W" by (simp only: \<open>N = add_mset a M\<close>)
  2816       next
  2817         case 2
  2818         from this(1) have "M0 + K \<in> ?W"
  2819         proof (induct K)
  2820           case empty
  2821           from M0 show "M0 + {#} \<in> ?W" by simp
  2822         next
  2823           case (add x K)
  2824           from add.prems have "(x, a) \<in> r" by simp
  2825           with wf_hyp have "\<forall>M \<in> ?W. add_mset x M \<in> ?W" by blast
  2826           moreover from add have "M0 + K \<in> ?W" by simp
  2827           ultimately have "add_mset x (M0 + K) \<in> ?W" ..
  2828           then show "M0 + (add_mset x K) \<in> ?W" by simp
  2829         qed
  2830         then show "N \<in> ?W" by (simp only: 2(2))
  2831       qed
  2832     qed
  2833   } note tedious_reasoning = this
  2834 
  2835   show "M \<in> ?W" for M
  2836   proof (induct M)
  2837     show "{#} \<in> ?W"
  2838     proof (rule accI)
  2839       fix b assume "(b, {#}) \<in> ?R"
  2840       with not_less_empty show "b \<in> ?W" by contradiction
  2841     qed
  2842 
  2843     fix M a assume "M \<in> ?W"
  2844     from \<open>wf r\<close> have "\<forall>M \<in> ?W. add_mset a M \<in> ?W"
  2845     proof induct
  2846       fix a
  2847       assume r: "\<And>b. (b, a) \<in> r \<Longrightarrow> (\<forall>M \<in> ?W. add_mset b M \<in> ?W)"
  2848       show "\<forall>M \<in> ?W. add_mset a M \<in> ?W"
  2849       proof
  2850         fix M assume "M \<in> ?W"
  2851         then show "add_mset a M \<in> ?W"
  2852           by (rule acc_induct) (rule tedious_reasoning [OF _ r])
  2853       qed
  2854     qed
  2855     from this and \<open>M \<in> ?W\<close> show "add_mset a M \<in> ?W" ..
  2856   qed
  2857 qed
  2858 
  2859 theorem wf_mult1: "wf r \<Longrightarrow> wf (mult1 r)"
  2860 by (rule acc_wfI) (rule all_accessible)
  2861 
  2862 theorem wf_mult: "wf r \<Longrightarrow> wf (mult r)"
  2863 unfolding mult_def by (rule wf_trancl) (rule wf_mult1)
  2864 
  2865 
  2866 subsubsection \<open>Closure-free presentation\<close>
  2867 
  2868 text \<open>One direction.\<close>
  2869 lemma mult_implies_one_step:
  2870   assumes
  2871     trans: "trans r" and
  2872     MN: "(M, N) \<in> mult r"
  2873   shows "\<exists>I J K. N = I + J \<and> M = I + K \<and> J \<noteq> {#} \<and> (\<forall>k \<in> set_mset K. \<exists>j \<in> set_mset J. (k, j) \<in> r)"
  2874   using MN unfolding mult_def mult1_def
  2875 proof (induction rule: converse_trancl_induct)
  2876   case (base y)
  2877   then show ?case by force
  2878 next
  2879   case (step y z) note yz = this(1) and zN = this(2) and N_decomp = this(3)
  2880   obtain I J K where
  2881     N: "N = I + J" "z = I + K" "J \<noteq> {#}" "\<forall>k\<in>#K. \<exists>j\<in>#J. (k, j) \<in> r"
  2882     using N_decomp by blast
  2883   obtain a M0 K' where
  2884     z: "z = add_mset a M0" and y: "y = M0 + K'" and K: "\<forall>b. b \<in># K' \<longrightarrow> (b, a) \<in> r"
  2885     using yz by blast
  2886   show ?case
  2887   proof (cases "a \<in># K")
  2888     case True
  2889     moreover have "\<exists>j\<in>#J. (k, j) \<in> r" if "k \<in># K'" for k
  2890       using K N trans True by (meson that transE)
  2891     ultimately show ?thesis
  2892       by (rule_tac x = I in exI, rule_tac x = J in exI, rule_tac x = "(K - {#a#}) + K'" in exI)
  2893         (use z y N in \<open>auto simp del: subset_mset.add_diff_assoc2 dest: in_diffD\<close>)
  2894   next
  2895     case False
  2896     then have "a \<in># I" by (metis N(2) union_iff union_single_eq_member z)
  2897     moreover have "M0 = I + K - {#a#}"
  2898       using N(2) z by force
  2899     ultimately show ?thesis
  2900       by (rule_tac x = "I - {#a#}" in exI, rule_tac x = "add_mset a J" in exI,
  2901           rule_tac x = "K + K'" in exI)
  2902         (use z y N False K in \<open>auto simp: add.assoc\<close>)
  2903   qed
  2904 qed
  2905 
  2906 lemma one_step_implies_mult:
  2907   assumes
  2908     "J \<noteq> {#}" and
  2909     "\<forall>k \<in> set_mset K. \<exists>j \<in> set_mset J. (k, j) \<in> r"
  2910   shows "(I + K, I + J) \<in> mult r"
  2911   using assms
  2912 proof (induction "size J" arbitrary: I J K)
  2913   case 0
  2914   then show ?case by auto
  2915 next
  2916   case (Suc n) note IH = this(1) and size_J = this(2)[THEN sym]
  2917   obtain J' a where J: "J = add_mset a J'"
  2918     using size_J by (blast dest: size_eq_Suc_imp_eq_union)
  2919   show ?case
  2920   proof (cases "J' = {#}")
  2921     case True
  2922     then show ?thesis
  2923       using J Suc by (fastforce simp add: mult_def mult1_def)
  2924   next
  2925     case [simp]: False
  2926     have K: "K = {#x \<in># K. (x, a) \<in> r#} + {#x \<in># K. (x, a) \<notin> r#}"
  2927       by simp
  2928     have "(I + K, (I + {# x \<in># K. (x, a) \<in> r #}) + J') \<in> mult r"
  2929       using IH[of J' "{# x \<in># K. (x, a) \<notin> r#}" "I + {# x \<in># K. (x, a) \<in> r#}"]
  2930         J Suc.prems K size_J by (auto simp: ac_simps)
  2931     moreover have "(I + {#x \<in># K. (x, a) \<in> r#} + J', I + J) \<in> mult r"
  2932       by (fastforce simp: J mult1_def mult_def)
  2933     ultimately show ?thesis
  2934       unfolding mult_def by simp
  2935   qed
  2936 qed
  2937 
  2938 lemma subset_implies_mult:
  2939   assumes sub: "A \<subset># B"
  2940   shows "(A, B) \<in> mult r"
  2941 proof -
  2942   have ApBmA: "A + (B - A) = B"
  2943     using sub by simp
  2944   have BmA: "B - A \<noteq> {#}"
  2945     using sub by (simp add: Diff_eq_empty_iff_mset subset_mset.less_le_not_le)
  2946   thus ?thesis
  2947     by (rule one_step_implies_mult[of "B - A" "{#}" _ A, unfolded ApBmA, simplified])
  2948 qed
  2949 
  2950 
  2951 subsection \<open>The multiset extension is cancellative for multiset union\<close>
  2952 
  2953 lemma mult_cancel:
  2954   assumes "trans s" and "irrefl s"
  2955   shows "(X + Z, Y + Z) \<in> mult s \<longleftrightarrow> (X, Y) \<in> mult s" (is "?L \<longleftrightarrow> ?R")
  2956 proof
  2957   assume ?L thus ?R
  2958   proof (induct Z)
  2959     case (add z Z)
  2960     obtain X' Y' Z' where *: "add_mset z X + Z = Z' + X'" "add_mset z Y + Z = Z' + Y'" "Y' \<noteq> {#}"
  2961       "\<forall>x \<in> set_mset X'. \<exists>y \<in> set_mset Y'. (x, y) \<in> s"
  2962       using mult_implies_one_step[OF \<open>trans s\<close> add(2)] by auto
  2963     consider Z2 where "Z' = add_mset z Z2" | X2 Y2 where "X' = add_mset z X2" "Y' = add_mset z Y2"
  2964       using *(1,2) by (metis add_mset_remove_trivial_If insert_iff set_mset_add_mset_insert union_iff)
  2965     thus ?case
  2966     proof (cases)
  2967       case 1 thus ?thesis using * one_step_implies_mult[of Y' X' s Z2]
  2968         by (auto simp: add.commute[of _ "{#_#}"] add.assoc intro: add(1))
  2969     next
  2970       case 2 then obtain y where "y \<in> set_mset Y2" "(z, y) \<in> s" using *(4) \<open>irrefl s\<close>
  2971         by (auto simp: irrefl_def)
  2972       moreover from this transD[OF \<open>trans s\<close> _ this(2)]
  2973       have "x' \<in> set_mset X2 \<Longrightarrow> \<exists>y \<in> set_mset Y2. (x', y) \<in> s" for x'
  2974         using 2 *(4)[rule_format, of x'] by auto
  2975       ultimately show ?thesis using  * one_step_implies_mult[of Y2 X2 s Z'] 2
  2976         by (force simp: add.commute[of "{#_#}"] add.assoc[symmetric] intro: add(1))
  2977     qed
  2978   qed auto
  2979 next
  2980   assume ?R then obtain I J K
  2981     where "Y = I + J" "X = I + K" "J \<noteq> {#}" "\<forall>k \<in> set_mset K. \<exists>j \<in> set_mset J. (k, j) \<in> s"
  2982     using mult_implies_one_step[OF \<open>trans s\<close>] by blast
  2983   thus ?L using one_step_implies_mult[of J K s "I + Z"] by (auto simp: ac_simps)
  2984 qed
  2985 
  2986 lemmas mult_cancel_add_mset =
  2987   mult_cancel[of _ _ "{#_#}", unfolded union_mset_add_mset_right add.comm_neutral]
  2988 
  2989 lemma mult_cancel_max:
  2990   assumes "trans s" and "irrefl s"
  2991   shows "(X, Y) \<in> mult s \<longleftrightarrow> (X - X \<inter># Y, Y - X \<inter># Y) \<in> mult s" (is "?L \<longleftrightarrow> ?R")
  2992 proof -
  2993   have "X - X \<inter># Y + X \<inter># Y = X" "Y - X \<inter># Y + X \<inter># Y = Y" by (auto simp flip: count_inject)
  2994   thus ?thesis using mult_cancel[OF assms, of "X - X \<inter># Y"  "X \<inter># Y" "Y - X \<inter># Y"] by auto
  2995 qed
  2996 
  2997 
  2998 subsection \<open>Quasi-executable version of the multiset extension\<close>
  2999 
  3000 text \<open>
  3001   Predicate variants of \<open>mult\<close> and the reflexive closure of \<open>mult\<close>, which are
  3002   executable whenever the given predicate \<open>P\<close> is. Together with the standard
  3003   code equations for \<open>(\<inter>#\<close>) and \<open>(-\<close>) this should yield quadratic
  3004   (with respect to calls to \<open>P\<close>) implementations of \<open>multp\<close> and \<open>multeqp\<close>.
  3005 \<close>
  3006 
  3007 definition multp :: "('a \<Rightarrow> 'a \<Rightarrow> bool) \<Rightarrow> 'a multiset \<Rightarrow> 'a multiset \<Rightarrow> bool" where
  3008   "multp P N M =
  3009     (let Z = M \<inter># N; X = M - Z in
  3010     X \<noteq> {#} \<and> (let Y = N - Z in (\<forall>y \<in> set_mset Y. \<exists>x \<in> set_mset X. P y x)))"
  3011 
  3012 definition multeqp :: "('a \<Rightarrow> 'a \<Rightarrow> bool) \<Rightarrow> 'a multiset \<Rightarrow> 'a multiset \<Rightarrow> bool" where
  3013   "multeqp P N M =
  3014     (let Z = M \<inter># N; X = M - Z; Y = N - Z in
  3015     (\<forall>y \<in> set_mset Y. \<exists>x \<in> set_mset X. P y x))"
  3016 
  3017 lemma multp_iff:
  3018   assumes "irrefl R" and "trans R" and [simp]: "\<And>x y. P x y \<longleftrightarrow> (x, y) \<in> R"
  3019   shows "multp P N M \<longleftrightarrow> (N, M) \<in> mult R" (is "?L \<longleftrightarrow> ?R")
  3020 proof -
  3021   have *: "M \<inter># N + (N - M \<inter># N) = N" "M \<inter># N + (M - M \<inter># N) = M"
  3022     "(M - M \<inter># N) \<inter># (N - M \<inter># N) = {#}" by (auto simp flip: count_inject)
  3023   show ?thesis
  3024   proof
  3025     assume ?L thus ?R
  3026       using one_step_implies_mult[of "M - M \<inter># N" "N - M \<inter># N" R "M \<inter># N"] *
  3027       by (auto simp: multp_def Let_def)
  3028   next
  3029     { fix I J K :: "'a multiset" assume "(I + J) \<inter># (I + K) = {#}"
  3030       then have "I = {#}" by (metis inter_union_distrib_right union_eq_empty)
  3031     } note [dest!] = this
  3032     assume ?R thus ?L
  3033       using mult_implies_one_step[OF assms(2), of "N - M \<inter># N" "M - M \<inter># N"]
  3034         mult_cancel_max[OF assms(2,1), of "N" "M"] * by (auto simp: multp_def)
  3035   qed
  3036 qed
  3037 
  3038 lemma multeqp_iff:
  3039   assumes "irrefl R" and "trans R" and "\<And>x y. P x y \<longleftrightarrow> (x, y) \<in> R"
  3040   shows "multeqp P N M \<longleftrightarrow> (N, M) \<in> (mult R)\<^sup>="
  3041 proof -
  3042   { assume "N \<noteq> M" "M - M \<inter># N = {#}"
  3043     then obtain y where "count N y \<noteq> count M y" by (auto simp flip: count_inject)
  3044     then have "\<exists>y. count M y < count N y" using \<open>M - M \<inter># N = {#}\<close>
  3045       by (auto simp flip: count_inject dest!: le_neq_implies_less fun_cong[of _ _ y])
  3046   }
  3047   then have "multeqp P N M \<longleftrightarrow> multp P N M \<or> N = M"
  3048     by (auto simp: multeqp_def multp_def Let_def in_diff_count)
  3049   thus ?thesis using multp_iff[OF assms] by simp
  3050 qed
  3051 
  3052 
  3053 subsubsection \<open>Partial-order properties\<close>
  3054 
  3055 lemma (in preorder) mult1_lessE:
  3056   assumes "(N, M) \<in> mult1 {(a, b). a < b}"
  3057   obtains a M0 K where "M = add_mset a M0" "N = M0 + K"
  3058     "a \<notin># K" "\<And>b. b \<in># K \<Longrightarrow> b < a"
  3059 proof -
  3060   from assms obtain a M0 K where "M = add_mset a M0" "N = M0 + K" and
  3061     *: "b \<in># K \<Longrightarrow> b < a" for b by (blast elim: mult1E)
  3062   moreover from * [of a] have "a \<notin># K" by auto
  3063   ultimately show thesis by (auto intro: that)
  3064 qed
  3065 
  3066 instantiation multiset :: (preorder) order
  3067 begin
  3068 
  3069 definition less_multiset :: "'a multiset \<Rightarrow> 'a multiset \<Rightarrow> bool"
  3070   where "M' < M \<longleftrightarrow> (M', M) \<in> mult {(x', x). x' < x}"
  3071 
  3072 definition less_eq_multiset :: "'a multiset \<Rightarrow> 'a multiset \<Rightarrow> bool"
  3073   where "less_eq_multiset M' M \<longleftrightarrow> M' < M \<or> M' = M"
  3074 
  3075 instance
  3076 proof -
  3077   have irrefl: "\<not> M < M" for M :: "'a multiset"
  3078   proof
  3079     assume "M < M"
  3080     then have MM: "(M, M) \<in> mult {(x, y). x < y}" by (simp add: less_multiset_def)
  3081     have "trans {(x'::'a, x). x' < x}"
  3082       by (metis (mono_tags, lifting) case_prodD case_prodI less_trans mem_Collect_eq transI)
  3083     moreover note MM
  3084     ultimately have "\<exists>I J K. M = I + J \<and> M = I + K
  3085       \<and> J \<noteq> {#} \<and> (\<forall>k\<in>set_mset K. \<exists>j\<in>set_mset J. (k, j) \<in> {(x, y). x < y})"
  3086       by (rule mult_implies_one_step)
  3087     then obtain I J K where "M = I + J" and "M = I + K"
  3088       and "J \<noteq> {#}" and "(\<forall>k\<in>set_mset K. \<exists>j\<in>set_mset J. (k, j) \<in> {(x, y). x < y})" by blast
  3089     then have *: "K \<noteq> {#}" and **: "\<forall>k\<in>set_mset K. \<exists>j\<in>set_mset K. k < j" by auto
  3090     have "finite (set_mset K)" by simp
  3091     moreover note **
  3092     ultimately have "set_mset K = {}"
  3093       by (induct rule: finite_induct) (auto intro: order_less_trans)
  3094     with * show False by simp
  3095   qed
  3096   have trans: "K < M \<Longrightarrow> M < N \<Longrightarrow> K < N" for K M N :: "'a multiset"
  3097     unfolding less_multiset_def mult_def by (blast intro: trancl_trans)
  3098   show "OFCLASS('a multiset, order_class)"
  3099     by standard (auto simp add: less_eq_multiset_def irrefl dest: trans)
  3100 qed
  3101 end \<comment> \<open>FIXME avoid junk stemming from type class interpretation\<close>
  3102 
  3103 lemma mset_le_irrefl [elim!]:
  3104   fixes M :: "'a::preorder multiset"
  3105   shows "M < M \<Longrightarrow> R"
  3106   by simp
  3107 
  3108 
  3109 subsubsection \<open>Monotonicity of multiset union\<close>
  3110 
  3111 lemma mult1_union: "(B, D) \<in> mult1 r \<Longrightarrow> (C + B, C + D) \<in> mult1 r"
  3112   by (force simp: mult1_def)
  3113 
  3114 lemma union_le_mono2: "B < D \<Longrightarrow> C + B < C + (D::'a::preorder multiset)"
  3115 apply (unfold less_multiset_def mult_def)
  3116 apply (erule trancl_induct)
  3117  apply (blast intro: mult1_union)
  3118 apply (blast intro: mult1_union trancl_trans)
  3119 done
  3120 
  3121 lemma union_le_mono1: "B < D \<Longrightarrow> B + C < D + (C::'a::preorder multiset)"
  3122 apply (subst add.commute [of B C])
  3123 apply (subst add.commute [of D C])
  3124 apply (erule union_le_mono2)
  3125 done
  3126 
  3127 lemma union_less_mono:
  3128   fixes A B C D :: "'a::preorder multiset"
  3129   shows "A < C \<Longrightarrow> B < D \<Longrightarrow> A + B < C + D"
  3130   by (blast intro!: union_le_mono1 union_le_mono2 less_trans)
  3131 
  3132 instantiation multiset :: (preorder) ordered_ab_semigroup_add
  3133 begin
  3134 instance
  3135   by standard (auto simp add: less_eq_multiset_def intro: union_le_mono2)
  3136 end
  3137 
  3138 
  3139 subsubsection \<open>Termination proofs with multiset orders\<close>
  3140 
  3141 lemma multi_member_skip: "x \<in># XS \<Longrightarrow> x \<in># {# y #} + XS"
  3142   and multi_member_this: "x \<in># {# x #} + XS"
  3143   and multi_member_last: "x \<in># {# x #}"
  3144   by auto
  3145 
  3146 definition "ms_strict = mult pair_less"
  3147 definition "ms_weak = ms_strict \<union> Id"
  3148 
  3149 lemma ms_reduction_pair: "reduction_pair (ms_strict, ms_weak)"
  3150 unfolding reduction_pair_def ms_strict_def ms_weak_def pair_less_def
  3151 by (auto intro: wf_mult1 wf_trancl simp: mult_def)
  3152 
  3153 lemma smsI:
  3154   "(set_mset A, set_mset B) \<in> max_strict \<Longrightarrow> (Z + A, Z + B) \<in> ms_strict"
  3155   unfolding ms_strict_def
  3156 by (rule one_step_implies_mult) (auto simp add: max_strict_def pair_less_def elim!:max_ext.cases)
  3157 
  3158 lemma wmsI:
  3159   "(set_mset A, set_mset B) \<in> max_strict \<or> A = {#} \<and> B = {#}
  3160   \<Longrightarrow> (Z + A, Z + B) \<in> ms_weak"
  3161 unfolding ms_weak_def ms_strict_def
  3162 by (auto simp add: pair_less_def max_strict_def elim!:max_ext.cases intro: one_step_implies_mult)
  3163 
  3164 inductive pw_leq
  3165 where
  3166   pw_leq_empty: "pw_leq {#} {#}"
  3167 | pw_leq_step:  "\<lbrakk>(x,y) \<in> pair_leq; pw_leq X Y \<rbrakk> \<Longrightarrow> pw_leq ({#x#} + X) ({#y#} + Y)"
  3168 
  3169 lemma pw_leq_lstep:
  3170   "(x, y) \<in> pair_leq \<Longrightarrow> pw_leq {#x#} {#y#}"
  3171 by (drule pw_leq_step) (rule pw_leq_empty, simp)
  3172 
  3173 lemma pw_leq_split:
  3174   assumes "pw_leq X Y"
  3175   shows "\<exists>A B Z. X = A + Z \<and> Y = B + Z \<and> ((set_mset A, set_mset B) \<in> max_strict \<or> (B = {#} \<and> A = {#}))"
  3176   using assms
  3177 proof induct
  3178   case pw_leq_empty thus ?case by auto
  3179 next
  3180   case (pw_leq_step x y X Y)
  3181   then obtain A B Z where
  3182     [simp]: "X = A + Z" "Y = B + Z"
  3183       and 1[simp]: "(set_mset A, set_mset B) \<in> max_strict \<or> (B = {#} \<and> A = {#})"
  3184     by auto
  3185   from pw_leq_step consider "x = y" | "(x, y) \<in> pair_less"
  3186     unfolding pair_leq_def by auto
  3187   thus ?case
  3188   proof cases
  3189     case [simp]: 1
  3190     have "{#x#} + X = A + ({#y#}+Z) \<and> {#y#} + Y = B + ({#y#}+Z) \<and>
  3191       ((set_mset A, set_mset B) \<in> max_strict \<or> (B = {#} \<and> A = {#}))"
  3192       by auto
  3193     thus ?thesis by blast
  3194   next
  3195     case 2
  3196     let ?A' = "{#x#} + A" and ?B' = "{#y#} + B"
  3197     have "{#x#} + X = ?A' + Z"
  3198       "{#y#} + Y = ?B' + Z"
  3199       by auto
  3200     moreover have
  3201       "(set_mset ?A', set_mset ?B') \<in> max_strict"
  3202       using 1 2 unfolding max_strict_def
  3203       by (auto elim!: max_ext.cases)
  3204     ultimately show ?thesis by blast
  3205   qed
  3206 qed
  3207 
  3208 lemma
  3209   assumes pwleq: "pw_leq Z Z'"
  3210   shows ms_strictI: "(set_mset A, set_mset B) \<in> max_strict \<Longrightarrow> (Z + A, Z' + B) \<in> ms_strict"
  3211     and ms_weakI1:  "(set_mset A, set_mset B) \<in> max_strict \<Longrightarrow> (Z + A, Z' + B) \<in> ms_weak"
  3212     and ms_weakI2:  "(Z + {#}, Z' + {#}) \<in> ms_weak"
  3213 proof -
  3214   from pw_leq_split[OF pwleq]
  3215   obtain A' B' Z''
  3216     where [simp]: "Z = A' + Z''" "Z' = B' + Z''"
  3217     and mx_or_empty: "(set_mset A', set_mset B') \<in> max_strict \<or> (A' = {#} \<and> B' = {#})"
  3218     by blast
  3219   {
  3220     assume max: "(set_mset A, set_mset B) \<in> max_strict"
  3221     from mx_or_empty
  3222     have "(Z'' + (A + A'), Z'' + (B + B')) \<in> ms_strict"
  3223     proof
  3224       assume max': "(set_mset A', set_mset B') \<in> max_strict"
  3225       with max have "(set_mset (A + A'), set_mset (B + B')) \<in> max_strict"
  3226         by (auto simp: max_strict_def intro: max_ext_additive)
  3227       thus ?thesis by (rule smsI)
  3228     next
  3229       assume [simp]: "A' = {#} \<and> B' = {#}"
  3230       show ?thesis by (rule smsI) (auto intro: max)
  3231     qed
  3232     thus "(Z + A, Z' + B) \<in> ms_strict" by (simp add: ac_simps)
  3233     thus "(Z + A, Z' + B) \<in> ms_weak" by (simp add: ms_weak_def)
  3234   }
  3235   from mx_or_empty
  3236   have "(Z'' + A', Z'' + B') \<in> ms_weak" by (rule wmsI)
  3237   thus "(Z + {#}, Z' + {#}) \<in> ms_weak" by (simp add: ac_simps)
  3238 qed
  3239 
  3240 lemma empty_neutral: "{#} + x = x" "x + {#} = x"
  3241 and nonempty_plus: "{# x #} + rs \<noteq> {#}"
  3242 and nonempty_single: "{# x #} \<noteq> {#}"
  3243 by auto
  3244 
  3245 setup \<open>
  3246   let
  3247     fun msetT T = Type (\<^type_name>\<open>multiset\<close>, [T]);
  3248 
  3249     fun mk_mset T [] = Const (\<^const_abbrev>\<open>Mempty\<close>, msetT T)
  3250       | mk_mset T [x] =
  3251         Const (\<^const_name>\<open>add_mset\<close>, T --> msetT T --> msetT T) $ x $
  3252           Const (\<^const_abbrev>\<open>Mempty\<close>, msetT T)
  3253       | mk_mset T (x :: xs) =
  3254         Const (\<^const_name>\<open>plus\<close>, msetT T --> msetT T --> msetT T) $
  3255           mk_mset T [x] $ mk_mset T xs
  3256 
  3257     fun mset_member_tac ctxt m i =
  3258       if m <= 0 then
  3259         resolve_tac ctxt @{thms multi_member_this} i ORELSE
  3260         resolve_tac ctxt @{thms multi_member_last} i
  3261       else
  3262         resolve_tac ctxt @{thms multi_member_skip} i THEN mset_member_tac ctxt (m - 1) i
  3263 
  3264     fun mset_nonempty_tac ctxt =
  3265       resolve_tac ctxt @{thms nonempty_plus} ORELSE'
  3266       resolve_tac ctxt @{thms nonempty_single}
  3267 
  3268     fun regroup_munion_conv ctxt =
  3269       Function_Lib.regroup_conv ctxt \<^const_abbrev>\<open>Mempty\<close> \<^const_name>\<open>plus\<close>
  3270         (map (fn t => t RS eq_reflection) (@{thms ac_simps} @ @{thms empty_neutral}))
  3271 
  3272     fun unfold_pwleq_tac ctxt i =
  3273       (resolve_tac ctxt @{thms pw_leq_step} i THEN (fn st => unfold_pwleq_tac ctxt (i + 1) st))
  3274         ORELSE (resolve_tac ctxt @{thms pw_leq_lstep} i)
  3275         ORELSE (resolve_tac ctxt @{thms pw_leq_empty} i)
  3276 
  3277     val set_mset_simps = [@{thm set_mset_empty}, @{thm set_mset_single}, @{thm set_mset_union},
  3278                         @{thm Un_insert_left}, @{thm Un_empty_left}]
  3279   in
  3280     ScnpReconstruct.multiset_setup (ScnpReconstruct.Multiset
  3281     {
  3282       msetT=msetT, mk_mset=mk_mset, mset_regroup_conv=regroup_munion_conv,
  3283       mset_member_tac=mset_member_tac, mset_nonempty_tac=mset_nonempty_tac,
  3284       mset_pwleq_tac=unfold_pwleq_tac, set_of_simps=set_mset_simps,
  3285       smsI'= @{thm ms_strictI}, wmsI2''= @{thm ms_weakI2}, wmsI1= @{thm ms_weakI1},
  3286       reduction_pair = @{thm ms_reduction_pair}
  3287     })
  3288   end
  3289 \<close>
  3290 
  3291 
  3292 subsection \<open>Legacy theorem bindings\<close>
  3293 
  3294 lemmas multi_count_eq = multiset_eq_iff [symmetric]
  3295 
  3296 lemma union_commute: "M + N = N + (M::'a multiset)"
  3297   by (fact add.commute)
  3298 
  3299 lemma union_assoc: "(M + N) + K = M + (N + (K::'a multiset))"
  3300   by (fact add.assoc)
  3301 
  3302 lemma union_lcomm: "M + (N + K) = N + (M + (K::'a multiset))"
  3303   by (fact add.left_commute)
  3304 
  3305 lemmas union_ac = union_assoc union_commute union_lcomm add_mset_commute
  3306 
  3307 lemma union_right_cancel: "M + K = N + K \<longleftrightarrow> M = (N::'a multiset)"
  3308   by (fact add_right_cancel)
  3309 
  3310 lemma union_left_cancel: "K + M = K + N \<longleftrightarrow> M = (N::'a multiset)"
  3311   by (fact add_left_cancel)
  3312 
  3313 lemma multi_union_self_other_eq: "(A::'a multiset) + X = A + Y \<Longrightarrow> X = Y"
  3314   by (fact add_left_imp_eq)
  3315 
  3316 lemma mset_subset_trans: "(M::'a multiset) \<subset># K \<Longrightarrow> K \<subset># N \<Longrightarrow> M \<subset># N"
  3317   by (fact subset_mset.less_trans)
  3318 
  3319 lemma multiset_inter_commute: "A \<inter># B = B \<inter># A"
  3320   by (fact subset_mset.inf.commute)
  3321 
  3322 lemma multiset_inter_assoc: "A \<inter># (B \<inter># C) = A \<inter># B \<inter># C"
  3323   by (fact subset_mset.inf.assoc [symmetric])
  3324 
  3325 lemma multiset_inter_left_commute: "A \<inter># (B \<inter># C) = B \<inter># (A \<inter># C)"
  3326   by (fact subset_mset.inf.left_commute)
  3327 
  3328 lemmas multiset_inter_ac =
  3329   multiset_inter_commute
  3330   multiset_inter_assoc
  3331   multiset_inter_left_commute
  3332 
  3333 lemma mset_le_not_refl: "\<not> M < (M::'a::preorder multiset)"
  3334   by (fact less_irrefl)
  3335 
  3336 lemma mset_le_trans: "K < M \<Longrightarrow> M < N \<Longrightarrow> K < (N::'a::preorder multiset)"
  3337   by (fact less_trans)
  3338 
  3339 lemma mset_le_not_sym: "M < N \<Longrightarrow> \<not> N < (M::'a::preorder multiset)"
  3340   by (fact less_not_sym)
  3341 
  3342 lemma mset_le_asym: "M < N \<Longrightarrow> (\<not> P \<Longrightarrow> N < (M::'a::preorder multiset)) \<Longrightarrow> P"
  3343   by (fact less_asym)
  3344 
  3345 declaration \<open>
  3346   let
  3347     fun multiset_postproc _ maybe_name all_values (T as Type (_, [elem_T])) (Const _ $ t') =
  3348           let
  3349             val (maybe_opt, ps) =
  3350               Nitpick_Model.dest_plain_fun t'
  3351               ||> (~~)
  3352               ||> map (apsnd (snd o HOLogic.dest_number))
  3353             fun elems_for t =
  3354               (case AList.lookup (=) ps t of
  3355                 SOME n => replicate n t
  3356               | NONE => [Const (maybe_name, elem_T --> elem_T) $ t])
  3357           in
  3358             (case maps elems_for (all_values elem_T) @
  3359                  (if maybe_opt then [Const (Nitpick_Model.unrep_mixfix (), elem_T)] else []) of
  3360               [] => Const (\<^const_name>\<open>zero_class.zero\<close>, T)
  3361             | ts =>
  3362                 foldl1 (fn (s, t) => Const (\<^const_name>\<open>add_mset\<close>, elem_T --> T --> T) $ s $ t)
  3363                   ts)
  3364           end
  3365       | multiset_postproc _ _ _ _ t = t
  3366   in Nitpick_Model.register_term_postprocessor \<^typ>\<open>'a multiset\<close> multiset_postproc end
  3367 \<close>
  3368 
  3369 
  3370 subsection \<open>Naive implementation using lists\<close>
  3371 
  3372 code_datatype mset
  3373 
  3374 lemma [code]: "{#} = mset []"
  3375   by simp
  3376 
  3377 lemma [code]: "add_mset x (mset xs) = mset (x # xs)"
  3378   by simp
  3379 
  3380 lemma [code]: "Multiset.is_empty (mset xs) \<longleftrightarrow> List.null xs"
  3381   by (simp add: Multiset.is_empty_def List.null_def)
  3382 
  3383 lemma union_code [code]: "mset xs + mset ys = mset (xs @ ys)"
  3384   by simp
  3385 
  3386 lemma [code]: "image_mset f (mset xs) = mset (map f xs)"
  3387   by simp
  3388 
  3389 lemma [code]: "filter_mset f (mset xs) = mset (filter f xs)"
  3390   by simp
  3391 
  3392 lemma [code]: "mset xs - mset ys = mset (fold remove1 ys xs)"
  3393   by (rule sym, induct ys arbitrary: xs) (simp_all add: diff_add diff_right_commute diff_diff_add)
  3394 
  3395 lemma [code]:
  3396   "mset xs \<inter># mset ys =
  3397     mset (snd (fold (\<lambda>x (ys, zs).
  3398       if x \<in> set ys then (remove1 x ys, x # zs) else (ys, zs)) xs (ys, [])))"
  3399 proof -
  3400   have "\<And>zs. mset (snd (fold (\<lambda>x (ys, zs).
  3401     if x \<in> set ys then (remove1 x ys, x # zs) else (ys, zs)) xs (ys, zs))) =
  3402       (mset xs \<inter># mset ys) + mset zs"
  3403     by (induct xs arbitrary: ys)
  3404       (auto simp add: inter_add_right1 inter_add_right2 ac_simps)
  3405   then show ?thesis by simp
  3406 qed
  3407 
  3408 lemma [code]:
  3409   "mset xs \<union># mset ys =
  3410     mset (case_prod append (fold (\<lambda>x (ys, zs). (remove1 x ys, x # zs)) xs (ys, [])))"
  3411 proof -
  3412   have "\<And>zs. mset (case_prod append (fold (\<lambda>x (ys, zs). (remove1 x ys, x # zs)) xs (ys, zs))) =
  3413       (mset xs \<union># mset ys) + mset zs"
  3414     by (induct xs arbitrary: ys) (simp_all add: multiset_eq_iff)
  3415   then show ?thesis by simp
  3416 qed
  3417 
  3418 declare in_multiset_in_set [code_unfold]
  3419 
  3420 lemma [code]: "count (mset xs) x = fold (\<lambda>y. if x = y then Suc else id) xs 0"
  3421 proof -
  3422   have "\<And>n. fold (\<lambda>y. if x = y then Suc else id) xs n = count (mset xs) x + n"
  3423     by (induct xs) simp_all
  3424   then show ?thesis by simp
  3425 qed
  3426 
  3427 declare set_mset_mset [code]
  3428 
  3429 declare sorted_list_of_multiset_mset [code]
  3430 
  3431 lemma [code]: \<comment> \<open>not very efficient, but representation-ignorant!\<close>
  3432   "mset_set A = mset (sorted_list_of_set A)"
  3433   apply (cases "finite A")
  3434   apply simp_all
  3435   apply (induct A rule: finite_induct)
  3436   apply simp_all
  3437   done
  3438 
  3439 declare size_mset [code]
  3440 
  3441 fun subset_eq_mset_impl :: "'a list \<Rightarrow> 'a list \<Rightarrow> bool option" where
  3442   "subset_eq_mset_impl [] ys = Some (ys \<noteq> [])"
  3443 | "subset_eq_mset_impl (Cons x xs) ys = (case List.extract ((=) x) ys of
  3444      None \<Rightarrow> None
  3445    | Some (ys1,_,ys2) \<Rightarrow> subset_eq_mset_impl xs (ys1 @ ys2))"
  3446 
  3447 lemma subset_eq_mset_impl: "(subset_eq_mset_impl xs ys = None \<longleftrightarrow> \<not> mset xs \<subseteq># mset ys) \<and>
  3448   (subset_eq_mset_impl xs ys = Some True \<longleftrightarrow> mset xs \<subset># mset ys) \<and>
  3449   (subset_eq_mset_impl xs ys = Some False \<longrightarrow> mset xs = mset ys)"
  3450 proof (induct xs arbitrary: ys)
  3451   case (Nil ys)
  3452   show ?case by (auto simp: subset_mset.zero_less_iff_neq_zero)
  3453 next
  3454   case (Cons x xs ys)
  3455   show ?case
  3456   proof (cases "List.extract ((=) x) ys")
  3457     case None
  3458     hence x: "x \<notin> set ys" by (simp add: extract_None_iff)
  3459     {
  3460       assume "mset (x # xs) \<subseteq># mset ys"
  3461       from set_mset_mono[OF this] x have False by simp
  3462     } note nle = this
  3463     moreover
  3464     {
  3465       assume "mset (x # xs) \<subset># mset ys"
  3466       hence "mset (x # xs) \<subseteq># mset ys" by auto
  3467       from nle[OF this] have False .
  3468     }
  3469     ultimately show ?thesis using None by auto
  3470   next
  3471     case (Some res)
  3472     obtain ys1 y ys2 where res: "res = (ys1,y,ys2)" by (cases res, auto)
  3473     note Some = Some[unfolded res]
  3474     from extract_SomeE[OF Some] have "ys = ys1 @ x # ys2" by simp
  3475     hence id: "mset ys = add_mset x (mset (ys1 @ ys2))"
  3476       by auto
  3477     show ?thesis unfolding subset_eq_mset_impl.simps
  3478       unfolding Some option.simps split
  3479       unfolding id
  3480       using Cons[of "ys1 @ ys2"]
  3481       unfolding subset_mset_def subseteq_mset_def by auto
  3482   qed
  3483 qed
  3484 
  3485 lemma [code]: "mset xs \<subseteq># mset ys \<longleftrightarrow> subset_eq_mset_impl xs ys \<noteq> None"
  3486   using subset_eq_mset_impl[of xs ys] by (cases "subset_eq_mset_impl xs ys", auto)
  3487 
  3488 lemma [code]: "mset xs \<subset># mset ys \<longleftrightarrow> subset_eq_mset_impl xs ys = Some True"
  3489   using subset_eq_mset_impl[of xs ys] by (cases "subset_eq_mset_impl xs ys", auto)
  3490 
  3491 instantiation multiset :: (equal) equal
  3492 begin
  3493 
  3494 definition
  3495   [code del]: "HOL.equal A (B :: 'a multiset) \<longleftrightarrow> A = B"
  3496 lemma [code]: "HOL.equal (mset xs) (mset ys) \<longleftrightarrow> subset_eq_mset_impl xs ys = Some False"
  3497   unfolding equal_multiset_def
  3498   using subset_eq_mset_impl[of xs ys] by (cases "subset_eq_mset_impl xs ys", auto)
  3499 
  3500 instance
  3501   by standard (simp add: equal_multiset_def)
  3502 
  3503 end
  3504 
  3505 declare sum_mset_sum_list [code]
  3506 
  3507 lemma [code]: "prod_mset (mset xs) = fold times xs 1"
  3508 proof -
  3509   have "\<And>x. fold times xs x = prod_mset (mset xs) * x"
  3510     by (induct xs) (simp_all add: ac_simps)
  3511   then show ?thesis by simp
  3512 qed
  3513 
  3514 text \<open>
  3515   Exercise for the casual reader: add implementations for \<^term>\<open>(\<le>)\<close>
  3516   and \<^term>\<open>(<)\<close> (multiset order).
  3517 \<close>
  3518 
  3519 text \<open>Quickcheck generators\<close>
  3520 
  3521 definition (in term_syntax)
  3522   msetify :: "'a::typerep list \<times> (unit \<Rightarrow> Code_Evaluation.term)
  3523     \<Rightarrow> 'a multiset \<times> (unit \<Rightarrow> Code_Evaluation.term)" where
  3524   [code_unfold]: "msetify xs = Code_Evaluation.valtermify mset {\<cdot>} xs"
  3525 
  3526 notation fcomp (infixl "\<circ>>" 60)
  3527 notation scomp (infixl "\<circ>\<rightarrow>" 60)
  3528 
  3529 instantiation multiset :: (random) random
  3530 begin
  3531 
  3532 definition
  3533   "Quickcheck_Random.random i = Quickcheck_Random.random i \<circ>\<rightarrow> (\<lambda>xs. Pair (msetify xs))"
  3534 
  3535 instance ..
  3536 
  3537 end
  3538 
  3539 no_notation fcomp (infixl "\<circ>>" 60)
  3540 no_notation scomp (infixl "\<circ>\<rightarrow>" 60)
  3541 
  3542 instantiation multiset :: (full_exhaustive) full_exhaustive
  3543 begin
  3544 
  3545 definition full_exhaustive_multiset :: "('a multiset \<times> (unit \<Rightarrow> term) \<Rightarrow> (bool \<times> term list) option) \<Rightarrow> natural \<Rightarrow> (bool \<times> term list) option"
  3546 where
  3547   "full_exhaustive_multiset f i = Quickcheck_Exhaustive.full_exhaustive (\<lambda>xs. f (msetify xs)) i"
  3548 
  3549 instance ..
  3550 
  3551 end
  3552 
  3553 hide_const (open) msetify
  3554 
  3555 
  3556 subsection \<open>BNF setup\<close>
  3557 
  3558 definition rel_mset where
  3559   "rel_mset R X Y \<longleftrightarrow> (\<exists>xs ys. mset xs = X \<and> mset ys = Y \<and> list_all2 R xs ys)"
  3560 
  3561 lemma mset_zip_take_Cons_drop_twice:
  3562   assumes "length xs = length ys" "j \<le> length xs"
  3563   shows "mset (zip (take j xs @ x # drop j xs) (take j ys @ y # drop j ys)) =
  3564     add_mset (x,y) (mset (zip xs ys))"
  3565   using assms
  3566 proof (induct xs ys arbitrary: x y j rule: list_induct2)
  3567   case Nil
  3568   thus ?case
  3569     by simp
  3570 next
  3571   case (Cons x xs y ys)
  3572   thus ?case
  3573   proof (cases "j = 0")
  3574     case True
  3575     thus ?thesis
  3576       by simp
  3577   next
  3578     case False
  3579     then obtain k where k: "j = Suc k"
  3580       by (cases j) simp
  3581     hence "k \<le> length xs"
  3582       using Cons.prems by auto
  3583     hence "mset (zip (take k xs @ x # drop k xs) (take k ys @ y # drop k ys)) =
  3584       add_mset (x,y) (mset (zip xs ys))"
  3585       by (rule Cons.hyps(2))
  3586     thus ?thesis
  3587       unfolding k by auto
  3588   qed
  3589 qed
  3590 
  3591 lemma ex_mset_zip_left:
  3592   assumes "length xs = length ys" "mset xs' = mset xs"
  3593   shows "\<exists>ys'. length ys' = length xs' \<and> mset (zip xs' ys') = mset (zip xs ys)"
  3594 using assms
  3595 proof (induct xs ys arbitrary: xs' rule: list_induct2)
  3596   case Nil
  3597   thus ?case
  3598     by auto
  3599 next
  3600   case (Cons x xs y ys xs')
  3601   obtain j where j_len: "j < length xs'" and nth_j: "xs' ! j = x"
  3602     by (metis Cons.prems in_set_conv_nth list.set_intros(1) mset_eq_setD)
  3603 
  3604   define xsa where "xsa = take j xs' @ drop (Suc j) xs'"
  3605   have "mset xs' = {#x#} + mset xsa"
  3606     unfolding xsa_def using j_len nth_j
  3607     by (metis Cons_nth_drop_Suc union_mset_add_mset_right add_mset_remove_trivial add_diff_cancel_left'
  3608         append_take_drop_id mset.simps(2) mset_append)
  3609   hence ms_x: "mset xsa = mset xs"
  3610     by (simp add: Cons.prems)
  3611   then obtain ysa where
  3612     len_a: "length ysa = length xsa" and ms_a: "mset (zip xsa ysa) = mset (zip xs ys)"
  3613     using Cons.hyps(2) by blast
  3614 
  3615   define ys' where "ys' = take j ysa @ y # drop j ysa"
  3616   have xs': "xs' = take j xsa @ x # drop j xsa"
  3617     using ms_x j_len nth_j Cons.prems xsa_def
  3618     by (metis append_eq_append_conv append_take_drop_id diff_Suc_Suc Cons_nth_drop_Suc length_Cons
  3619       length_drop size_mset)
  3620   have j_len': "j \<le> length xsa"
  3621     using j_len xs' xsa_def
  3622     by (metis add_Suc_right append_take_drop_id length_Cons length_append less_eq_Suc_le not_less)
  3623   have "length ys' = length xs'"
  3624     unfolding ys'_def using Cons.prems len_a ms_x
  3625     by (metis add_Suc_right append_take_drop_id length_Cons length_append mset_eq_length)
  3626   moreover have "mset (zip xs' ys') = mset (zip (x # xs) (y # ys))"
  3627     unfolding xs' ys'_def
  3628     by (rule trans[OF mset_zip_take_Cons_drop_twice])
  3629       (auto simp: len_a ms_a j_len')
  3630   ultimately show ?case
  3631     by blast
  3632 qed
  3633 
  3634 lemma list_all2_reorder_left_invariance:
  3635   assumes rel: "list_all2 R xs ys" and ms_x: "mset xs' = mset xs"
  3636   shows "\<exists>ys'. list_all2 R xs' ys' \<and> mset ys' = mset ys"
  3637 proof -
  3638   have len: "length xs = length ys"
  3639     using rel list_all2_conv_all_nth by auto
  3640   obtain ys' where
  3641     len': "length xs' = length ys'" and ms_xy: "mset (zip xs' ys') = mset (zip xs ys)"
  3642     using len ms_x by (metis ex_mset_zip_left)
  3643   have "list_all2 R xs' ys'"
  3644     using assms(1) len' ms_xy unfolding list_all2_iff by (blast dest: mset_eq_setD)
  3645   moreover have "mset ys' = mset ys"
  3646     using len len' ms_xy map_snd_zip mset_map by metis
  3647   ultimately show ?thesis
  3648     by blast
  3649 qed
  3650 
  3651 lemma ex_mset: "\<exists>xs. mset xs = X"
  3652   by (induct X) (simp, metis mset.simps(2))
  3653 
  3654 inductive pred_mset :: "('a \<Rightarrow> bool) \<Rightarrow> 'a multiset \<Rightarrow> bool"
  3655 where
  3656   "pred_mset P {#}"
  3657 | "\<lbrakk>P a; pred_mset P M\<rbrakk> \<Longrightarrow> pred_mset P (add_mset a M)"
  3658 
  3659 bnf "'a multiset"
  3660   map: image_mset
  3661   sets: set_mset
  3662   bd: natLeq
  3663   wits: "{#}"
  3664   rel: rel_mset
  3665   pred: pred_mset
  3666 proof -
  3667   show "image_mset id = id"
  3668     by (rule image_mset.id)
  3669   show "image_mset (g \<circ> f) = image_mset g \<circ> image_mset f" for f g
  3670     unfolding comp_def by (rule ext) (simp add: comp_def image_mset.compositionality)
  3671   show "(\<And>z. z \<in> set_mset X \<Longrightarrow> f z = g z) \<Longrightarrow> image_mset f X = image_mset g X" for f g X
  3672     by (induct X) simp_all
  3673   show "set_mset \<circ> image_mset f = (`) f \<circ> set_mset" for f
  3674     by auto
  3675   show "card_order natLeq"
  3676     by (rule natLeq_card_order)
  3677   show "BNF_Cardinal_Arithmetic.cinfinite natLeq"
  3678     by (rule natLeq_cinfinite)
  3679   show "ordLeq3 (card_of (set_mset X)) natLeq" for X
  3680     by transfer
  3681       (auto intro!: ordLess_imp_ordLeq simp: finite_iff_ordLess_natLeq[symmetric] multiset_def)
  3682   show "rel_mset R OO rel_mset S \<le> rel_mset (R OO S)" for R S
  3683     unfolding rel_mset_def[abs_def] OO_def
  3684     apply clarify
  3685     subgoal for X Z Y xs ys' ys zs
  3686       apply (drule list_all2_reorder_left_invariance [where xs = ys' and ys = zs and xs' = ys])
  3687       apply (auto intro: list_all2_trans)
  3688       done
  3689     done
  3690   show "rel_mset R =
  3691     (\<lambda>x y. \<exists>z. set_mset z \<subseteq> {(x, y). R x y} \<and>
  3692     image_mset fst z = x \<and> image_mset snd z = y)" for R
  3693     unfolding rel_mset_def[abs_def]
  3694     apply (rule ext)+
  3695     apply safe
  3696      apply (rule_tac x = "mset (zip xs ys)" in exI;
  3697        auto simp: in_set_zip list_all2_iff simp flip: mset_map)
  3698     apply (rename_tac XY)
  3699     apply (cut_tac X = XY in ex_mset)
  3700     apply (erule exE)
  3701     apply (rename_tac xys)
  3702     apply (rule_tac x = "map fst xys" in exI)
  3703     apply (auto simp: mset_map)
  3704     apply (rule_tac x = "map snd xys" in exI)
  3705     apply (auto simp: mset_map list_all2I subset_eq zip_map_fst_snd)
  3706     done
  3707   show "z \<in> set_mset {#} \<Longrightarrow> False" for z
  3708     by auto
  3709   show "pred_mset P = (\<lambda>x. Ball (set_mset x) P)" for P
  3710   proof (intro ext iffI)
  3711     fix x
  3712     assume "pred_mset P x"
  3713     then show "Ball (set_mset x) P" by (induct pred: pred_mset; simp)
  3714   next
  3715     fix x
  3716     assume "Ball (set_mset x) P"
  3717     then show "pred_mset P x" by (induct x; auto intro: pred_mset.intros)
  3718   qed
  3719 qed
  3720 
  3721 inductive rel_mset'
  3722 where
  3723   Zero[intro]: "rel_mset' R {#} {#}"
  3724 | Plus[intro]: "\<lbrakk>R a b; rel_mset' R M N\<rbrakk> \<Longrightarrow> rel_mset' R (add_mset a M) (add_mset b N)"
  3725 
  3726 lemma rel_mset_Zero: "rel_mset R {#} {#}"
  3727 unfolding rel_mset_def Grp_def by auto
  3728 
  3729 declare multiset.count[simp]
  3730 declare Abs_multiset_inverse[simp]
  3731 declare multiset.count_inverse[simp]
  3732 declare union_preserves_multiset[simp]
  3733 
  3734 lemma rel_mset_Plus:
  3735   assumes ab: "R a b"
  3736     and MN: "rel_mset R M N"
  3737   shows "rel_mset R (add_mset a M) (add_mset b N)"
  3738 proof -
  3739   have "\<exists>ya. add_mset a (image_mset fst y) = image_mset fst ya \<and>
  3740     add_mset b (image_mset snd y) = image_mset snd ya \<and>
  3741     set_mset ya \<subseteq> {(x, y). R x y}"
  3742     if "R a b" and "set_mset y \<subseteq> {(x, y). R x y}" for y
  3743     using that by (intro exI[of _ "add_mset (a,b) y"]) auto
  3744   thus ?thesis
  3745   using assms
  3746   unfolding multiset.rel_compp_Grp Grp_def by blast
  3747 qed
  3748 
  3749 lemma rel_mset'_imp_rel_mset: "rel_mset' R M N \<Longrightarrow> rel_mset R M N"
  3750   by (induct rule: rel_mset'.induct) (auto simp: rel_mset_Zero rel_mset_Plus)
  3751 
  3752 lemma rel_mset_size: "rel_mset R M N \<Longrightarrow> size M = size N"
  3753   unfolding multiset.rel_compp_Grp Grp_def by auto
  3754 
  3755 lemma multiset_induct2[case_names empty addL addR]:
  3756   assumes empty: "P {#} {#}"
  3757     and addL: "\<And>a M N. P M N \<Longrightarrow> P (add_mset a M) N"
  3758     and addR: "\<And>a M N. P M N \<Longrightarrow> P M (add_mset a N)"
  3759   shows "P M N"
  3760 apply(induct N rule: multiset_induct)
  3761   apply(induct M rule: multiset_induct, rule empty, erule addL)
  3762   apply(induct M rule: multiset_induct, erule addR, erule addR)
  3763 done
  3764 
  3765 lemma multiset_induct2_size[consumes 1, case_names empty add]:
  3766   assumes c: "size M = size N"
  3767     and empty: "P {#} {#}"
  3768     and add: "\<And>a b M N a b. P M N \<Longrightarrow> P (add_mset a M) (add_mset b N)"
  3769   shows "P M N"
  3770   using c
  3771 proof (induct M arbitrary: N rule: measure_induct_rule[of size])
  3772   case (less M)
  3773   show ?case
  3774   proof(cases "M = {#}")
  3775     case True hence "N = {#}" using less.prems by auto
  3776     thus ?thesis using True empty by auto
  3777   next
  3778     case False then obtain M1 a where M: "M = add_mset a M1" by (metis multi_nonempty_split)
  3779     have "N \<noteq> {#}" using False less.prems by auto
  3780     then obtain N1 b where N: "N = add_mset b N1" by (metis multi_nonempty_split)
  3781     have "size M1 = size N1" using less.prems unfolding M N by auto
  3782     thus ?thesis using M N less.hyps add by auto
  3783   qed
  3784 qed
  3785 
  3786 lemma msed_map_invL:
  3787   assumes "image_mset f (add_mset a M) = N"
  3788   shows "\<exists>N1. N = add_mset (f a) N1 \<and> image_mset f M = N1"
  3789 proof -
  3790   have "f a \<in># N"
  3791     using assms multiset.set_map[of f "add_mset a M"] by auto
  3792   then obtain N1 where N: "N = add_mset (f a) N1" using multi_member_split by metis
  3793   have "image_mset f M = N1" using assms unfolding N by simp
  3794   thus ?thesis using N by blast
  3795 qed
  3796 
  3797 lemma msed_map_invR:
  3798   assumes "image_mset f M = add_mset b N"
  3799   shows "\<exists>M1 a. M = add_mset a M1 \<and> f a = b \<and> image_mset f M1 = N"
  3800 proof -
  3801   obtain a where a: "a \<in># M" and fa: "f a = b"
  3802     using multiset.set_map[of f M] unfolding assms
  3803     by (metis image_iff union_single_eq_member)
  3804   then obtain M1 where M: "M = add_mset a M1" using multi_member_split by metis
  3805   have "image_mset f M1 = N" using assms unfolding M fa[symmetric] by simp
  3806   thus ?thesis using M fa by blast
  3807 qed
  3808 
  3809 lemma msed_rel_invL:
  3810   assumes "rel_mset R (add_mset a M) N"
  3811   shows "\<exists>N1 b. N = add_mset b N1 \<and> R a b \<and> rel_mset R M N1"
  3812 proof -
  3813   obtain K where KM: "image_mset fst K = add_mset a M"
  3814     and KN: "image_mset snd K = N" and sK: "set_mset K \<subseteq> {(a, b). R a b}"
  3815     using assms
  3816     unfolding multiset.rel_compp_Grp Grp_def by auto
  3817   obtain K1 ab where K: "K = add_mset ab K1" and a: "fst ab = a"
  3818     and K1M: "image_mset fst K1 = M" using msed_map_invR[OF KM] by auto
  3819   obtain N1 where N: "N = add_mset (snd ab) N1" and K1N1: "image_mset snd K1 = N1"
  3820     using msed_map_invL[OF KN[unfolded K]] by auto
  3821   have Rab: "R a (snd ab)" using sK a unfolding K by auto
  3822   have "rel_mset R M N1" using sK K1M K1N1
  3823     unfolding K multiset.rel_compp_Grp Grp_def by auto
  3824   thus ?thesis using N Rab by auto
  3825 qed
  3826 
  3827 lemma msed_rel_invR:
  3828   assumes "rel_mset R M (add_mset b N)"
  3829   shows "\<exists>M1 a. M = add_mset a M1 \<and> R a b \<and> rel_mset R M1 N"
  3830 proof -
  3831   obtain K where KN: "image_mset snd K = add_mset b N"
  3832     and KM: "image_mset fst K = M" and sK: "set_mset K \<subseteq> {(a, b). R a b}"
  3833     using assms
  3834     unfolding multiset.rel_compp_Grp Grp_def by auto
  3835   obtain K1 ab where K: "K = add_mset ab K1" and b: "snd ab = b"
  3836     and K1N: "image_mset snd K1 = N" using msed_map_invR[OF KN] by auto
  3837   obtain M1 where M: "M = add_mset (fst ab) M1" and K1M1: "image_mset fst K1 = M1"
  3838     using msed_map_invL[OF KM[unfolded K]] by auto
  3839   have Rab: "R (fst ab) b" using sK b unfolding K by auto
  3840   have "rel_mset R M1 N" using sK K1N K1M1
  3841     unfolding K multiset.rel_compp_Grp Grp_def by auto
  3842   thus ?thesis using M Rab by auto
  3843 qed
  3844 
  3845 lemma rel_mset_imp_rel_mset':
  3846   assumes "rel_mset R M N"
  3847   shows "rel_mset' R M N"
  3848 using assms proof(induct M arbitrary: N rule: measure_induct_rule[of size])
  3849   case (less M)
  3850   have c: "size M = size N" using rel_mset_size[OF less.prems] .
  3851   show ?case
  3852   proof(cases "M = {#}")
  3853     case True hence "N = {#}" using c by simp
  3854     thus ?thesis using True rel_mset'.Zero by auto
  3855   next
  3856     case False then obtain M1 a where M: "M = add_mset a M1" by (metis multi_nonempty_split)
  3857     obtain N1 b where N: "N = add_mset b N1" and R: "R a b" and ms: "rel_mset R M1 N1"
  3858       using msed_rel_invL[OF less.prems[unfolded M]] by auto
  3859     have "rel_mset' R M1 N1" using less.hyps[of M1 N1] ms unfolding M by simp
  3860     thus ?thesis using rel_mset'.Plus[of R a b, OF R] unfolding M N by simp
  3861   qed
  3862 qed
  3863 
  3864 lemma rel_mset_rel_mset': "rel_mset R M N = rel_mset' R M N"
  3865   using rel_mset_imp_rel_mset' rel_mset'_imp_rel_mset by auto
  3866 
  3867 text \<open>The main end product for \<^const>\<open>rel_mset\<close>: inductive characterization:\<close>
  3868 lemmas rel_mset_induct[case_names empty add, induct pred: rel_mset] =
  3869   rel_mset'.induct[unfolded rel_mset_rel_mset'[symmetric]]
  3870 
  3871 
  3872 subsection \<open>Size setup\<close>
  3873 
  3874 lemma size_multiset_o_map: "size_multiset g \<circ> image_mset f = size_multiset (g \<circ> f)"
  3875   apply (rule ext)
  3876   subgoal for x by (induct x) auto
  3877   done
  3878 
  3879 setup \<open>
  3880   BNF_LFP_Size.register_size_global \<^type_name>\<open>multiset\<close> \<^const_name>\<open>size_multiset\<close>
  3881     @{thm size_multiset_overloaded_def}
  3882     @{thms size_multiset_empty size_multiset_single size_multiset_union size_empty size_single
  3883       size_union}
  3884     @{thms size_multiset_o_map}
  3885 \<close>
  3886 
  3887 subsection \<open>Lemmas about Size\<close>
  3888 
  3889 lemma size_mset_SucE: "size A = Suc n \<Longrightarrow> (\<And>a B. A = {#a#} + B \<Longrightarrow> size B = n \<Longrightarrow> P) \<Longrightarrow> P"
  3890   by (cases A) (auto simp add: ac_simps)
  3891 
  3892 lemma size_Suc_Diff1: "x \<in># M \<Longrightarrow> Suc (size (M - {#x#})) = size M"
  3893   using arg_cong[OF insert_DiffM, of _ _ size] by simp
  3894 
  3895 lemma size_Diff_singleton: "x \<in># M \<Longrightarrow> size (M - {#x#}) = size M - 1"
  3896   by (simp flip: size_Suc_Diff1)
  3897 
  3898 lemma size_Diff_singleton_if: "size (A - {#x#}) = (if x \<in># A then size A - 1 else size A)"
  3899   by (simp add: diff_single_trivial size_Diff_singleton)
  3900 
  3901 lemma size_Un_Int: "size A + size B = size (A \<union># B) + size (A \<inter># B)"
  3902   by (metis inter_subset_eq_union size_union subset_mset.diff_add union_diff_inter_eq_sup)
  3903 
  3904 lemma size_Un_disjoint: "A \<inter># B = {#} \<Longrightarrow> size (A \<union># B) = size A + size B"
  3905   using size_Un_Int[of A B] by simp
  3906 
  3907 lemma size_Diff_subset_Int: "size (M - M') = size M - size (M \<inter># M')"
  3908   by (metis diff_intersect_left_idem size_Diff_submset subset_mset.inf_le1)
  3909 
  3910 lemma diff_size_le_size_Diff: "size (M :: _ multiset) - size M' \<le> size (M - M')"
  3911   by (simp add: diff_le_mono2 size_Diff_subset_Int size_mset_mono)
  3912 
  3913 lemma size_Diff1_less: "x\<in># M \<Longrightarrow> size (M - {#x#}) < size M"
  3914   by (rule Suc_less_SucD) (simp add: size_Suc_Diff1)
  3915 
  3916 lemma size_Diff2_less: "x\<in># M \<Longrightarrow> y\<in># M \<Longrightarrow> size (M - {#x#} - {#y#}) < size M"
  3917   by (metis less_imp_diff_less size_Diff1_less size_Diff_subset_Int)
  3918 
  3919 lemma size_Diff1_le: "size (M - {#x#}) \<le> size M"
  3920   by (cases "x \<in># M") (simp_all add: size_Diff1_less less_imp_le diff_single_trivial)
  3921 
  3922 lemma size_psubset: "M \<subseteq># M' \<Longrightarrow> size M < size M' \<Longrightarrow> M \<subset># M'"
  3923   using less_irrefl subset_mset_def by blast
  3924 
  3925 hide_const (open) wcount
  3926 
  3927 end