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