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