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