src/HOL/Library/Multiset.thy
author haftmann
Mon Jul 07 08:47:17 2008 +0200 (2008-07-07)
changeset 27487 c8a6ce181805
parent 27368 9f90ac19e32b
child 27611 2c01c0bdb385
permissions -rw-r--r--
absolute imports of HOL/*.thy theories
     1 (*  Title:      HOL/Library/Multiset.thy
     2     ID:         $Id$
     3     Author:     Tobias Nipkow, Markus Wenzel, Lawrence C Paulson, Norbert Voelker
     4 *)
     5 
     6 header {* Multisets *}
     7 
     8 theory Multiset
     9 imports Plain "~~/src/HOL/List"
    10 begin
    11 
    12 subsection {* The type of multisets *}
    13 
    14 typedef 'a multiset = "{f::'a => nat. finite {x . f x > 0}}"
    15 proof
    16   show "(\<lambda>x. 0::nat) \<in> ?multiset" by simp
    17 qed
    18 
    19 lemmas multiset_typedef [simp] =
    20     Abs_multiset_inverse Rep_multiset_inverse Rep_multiset
    21   and [simp] = Rep_multiset_inject [symmetric]
    22 
    23 definition
    24   Mempty :: "'a multiset"  ("{#}") where
    25   "{#} = Abs_multiset (\<lambda>a. 0)"
    26 
    27 definition
    28   single :: "'a => 'a multiset" where
    29   "single a = Abs_multiset (\<lambda>b. if b = a then 1 else 0)"
    30 
    31 declare
    32   Mempty_def[code func del] single_def[code func del]
    33 
    34 definition
    35   count :: "'a multiset => 'a => nat" where
    36   "count = Rep_multiset"
    37 
    38 definition
    39   MCollect :: "'a multiset => ('a => bool) => 'a multiset" where
    40   "MCollect M P = Abs_multiset (\<lambda>x. if P x then Rep_multiset M x else 0)"
    41 
    42 abbreviation
    43   Melem :: "'a => 'a multiset => bool"  ("(_/ :# _)" [50, 51] 50) where
    44   "a :# M == 0 < count M a"
    45 
    46 notation (xsymbols)
    47   Melem (infix "\<in>#" 50)
    48 
    49 syntax
    50   "_MCollect" :: "pttrn => 'a multiset => bool => 'a multiset"    ("(1{# _ :# _./ _#})")
    51 translations
    52   "{#x :# M. P#}" == "CONST MCollect M (\<lambda>x. P)"
    53 
    54 definition
    55   set_of :: "'a multiset => 'a set" where
    56   "set_of M = {x. x :# M}"
    57 
    58 instantiation multiset :: (type) "{plus, minus, zero, size}" 
    59 begin
    60 
    61 definition
    62   union_def[code func del]:
    63   "M + N = Abs_multiset (\<lambda>a. Rep_multiset M a + Rep_multiset N a)"
    64 
    65 definition
    66   diff_def: "M - N = Abs_multiset (\<lambda>a. Rep_multiset M a - Rep_multiset N a)"
    67 
    68 definition
    69   Zero_multiset_def [simp]: "0 = {#}"
    70 
    71 definition
    72   size_def[code func del]: "size M = setsum (count M) (set_of M)"
    73 
    74 instance ..
    75 
    76 end
    77 
    78 definition
    79   multiset_inter :: "'a multiset \<Rightarrow> 'a multiset \<Rightarrow> 'a multiset"  (infixl "#\<inter>" 70) where
    80   "multiset_inter A B = A - (A - B)"
    81 
    82 text {* Multiset Enumeration *}
    83 syntax
    84   "_multiset" :: "args => 'a multiset"    ("{#(_)#}")
    85 translations
    86   "{#x, xs#}" == "{#x#} + {#xs#}"
    87   "{#x#}" == "CONST single x"
    88 
    89 
    90 text {*
    91  \medskip Preservation of the representing set @{term multiset}.
    92 *}
    93 
    94 lemma const0_in_multiset: "(\<lambda>a. 0) \<in> multiset"
    95 by (simp add: multiset_def)
    96 
    97 lemma only1_in_multiset: "(\<lambda>b. if b = a then 1 else 0) \<in> multiset"
    98 by (simp add: multiset_def)
    99 
   100 lemma union_preserves_multiset:
   101   "M \<in> multiset ==> N \<in> multiset ==> (\<lambda>a. M a + N a) \<in> multiset"
   102 apply (simp add: multiset_def)
   103 apply (drule (1) finite_UnI)
   104 apply (simp del: finite_Un add: Un_def)
   105 done
   106 
   107 lemma diff_preserves_multiset:
   108   "M \<in> multiset ==> (\<lambda>a. M a - N a) \<in> multiset"
   109 apply (simp add: multiset_def)
   110 apply (rule finite_subset)
   111  apply auto
   112 done
   113 
   114 lemma MCollect_preserves_multiset:
   115   "M \<in> multiset ==> (\<lambda>x. if P x then M x else 0) \<in> multiset"
   116 apply (simp add: multiset_def)
   117 apply (rule finite_subset, auto)
   118 done
   119 
   120 lemmas in_multiset = const0_in_multiset only1_in_multiset
   121   union_preserves_multiset diff_preserves_multiset MCollect_preserves_multiset
   122 
   123 
   124 subsection {* Algebraic properties *}
   125 
   126 subsubsection {* Union *}
   127 
   128 lemma union_empty [simp]: "M + {#} = M \<and> {#} + M = M"
   129 by (simp add: union_def Mempty_def in_multiset)
   130 
   131 lemma union_commute: "M + N = N + (M::'a multiset)"
   132 by (simp add: union_def add_ac in_multiset)
   133 
   134 lemma union_assoc: "(M + N) + K = M + (N + (K::'a multiset))"
   135 by (simp add: union_def add_ac in_multiset)
   136 
   137 lemma union_lcomm: "M + (N + K) = N + (M + (K::'a multiset))"
   138 proof -
   139   have "M + (N + K) = (N + K) + M" by (rule union_commute)
   140   also have "\<dots> = N + (K + M)" by (rule union_assoc)
   141   also have "K + M = M + K" by (rule union_commute)
   142   finally show ?thesis .
   143 qed
   144 
   145 lemmas union_ac = union_assoc union_commute union_lcomm
   146 
   147 instance multiset :: (type) comm_monoid_add
   148 proof
   149   fix a b c :: "'a multiset"
   150   show "(a + b) + c = a + (b + c)" by (rule union_assoc)
   151   show "a + b = b + a" by (rule union_commute)
   152   show "0 + a = a" by simp
   153 qed
   154 
   155 
   156 subsubsection {* Difference *}
   157 
   158 lemma diff_empty [simp]: "M - {#} = M \<and> {#} - M = {#}"
   159 by (simp add: Mempty_def diff_def in_multiset)
   160 
   161 lemma diff_union_inverse2 [simp]: "M + {#a#} - {#a#} = M"
   162 by (simp add: union_def diff_def in_multiset)
   163 
   164 lemma diff_cancel: "A - A = {#}"
   165 by (simp add: diff_def Mempty_def)
   166 
   167 
   168 subsubsection {* Count of elements *}
   169 
   170 lemma count_empty [simp]: "count {#} a = 0"
   171 by (simp add: count_def Mempty_def in_multiset)
   172 
   173 lemma count_single [simp]: "count {#b#} a = (if b = a then 1 else 0)"
   174 by (simp add: count_def single_def in_multiset)
   175 
   176 lemma count_union [simp]: "count (M + N) a = count M a + count N a"
   177 by (simp add: count_def union_def in_multiset)
   178 
   179 lemma count_diff [simp]: "count (M - N) a = count M a - count N a"
   180 by (simp add: count_def diff_def in_multiset)
   181 
   182 lemma count_MCollect [simp]:
   183   "count {# x:#M. P x #} a = (if P a then count M a else 0)"
   184 by (simp add: count_def MCollect_def in_multiset)
   185 
   186 
   187 subsubsection {* Set of elements *}
   188 
   189 lemma set_of_empty [simp]: "set_of {#} = {}"
   190 by (simp add: set_of_def)
   191 
   192 lemma set_of_single [simp]: "set_of {#b#} = {b}"
   193 by (simp add: set_of_def)
   194 
   195 lemma set_of_union [simp]: "set_of (M + N) = set_of M \<union> set_of N"
   196 by (auto simp add: set_of_def)
   197 
   198 lemma set_of_eq_empty_iff [simp]: "(set_of M = {}) = (M = {#})"
   199 by (auto simp: set_of_def Mempty_def in_multiset count_def expand_fun_eq [where f="Rep_multiset M"])
   200 
   201 lemma mem_set_of_iff [simp]: "(x \<in> set_of M) = (x :# M)"
   202 by (auto simp add: set_of_def)
   203 
   204 lemma set_of_MCollect [simp]: "set_of {# x:#M. P x #} = set_of M \<inter> {x. P x}"
   205 by (auto simp add: set_of_def)
   206 
   207 
   208 subsubsection {* Size *}
   209 
   210 lemma size_empty [simp,code func]: "size {#} = 0"
   211 by (simp add: size_def)
   212 
   213 lemma size_single [simp,code func]: "size {#b#} = 1"
   214 by (simp add: size_def)
   215 
   216 lemma finite_set_of [iff]: "finite (set_of M)"
   217 using Rep_multiset [of M] by (simp add: multiset_def set_of_def count_def)
   218 
   219 lemma setsum_count_Int:
   220   "finite A ==> setsum (count N) (A \<inter> set_of N) = setsum (count N) A"
   221 apply (induct rule: finite_induct)
   222  apply simp
   223 apply (simp add: Int_insert_left set_of_def)
   224 done
   225 
   226 lemma size_union[simp,code func]: "size (M + N::'a multiset) = size M + size N"
   227 apply (unfold size_def)
   228 apply (subgoal_tac "count (M + N) = (\<lambda>a. count M a + count N a)")
   229  prefer 2
   230  apply (rule ext, simp)
   231 apply (simp (no_asm_simp) add: setsum_Un_nat setsum_addf setsum_count_Int)
   232 apply (subst Int_commute)
   233 apply (simp (no_asm_simp) add: setsum_count_Int)
   234 done
   235 
   236 lemma size_eq_0_iff_empty [iff]: "(size M = 0) = (M = {#})"
   237 apply (unfold size_def Mempty_def count_def, auto simp: in_multiset)
   238 apply (simp add: set_of_def count_def in_multiset expand_fun_eq)
   239 done
   240 
   241 lemma nonempty_has_size: "(S \<noteq> {#}) = (0 < size S)"
   242 by (metis gr0I gr_implies_not0 size_empty size_eq_0_iff_empty)
   243 
   244 lemma size_eq_Suc_imp_elem: "size M = Suc n ==> \<exists>a. a :# M"
   245 apply (unfold size_def)
   246 apply (drule setsum_SucD)
   247 apply auto
   248 done
   249 
   250 
   251 subsubsection {* Equality of multisets *}
   252 
   253 lemma multiset_eq_conv_count_eq: "(M = N) = (\<forall>a. count M a = count N a)"
   254 by (simp add: count_def expand_fun_eq)
   255 
   256 lemma single_not_empty [simp]: "{#a#} \<noteq> {#} \<and> {#} \<noteq> {#a#}"
   257 by (simp add: single_def Mempty_def in_multiset expand_fun_eq)
   258 
   259 lemma single_eq_single [simp]: "({#a#} = {#b#}) = (a = b)"
   260 by (auto simp add: single_def in_multiset expand_fun_eq)
   261 
   262 lemma union_eq_empty [iff]: "(M + N = {#}) = (M = {#} \<and> N = {#})"
   263 by (auto simp add: union_def Mempty_def in_multiset expand_fun_eq)
   264 
   265 lemma empty_eq_union [iff]: "({#} = M + N) = (M = {#} \<and> N = {#})"
   266 by (auto simp add: union_def Mempty_def in_multiset expand_fun_eq)
   267 
   268 lemma union_right_cancel [simp]: "(M + K = N + K) = (M = (N::'a multiset))"
   269 by (simp add: union_def in_multiset expand_fun_eq)
   270 
   271 lemma union_left_cancel [simp]: "(K + M = K + N) = (M = (N::'a multiset))"
   272 by (simp add: union_def in_multiset expand_fun_eq)
   273 
   274 lemma union_is_single:
   275   "(M + N = {#a#}) = (M = {#a#} \<and> N={#} \<or> M = {#} \<and> N = {#a#})"
   276 apply (simp add: Mempty_def single_def union_def in_multiset add_is_1 expand_fun_eq)
   277 apply blast
   278 done
   279 
   280 lemma single_is_union:
   281   "({#a#} = M + N) \<longleftrightarrow> ({#a#} = M \<and> N = {#} \<or> M = {#} \<and> {#a#} = N)"
   282 apply (unfold Mempty_def single_def union_def)
   283 apply (simp add: add_is_1 one_is_add in_multiset expand_fun_eq)
   284 apply (blast dest: sym)
   285 done
   286 
   287 lemma add_eq_conv_diff:
   288   "(M + {#a#} = N + {#b#}) =
   289    (M = N \<and> a = b \<or> M = N - {#a#} + {#b#} \<and> N = M - {#b#} + {#a#})"
   290 using [[simproc del: neq]]
   291 apply (unfold single_def union_def diff_def)
   292 apply (simp (no_asm) add: in_multiset expand_fun_eq)
   293 apply (rule conjI, force, safe, simp_all)
   294 apply (simp add: eq_sym_conv)
   295 done
   296 
   297 declare Rep_multiset_inject [symmetric, simp del]
   298 
   299 instance multiset :: (type) cancel_ab_semigroup_add
   300 proof
   301   fix a b c :: "'a multiset"
   302   show "a + b = a + c \<Longrightarrow> b = c" by simp
   303 qed
   304 
   305 lemma insert_DiffM:
   306   "x \<in># M \<Longrightarrow> {#x#} + (M - {#x#}) = M"
   307 by (clarsimp simp: multiset_eq_conv_count_eq)
   308 
   309 lemma insert_DiffM2[simp]:
   310   "x \<in># M \<Longrightarrow> M - {#x#} + {#x#} = M"
   311 by (clarsimp simp: multiset_eq_conv_count_eq)
   312 
   313 lemma multi_union_self_other_eq: 
   314   "(A::'a multiset) + X = A + Y \<Longrightarrow> X = Y"
   315 by (induct A arbitrary: X Y) auto
   316 
   317 lemma multi_self_add_other_not_self[simp]: "(A = A + {#x#}) = False"
   318 by (metis single_not_empty union_empty union_left_cancel)
   319 
   320 lemma insert_noteq_member: 
   321   assumes BC: "B + {#b#} = C + {#c#}"
   322    and bnotc: "b \<noteq> c"
   323   shows "c \<in># B"
   324 proof -
   325   have "c \<in># C + {#c#}" by simp
   326   have nc: "\<not> c \<in># {#b#}" using bnotc by simp
   327   then have "c \<in># B + {#b#}" using BC by simp
   328   then show "c \<in># B" using nc by simp
   329 qed
   330 
   331 
   332 lemma add_eq_conv_ex:
   333   "(M + {#a#} = N + {#b#}) =
   334     (M = N \<and> a = b \<or> (\<exists>K. M = K + {#b#} \<and> N = K + {#a#}))"
   335 by (auto simp add: add_eq_conv_diff)
   336 
   337 
   338 lemma empty_multiset_count:
   339   "(\<forall>x. count A x = 0) = (A = {#})"
   340 by (metis count_empty multiset_eq_conv_count_eq)
   341 
   342 
   343 subsubsection {* Intersection *}
   344 
   345 lemma multiset_inter_count:
   346   "count (A #\<inter> B) x = min (count A x) (count B x)"
   347 by (simp add: multiset_inter_def min_def)
   348 
   349 lemma multiset_inter_commute: "A #\<inter> B = B #\<inter> A"
   350 by (simp add: multiset_eq_conv_count_eq multiset_inter_count
   351     min_max.inf_commute)
   352 
   353 lemma multiset_inter_assoc: "A #\<inter> (B #\<inter> C) = A #\<inter> B #\<inter> C"
   354 by (simp add: multiset_eq_conv_count_eq multiset_inter_count
   355     min_max.inf_assoc)
   356 
   357 lemma multiset_inter_left_commute: "A #\<inter> (B #\<inter> C) = B #\<inter> (A #\<inter> C)"
   358 by (simp add: multiset_eq_conv_count_eq multiset_inter_count min_def)
   359 
   360 lemmas multiset_inter_ac =
   361   multiset_inter_commute
   362   multiset_inter_assoc
   363   multiset_inter_left_commute
   364 
   365 lemma multiset_inter_single: "a \<noteq> b \<Longrightarrow> {#a#} #\<inter> {#b#} = {#}"
   366 by (simp add: multiset_eq_conv_count_eq multiset_inter_count)
   367 
   368 lemma multiset_union_diff_commute: "B #\<inter> C = {#} \<Longrightarrow> A + B - C = A - C + B"
   369 apply (simp add: multiset_eq_conv_count_eq multiset_inter_count min_def
   370     split: split_if_asm)
   371 apply clarsimp
   372 apply (erule_tac x = a in allE)
   373 apply auto
   374 done
   375 
   376 
   377 subsubsection {* Comprehension (filter) *}
   378 
   379 lemma MCollect_empty[simp, code func]: "MCollect {#} P = {#}"
   380 by (simp add: MCollect_def Mempty_def Abs_multiset_inject
   381     in_multiset expand_fun_eq)
   382 
   383 lemma MCollect_single[simp, code func]:
   384   "MCollect {#x#} P = (if P x then {#x#} else {#})"
   385 by (simp add: MCollect_def Mempty_def single_def Abs_multiset_inject
   386     in_multiset expand_fun_eq)
   387 
   388 lemma MCollect_union[simp, code func]:
   389   "MCollect (M+N) f = MCollect M f + MCollect N f"
   390 by (simp add: MCollect_def union_def Abs_multiset_inject
   391     in_multiset expand_fun_eq)
   392 
   393 
   394 subsection {* Induction and case splits *}
   395 
   396 lemma setsum_decr:
   397   "finite F ==> (0::nat) < f a ==>
   398     setsum (f (a := f a - 1)) F = (if a\<in>F then setsum f F - 1 else setsum f F)"
   399 apply (induct rule: finite_induct)
   400  apply auto
   401 apply (drule_tac a = a in mk_disjoint_insert, auto)
   402 done
   403 
   404 lemma rep_multiset_induct_aux:
   405 assumes 1: "P (\<lambda>a. (0::nat))"
   406   and 2: "!!f b. f \<in> multiset ==> P f ==> P (f (b := f b + 1))"
   407 shows "\<forall>f. f \<in> multiset --> setsum f {x. f x \<noteq> 0} = n --> P f"
   408 apply (unfold multiset_def)
   409 apply (induct_tac n, simp, clarify)
   410  apply (subgoal_tac "f = (\<lambda>a.0)")
   411   apply simp
   412   apply (rule 1)
   413  apply (rule ext, force, clarify)
   414 apply (frule setsum_SucD, clarify)
   415 apply (rename_tac a)
   416 apply (subgoal_tac "finite {x. (f (a := f a - 1)) x > 0}")
   417  prefer 2
   418  apply (rule finite_subset)
   419   prefer 2
   420   apply assumption
   421  apply simp
   422  apply blast
   423 apply (subgoal_tac "f = (f (a := f a - 1))(a := (f (a := f a - 1)) a + 1)")
   424  prefer 2
   425  apply (rule ext)
   426  apply (simp (no_asm_simp))
   427  apply (erule ssubst, rule 2 [unfolded multiset_def], blast)
   428 apply (erule allE, erule impE, erule_tac [2] mp, blast)
   429 apply (simp (no_asm_simp) add: setsum_decr del: fun_upd_apply One_nat_def)
   430 apply (subgoal_tac "{x. x \<noteq> a --> f x \<noteq> 0} = {x. f x \<noteq> 0}")
   431  prefer 2
   432  apply blast
   433 apply (subgoal_tac "{x. x \<noteq> a \<and> f x \<noteq> 0} = {x. f x \<noteq> 0} - {a}")
   434  prefer 2
   435  apply blast
   436 apply (simp add: le_imp_diff_is_add setsum_diff1_nat cong: conj_cong)
   437 done
   438 
   439 theorem rep_multiset_induct:
   440   "f \<in> multiset ==> P (\<lambda>a. 0) ==>
   441     (!!f b. f \<in> multiset ==> P f ==> P (f (b := f b + 1))) ==> P f"
   442 using rep_multiset_induct_aux by blast
   443 
   444 theorem multiset_induct [case_names empty add, induct type: multiset]:
   445 assumes empty: "P {#}"
   446   and add: "!!M x. P M ==> P (M + {#x#})"
   447 shows "P M"
   448 proof -
   449   note defns = union_def single_def Mempty_def
   450   show ?thesis
   451     apply (rule Rep_multiset_inverse [THEN subst])
   452     apply (rule Rep_multiset [THEN rep_multiset_induct])
   453      apply (rule empty [unfolded defns])
   454     apply (subgoal_tac "f(b := f b + 1) = (\<lambda>a. f a + (if a=b then 1 else 0))")
   455      prefer 2
   456      apply (simp add: expand_fun_eq)
   457     apply (erule ssubst)
   458     apply (erule Abs_multiset_inverse [THEN subst])
   459     apply (drule add [unfolded defns, simplified])
   460     apply(simp add:in_multiset)
   461     done
   462 qed
   463 
   464 lemma multi_nonempty_split: "M \<noteq> {#} \<Longrightarrow> \<exists>A a. M = A + {#a#}"
   465 by (induct M) auto
   466 
   467 lemma multiset_cases [cases type, case_names empty add]:
   468 assumes em:  "M = {#} \<Longrightarrow> P"
   469 assumes add: "\<And>N x. M = N + {#x#} \<Longrightarrow> P"
   470 shows "P"
   471 proof (cases "M = {#}")
   472   assume "M = {#}" then show ?thesis using em by simp
   473 next
   474   assume "M \<noteq> {#}"
   475   then obtain M' m where "M = M' + {#m#}" 
   476     by (blast dest: multi_nonempty_split)
   477   then show ?thesis using add by simp
   478 qed
   479 
   480 lemma multi_member_split: "x \<in># M \<Longrightarrow> \<exists>A. M = A + {#x#}"
   481 apply (cases M)
   482  apply simp
   483 apply (rule_tac x="M - {#x#}" in exI, simp)
   484 done
   485 
   486 lemma multiset_partition: "M = {# x:#M. P x #} + {# x:#M. \<not> P x #}"
   487 apply (subst multiset_eq_conv_count_eq)
   488 apply auto
   489 done
   490 
   491 declare multiset_typedef [simp del]
   492 
   493 lemma multi_drop_mem_not_eq: "c \<in># B \<Longrightarrow> B - {#c#} \<noteq> B"
   494 by (cases "B = {#}") (auto dest: multi_member_split)
   495 
   496 
   497 subsection {* Orderings *}
   498 
   499 subsubsection {* Well-foundedness *}
   500 
   501 definition
   502   mult1 :: "('a \<times> 'a) set => ('a multiset \<times> 'a multiset) set" where
   503   [code func del]:"mult1 r =
   504     {(N, M). \<exists>a M0 K. M = M0 + {#a#} \<and> N = M0 + K \<and>
   505       (\<forall>b. b :# K --> (b, a) \<in> r)}"
   506 
   507 definition
   508   mult :: "('a \<times> 'a) set => ('a multiset \<times> 'a multiset) set" where
   509   "mult r = (mult1 r)\<^sup>+"
   510 
   511 lemma not_less_empty [iff]: "(M, {#}) \<notin> mult1 r"
   512 by (simp add: mult1_def)
   513 
   514 lemma less_add: "(N, M0 + {#a#}) \<in> mult1 r ==>
   515     (\<exists>M. (M, M0) \<in> mult1 r \<and> N = M + {#a#}) \<or>
   516     (\<exists>K. (\<forall>b. b :# K --> (b, a) \<in> r) \<and> N = M0 + K)"
   517   (is "_ \<Longrightarrow> ?case1 (mult1 r) \<or> ?case2")
   518 proof (unfold mult1_def)
   519   let ?r = "\<lambda>K a. \<forall>b. b :# K --> (b, a) \<in> r"
   520   let ?R = "\<lambda>N M. \<exists>a M0 K. M = M0 + {#a#} \<and> N = M0 + K \<and> ?r K a"
   521   let ?case1 = "?case1 {(N, M). ?R N M}"
   522 
   523   assume "(N, M0 + {#a#}) \<in> {(N, M). ?R N M}"
   524   then have "\<exists>a' M0' K.
   525       M0 + {#a#} = M0' + {#a'#} \<and> N = M0' + K \<and> ?r K a'" by simp
   526   then show "?case1 \<or> ?case2"
   527   proof (elim exE conjE)
   528     fix a' M0' K
   529     assume N: "N = M0' + K" and r: "?r K a'"
   530     assume "M0 + {#a#} = M0' + {#a'#}"
   531     then have "M0 = M0' \<and> a = a' \<or>
   532         (\<exists>K'. M0 = K' + {#a'#} \<and> M0' = K' + {#a#})"
   533       by (simp only: add_eq_conv_ex)
   534     then show ?thesis
   535     proof (elim disjE conjE exE)
   536       assume "M0 = M0'" "a = a'"
   537       with N r have "?r K a \<and> N = M0 + K" by simp
   538       then have ?case2 .. then show ?thesis ..
   539     next
   540       fix K'
   541       assume "M0' = K' + {#a#}"
   542       with N have n: "N = K' + K + {#a#}" by (simp add: union_ac)
   543 
   544       assume "M0 = K' + {#a'#}"
   545       with r have "?R (K' + K) M0" by blast
   546       with n have ?case1 by simp then show ?thesis ..
   547     qed
   548   qed
   549 qed
   550 
   551 lemma all_accessible: "wf r ==> \<forall>M. M \<in> acc (mult1 r)"
   552 proof
   553   let ?R = "mult1 r"
   554   let ?W = "acc ?R"
   555   {
   556     fix M M0 a
   557     assume M0: "M0 \<in> ?W"
   558       and wf_hyp: "!!b. (b, a) \<in> r ==> (\<forall>M \<in> ?W. M + {#b#} \<in> ?W)"
   559       and acc_hyp: "\<forall>M. (M, M0) \<in> ?R --> M + {#a#} \<in> ?W"
   560     have "M0 + {#a#} \<in> ?W"
   561     proof (rule accI [of "M0 + {#a#}"])
   562       fix N
   563       assume "(N, M0 + {#a#}) \<in> ?R"
   564       then have "((\<exists>M. (M, M0) \<in> ?R \<and> N = M + {#a#}) \<or>
   565           (\<exists>K. (\<forall>b. b :# K --> (b, a) \<in> r) \<and> N = M0 + K))"
   566         by (rule less_add)
   567       then show "N \<in> ?W"
   568       proof (elim exE disjE conjE)
   569         fix M assume "(M, M0) \<in> ?R" and N: "N = M + {#a#}"
   570         from acc_hyp have "(M, M0) \<in> ?R --> M + {#a#} \<in> ?W" ..
   571         from this and `(M, M0) \<in> ?R` have "M + {#a#} \<in> ?W" ..
   572         then show "N \<in> ?W" by (simp only: N)
   573       next
   574         fix K
   575         assume N: "N = M0 + K"
   576         assume "\<forall>b. b :# K --> (b, a) \<in> r"
   577         then have "M0 + K \<in> ?W"
   578         proof (induct K)
   579           case empty
   580           from M0 show "M0 + {#} \<in> ?W" by simp
   581         next
   582           case (add K x)
   583           from add.prems have "(x, a) \<in> r" by simp
   584           with wf_hyp have "\<forall>M \<in> ?W. M + {#x#} \<in> ?W" by blast
   585           moreover from add have "M0 + K \<in> ?W" by simp
   586           ultimately have "(M0 + K) + {#x#} \<in> ?W" ..
   587           then show "M0 + (K + {#x#}) \<in> ?W" by (simp only: union_assoc)
   588         qed
   589         then show "N \<in> ?W" by (simp only: N)
   590       qed
   591     qed
   592   } note tedious_reasoning = this
   593 
   594   assume wf: "wf r"
   595   fix M
   596   show "M \<in> ?W"
   597   proof (induct M)
   598     show "{#} \<in> ?W"
   599     proof (rule accI)
   600       fix b assume "(b, {#}) \<in> ?R"
   601       with not_less_empty show "b \<in> ?W" by contradiction
   602     qed
   603 
   604     fix M a assume "M \<in> ?W"
   605     from wf have "\<forall>M \<in> ?W. M + {#a#} \<in> ?W"
   606     proof induct
   607       fix a
   608       assume r: "!!b. (b, a) \<in> r ==> (\<forall>M \<in> ?W. M + {#b#} \<in> ?W)"
   609       show "\<forall>M \<in> ?W. M + {#a#} \<in> ?W"
   610       proof
   611         fix M assume "M \<in> ?W"
   612         then show "M + {#a#} \<in> ?W"
   613           by (rule acc_induct) (rule tedious_reasoning [OF _ r])
   614       qed
   615     qed
   616     from this and `M \<in> ?W` show "M + {#a#} \<in> ?W" ..
   617   qed
   618 qed
   619 
   620 theorem wf_mult1: "wf r ==> wf (mult1 r)"
   621 by (rule acc_wfI) (rule all_accessible)
   622 
   623 theorem wf_mult: "wf r ==> wf (mult r)"
   624 unfolding mult_def by (rule wf_trancl) (rule wf_mult1)
   625 
   626 
   627 subsubsection {* Closure-free presentation *}
   628 
   629 (*Badly needed: a linear arithmetic procedure for multisets*)
   630 
   631 lemma diff_union_single_conv: "a :# J ==> I + J - {#a#} = I + (J - {#a#})"
   632 by (simp add: multiset_eq_conv_count_eq)
   633 
   634 text {* One direction. *}
   635 
   636 lemma mult_implies_one_step:
   637   "trans r ==> (M, N) \<in> mult r ==>
   638     \<exists>I J K. N = I + J \<and> M = I + K \<and> J \<noteq> {#} \<and>
   639     (\<forall>k \<in> set_of K. \<exists>j \<in> set_of J. (k, j) \<in> r)"
   640 apply (unfold mult_def mult1_def set_of_def)
   641 apply (erule converse_trancl_induct, clarify)
   642  apply (rule_tac x = M0 in exI, simp, clarify)
   643 apply (case_tac "a :# K")
   644  apply (rule_tac x = I in exI)
   645  apply (simp (no_asm))
   646  apply (rule_tac x = "(K - {#a#}) + Ka" in exI)
   647  apply (simp (no_asm_simp) add: union_assoc [symmetric])
   648  apply (drule_tac f = "\<lambda>M. M - {#a#}" in arg_cong)
   649  apply (simp add: diff_union_single_conv)
   650  apply (simp (no_asm_use) add: trans_def)
   651  apply blast
   652 apply (subgoal_tac "a :# I")
   653  apply (rule_tac x = "I - {#a#}" in exI)
   654  apply (rule_tac x = "J + {#a#}" in exI)
   655  apply (rule_tac x = "K + Ka" in exI)
   656  apply (rule conjI)
   657   apply (simp add: multiset_eq_conv_count_eq split: nat_diff_split)
   658  apply (rule conjI)
   659   apply (drule_tac f = "\<lambda>M. M - {#a#}" in arg_cong, simp)
   660   apply (simp add: multiset_eq_conv_count_eq split: nat_diff_split)
   661  apply (simp (no_asm_use) add: trans_def)
   662  apply blast
   663 apply (subgoal_tac "a :# (M0 + {#a#})")
   664  apply simp
   665 apply (simp (no_asm))
   666 done
   667 
   668 lemma elem_imp_eq_diff_union: "a :# M ==> M = M - {#a#} + {#a#}"
   669 by (simp add: multiset_eq_conv_count_eq)
   670 
   671 lemma size_eq_Suc_imp_eq_union: "size M = Suc n ==> \<exists>a N. M = N + {#a#}"
   672 apply (erule size_eq_Suc_imp_elem [THEN exE])
   673 apply (drule elem_imp_eq_diff_union, auto)
   674 done
   675 
   676 lemma one_step_implies_mult_aux:
   677   "trans r ==>
   678     \<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))
   679       --> (I + K, I + J) \<in> mult r"
   680 apply (induct_tac n, auto)
   681 apply (frule size_eq_Suc_imp_eq_union, clarify)
   682 apply (rename_tac "J'", simp)
   683 apply (erule notE, auto)
   684 apply (case_tac "J' = {#}")
   685  apply (simp add: mult_def)
   686  apply (rule r_into_trancl)
   687  apply (simp add: mult1_def set_of_def, blast)
   688 txt {* Now we know @{term "J' \<noteq> {#}"}. *}
   689 apply (cut_tac M = K and P = "\<lambda>x. (x, a) \<in> r" in multiset_partition)
   690 apply (erule_tac P = "\<forall>k \<in> set_of K. ?P k" in rev_mp)
   691 apply (erule ssubst)
   692 apply (simp add: Ball_def, auto)
   693 apply (subgoal_tac
   694   "((I + {# x :# K. (x, a) \<in> r #}) + {# x :# K. (x, a) \<notin> r #},
   695     (I + {# x :# K. (x, a) \<in> r #}) + J') \<in> mult r")
   696  prefer 2
   697  apply force
   698 apply (simp (no_asm_use) add: union_assoc [symmetric] mult_def)
   699 apply (erule trancl_trans)
   700 apply (rule r_into_trancl)
   701 apply (simp add: mult1_def set_of_def)
   702 apply (rule_tac x = a in exI)
   703 apply (rule_tac x = "I + J'" in exI)
   704 apply (simp add: union_ac)
   705 done
   706 
   707 lemma one_step_implies_mult:
   708   "trans r ==> J \<noteq> {#} ==> \<forall>k \<in> set_of K. \<exists>j \<in> set_of J. (k, j) \<in> r
   709     ==> (I + K, I + J) \<in> mult r"
   710 using one_step_implies_mult_aux by blast
   711 
   712 
   713 subsubsection {* Partial-order properties *}
   714 
   715 instantiation multiset :: (order) order
   716 begin
   717 
   718 definition
   719   less_multiset_def [code func del]: "M' < M \<longleftrightarrow> (M', M) \<in> mult {(x', x). x' < x}"
   720 
   721 definition
   722   le_multiset_def [code func del]: "M' <= M \<longleftrightarrow> M' = M \<or> M' < (M::'a multiset)"
   723 
   724 lemma trans_base_order: "trans {(x', x). x' < (x::'a::order)}"
   725 unfolding trans_def by (blast intro: order_less_trans)
   726 
   727 text {*
   728  \medskip Irreflexivity.
   729 *}
   730 
   731 lemma mult_irrefl_aux:
   732   "finite A ==> (\<forall>x \<in> A. \<exists>y \<in> A. x < (y::'a::order)) \<Longrightarrow> A = {}"
   733 by (induct rule: finite_induct) (auto intro: order_less_trans)
   734 
   735 lemma mult_less_not_refl: "\<not> M < (M::'a::order multiset)"
   736 apply (unfold less_multiset_def, auto)
   737 apply (drule trans_base_order [THEN mult_implies_one_step], auto)
   738 apply (drule finite_set_of [THEN mult_irrefl_aux [rule_format (no_asm)]])
   739 apply (simp add: set_of_eq_empty_iff)
   740 done
   741 
   742 lemma mult_less_irrefl [elim!]: "M < (M::'a::order multiset) ==> R"
   743 using insert mult_less_not_refl by fast
   744 
   745 
   746 text {* Transitivity. *}
   747 
   748 theorem mult_less_trans: "K < M ==> M < N ==> K < (N::'a::order multiset)"
   749 unfolding less_multiset_def mult_def by (blast intro: trancl_trans)
   750 
   751 text {* Asymmetry. *}
   752 
   753 theorem mult_less_not_sym: "M < N ==> \<not> N < (M::'a::order multiset)"
   754 apply auto
   755 apply (rule mult_less_not_refl [THEN notE])
   756 apply (erule mult_less_trans, assumption)
   757 done
   758 
   759 theorem mult_less_asym:
   760   "M < N ==> (\<not> P ==> N < (M::'a::order multiset)) ==> P"
   761 using mult_less_not_sym by blast
   762 
   763 theorem mult_le_refl [iff]: "M <= (M::'a::order multiset)"
   764 unfolding le_multiset_def by auto
   765 
   766 text {* Anti-symmetry. *}
   767 
   768 theorem mult_le_antisym:
   769   "M <= N ==> N <= M ==> M = (N::'a::order multiset)"
   770 unfolding le_multiset_def by (blast dest: mult_less_not_sym)
   771 
   772 text {* Transitivity. *}
   773 
   774 theorem mult_le_trans:
   775   "K <= M ==> M <= N ==> K <= (N::'a::order multiset)"
   776 unfolding le_multiset_def by (blast intro: mult_less_trans)
   777 
   778 theorem mult_less_le: "(M < N) = (M <= N \<and> M \<noteq> (N::'a::order multiset))"
   779 unfolding le_multiset_def by auto
   780 
   781 instance
   782 apply intro_classes
   783    apply (rule mult_less_le)
   784   apply (rule mult_le_refl)
   785  apply (erule mult_le_trans, assumption)
   786 apply (erule mult_le_antisym, assumption)
   787 done
   788 
   789 end
   790 
   791 
   792 subsubsection {* Monotonicity of multiset union *}
   793 
   794 lemma mult1_union:
   795   "(B, D) \<in> mult1 r ==> trans r ==> (C + B, C + D) \<in> mult1 r"
   796 apply (unfold mult1_def)
   797 apply auto
   798 apply (rule_tac x = a in exI)
   799 apply (rule_tac x = "C + M0" in exI)
   800 apply (simp add: union_assoc)
   801 done
   802 
   803 lemma union_less_mono2: "B < D ==> C + B < C + (D::'a::order multiset)"
   804 apply (unfold less_multiset_def mult_def)
   805 apply (erule trancl_induct)
   806  apply (blast intro: mult1_union transI order_less_trans r_into_trancl)
   807 apply (blast intro: mult1_union transI order_less_trans r_into_trancl trancl_trans)
   808 done
   809 
   810 lemma union_less_mono1: "B < D ==> B + C < D + (C::'a::order multiset)"
   811 apply (subst union_commute [of B C])
   812 apply (subst union_commute [of D C])
   813 apply (erule union_less_mono2)
   814 done
   815 
   816 lemma union_less_mono:
   817   "A < C ==> B < D ==> A + B < C + (D::'a::order multiset)"
   818 by (blast intro!: union_less_mono1 union_less_mono2 mult_less_trans)
   819 
   820 lemma union_le_mono:
   821   "A <= C ==> B <= D ==> A + B <= C + (D::'a::order multiset)"
   822 unfolding le_multiset_def
   823 by (blast intro: union_less_mono union_less_mono1 union_less_mono2)
   824 
   825 lemma empty_leI [iff]: "{#} <= (M::'a::order multiset)"
   826 apply (unfold le_multiset_def less_multiset_def)
   827 apply (case_tac "M = {#}")
   828  prefer 2
   829  apply (subgoal_tac "({#} + {#}, {#} + M) \<in> mult (Collect (split op <))")
   830   prefer 2
   831   apply (rule one_step_implies_mult)
   832     apply (simp only: trans_def)
   833     apply auto
   834 done
   835 
   836 lemma union_upper1: "A <= A + (B::'a::order multiset)"
   837 proof -
   838   have "A + {#} <= A + B" by (blast intro: union_le_mono)
   839   then show ?thesis by simp
   840 qed
   841 
   842 lemma union_upper2: "B <= A + (B::'a::order multiset)"
   843 by (subst union_commute) (rule union_upper1)
   844 
   845 instance multiset :: (order) pordered_ab_semigroup_add
   846 apply intro_classes
   847 apply (erule union_le_mono[OF mult_le_refl])
   848 done
   849 
   850 
   851 subsection {* Link with lists *}
   852 
   853 primrec multiset_of :: "'a list \<Rightarrow> 'a multiset" where
   854   "multiset_of [] = {#}" |
   855   "multiset_of (a # x) = multiset_of x + {# a #}"
   856 
   857 lemma multiset_of_zero_iff[simp]: "(multiset_of x = {#}) = (x = [])"
   858 by (induct x) auto
   859 
   860 lemma multiset_of_zero_iff_right[simp]: "({#} = multiset_of x) = (x = [])"
   861 by (induct x) auto
   862 
   863 lemma set_of_multiset_of[simp]: "set_of(multiset_of x) = set x"
   864 by (induct x) auto
   865 
   866 lemma mem_set_multiset_eq: "x \<in> set xs = (x :# multiset_of xs)"
   867 by (induct xs) auto
   868 
   869 lemma multiset_of_append [simp]:
   870   "multiset_of (xs @ ys) = multiset_of xs + multiset_of ys"
   871 by (induct xs arbitrary: ys) (auto simp: union_ac)
   872 
   873 lemma surj_multiset_of: "surj multiset_of"
   874 apply (unfold surj_def)
   875 apply (rule allI)
   876 apply (rule_tac M = y in multiset_induct)
   877  apply auto
   878 apply (rule_tac x = "x # xa" in exI)
   879 apply auto
   880 done
   881 
   882 lemma set_count_greater_0: "set x = {a. count (multiset_of x) a > 0}"
   883 by (induct x) auto
   884 
   885 lemma distinct_count_atmost_1:
   886   "distinct x = (! a. count (multiset_of x) a = (if a \<in> set x then 1 else 0))"
   887 apply (induct x, simp, rule iffI, simp_all)
   888 apply (rule conjI)
   889 apply (simp_all add: set_of_multiset_of [THEN sym] del: set_of_multiset_of)
   890 apply (erule_tac x = a in allE, simp, clarify)
   891 apply (erule_tac x = aa in allE, simp)
   892 done
   893 
   894 lemma multiset_of_eq_setD:
   895   "multiset_of xs = multiset_of ys \<Longrightarrow> set xs = set ys"
   896 by (rule) (auto simp add:multiset_eq_conv_count_eq set_count_greater_0)
   897 
   898 lemma set_eq_iff_multiset_of_eq_distinct:
   899   "distinct x \<Longrightarrow> distinct y \<Longrightarrow>
   900     (set x = set y) = (multiset_of x = multiset_of y)"
   901 by (auto simp: multiset_eq_conv_count_eq distinct_count_atmost_1)
   902 
   903 lemma set_eq_iff_multiset_of_remdups_eq:
   904    "(set x = set y) = (multiset_of (remdups x) = multiset_of (remdups y))"
   905 apply (rule iffI)
   906 apply (simp add: set_eq_iff_multiset_of_eq_distinct[THEN iffD1])
   907 apply (drule distinct_remdups [THEN distinct_remdups
   908       [THEN set_eq_iff_multiset_of_eq_distinct [THEN iffD2]]])
   909 apply simp
   910 done
   911 
   912 lemma multiset_of_compl_union [simp]:
   913   "multiset_of [x\<leftarrow>xs. P x] + multiset_of [x\<leftarrow>xs. \<not>P x] = multiset_of xs"
   914 by (induct xs) (auto simp: union_ac)
   915 
   916 lemma count_filter:
   917   "count (multiset_of xs) x = length [y \<leftarrow> xs. y = x]"
   918 by (induct xs) auto
   919 
   920 lemma nth_mem_multiset_of: "i < length ls \<Longrightarrow> (ls ! i) :# multiset_of ls"
   921 apply (induct ls arbitrary: i)
   922  apply simp
   923 apply (case_tac i)
   924  apply auto
   925 done
   926 
   927 lemma multiset_of_remove1: "multiset_of (remove1 a xs) = multiset_of xs - {#a#}"
   928 by (induct xs) (auto simp add: multiset_eq_conv_count_eq)
   929 
   930 lemma multiset_of_eq_length:
   931 assumes "multiset_of xs = multiset_of ys"
   932 shows "length xs = length ys"
   933 using assms
   934 proof (induct arbitrary: ys rule: length_induct)
   935   case (1 xs ys)
   936   show ?case
   937   proof (cases xs)
   938     case Nil with "1.prems" show ?thesis by simp
   939   next
   940     case (Cons x xs')
   941     note xCons = Cons
   942     show ?thesis
   943     proof (cases ys)
   944       case Nil
   945       with "1.prems" Cons show ?thesis by simp
   946     next
   947       case (Cons y ys')
   948       have x_in_ys: "x = y \<or> x \<in> set ys'"
   949       proof (cases "x = y")
   950 	case True then show ?thesis ..
   951       next
   952 	case False
   953 	from "1.prems" [symmetric] xCons Cons have "x :# multiset_of ys' + {#y#}" by simp
   954 	with False show ?thesis by (simp add: mem_set_multiset_eq)
   955       qed
   956       from "1.hyps" have IH: "length xs' < length xs \<longrightarrow>
   957 	(\<forall>x. multiset_of xs' = multiset_of x \<longrightarrow> length xs' = length x)" by blast
   958       from "1.prems" x_in_ys Cons xCons have "multiset_of xs' = multiset_of (remove1 x (y#ys'))"
   959 	apply -
   960 	apply (simp add: multiset_of_remove1, simp only: add_eq_conv_diff)
   961 	apply fastsimp
   962 	done
   963       with IH xCons have IH': "length xs' = length (remove1 x (y#ys'))" by fastsimp
   964       from x_in_ys have "x \<noteq> y \<Longrightarrow> length ys' > 0" by auto
   965       with Cons xCons x_in_ys IH' show ?thesis by (auto simp add: length_remove1)
   966     qed
   967   qed
   968 qed
   969 
   970 text {*
   971   This lemma shows which properties suffice to show that a function
   972   @{text "f"} with @{text "f xs = ys"} behaves like sort.
   973 *}
   974 lemma properties_for_sort:
   975   "multiset_of ys = multiset_of xs \<Longrightarrow> sorted ys \<Longrightarrow> sort xs = ys"
   976 proof (induct xs arbitrary: ys)
   977   case Nil then show ?case by simp
   978 next
   979   case (Cons x xs)
   980   then have "x \<in> set ys"
   981     by (auto simp add:  mem_set_multiset_eq intro!: ccontr)
   982   with Cons.prems Cons.hyps [of "remove1 x ys"] show ?case
   983     by (simp add: sorted_remove1 multiset_of_remove1 insort_remove1)
   984 qed
   985 
   986 
   987 subsection {* Pointwise ordering induced by count *}
   988 
   989 definition
   990   mset_le :: "'a multiset \<Rightarrow> 'a multiset \<Rightarrow> bool"  (infix "\<le>#" 50) where
   991   [code func del]: "(A \<le># B) = (\<forall>a. count A a \<le> count B a)"
   992 
   993 definition
   994   mset_less :: "'a multiset \<Rightarrow> 'a multiset \<Rightarrow> bool"  (infix "<#" 50) where
   995   [code func del]: "(A <# B) = (A \<le># B \<and> A \<noteq> B)"
   996 
   997 notation mset_le  (infix "\<subseteq>#" 50)
   998 notation mset_less  (infix "\<subset>#" 50)
   999 
  1000 lemma mset_le_refl[simp]: "A \<le># A"
  1001 unfolding mset_le_def by auto
  1002 
  1003 lemma mset_le_trans: "A \<le># B \<Longrightarrow> B \<le># C \<Longrightarrow> A \<le># C"
  1004 unfolding mset_le_def by (fast intro: order_trans)
  1005 
  1006 lemma mset_le_antisym: "A \<le># B \<Longrightarrow> B \<le># A \<Longrightarrow> A = B"
  1007 apply (unfold mset_le_def)
  1008 apply (rule multiset_eq_conv_count_eq [THEN iffD2])
  1009 apply (blast intro: order_antisym)
  1010 done
  1011 
  1012 lemma mset_le_exists_conv: "(A \<le># B) = (\<exists>C. B = A + C)"
  1013 apply (unfold mset_le_def, rule iffI, rule_tac x = "B - A" in exI)
  1014 apply (auto intro: multiset_eq_conv_count_eq [THEN iffD2])
  1015 done
  1016 
  1017 lemma mset_le_mono_add_right_cancel[simp]: "(A + C \<le># B + C) = (A \<le># B)"
  1018 unfolding mset_le_def by auto
  1019 
  1020 lemma mset_le_mono_add_left_cancel[simp]: "(C + A \<le># C + B) = (A \<le># B)"
  1021 unfolding mset_le_def by auto
  1022 
  1023 lemma mset_le_mono_add: "\<lbrakk> A \<le># B; C \<le># D \<rbrakk> \<Longrightarrow> A + C \<le># B + D"
  1024 apply (unfold mset_le_def)
  1025 apply auto
  1026 apply (erule_tac x = a in allE)+
  1027 apply auto
  1028 done
  1029 
  1030 lemma mset_le_add_left[simp]: "A \<le># A + B"
  1031 unfolding mset_le_def by auto
  1032 
  1033 lemma mset_le_add_right[simp]: "B \<le># A + B"
  1034 unfolding mset_le_def by auto
  1035 
  1036 lemma mset_le_single: "a :# B \<Longrightarrow> {#a#} \<le># B"
  1037 by (simp add: mset_le_def)
  1038 
  1039 lemma multiset_diff_union_assoc: "C \<le># B \<Longrightarrow> A + B - C = A + (B - C)"
  1040 by (simp add: multiset_eq_conv_count_eq mset_le_def)
  1041 
  1042 lemma mset_le_multiset_union_diff_commute:
  1043 assumes "B \<le># A"
  1044 shows "A - B + C = A + C - B"
  1045 proof -
  1046   from mset_le_exists_conv [of "B" "A"] assms have "\<exists>D. A = B + D" ..
  1047   from this obtain D where "A = B + D" ..
  1048   then show ?thesis
  1049     apply simp
  1050     apply (subst union_commute)
  1051     apply (subst multiset_diff_union_assoc)
  1052     apply simp
  1053     apply (simp add: diff_cancel)
  1054     apply (subst union_assoc)
  1055     apply (subst union_commute[of "B" _])
  1056     apply (subst multiset_diff_union_assoc)
  1057     apply simp
  1058     apply (simp add: diff_cancel)
  1059     done
  1060 qed
  1061 
  1062 lemma multiset_of_remdups_le: "multiset_of (remdups xs) \<le># multiset_of xs"
  1063 apply (induct xs)
  1064  apply auto
  1065 apply (rule mset_le_trans)
  1066  apply auto
  1067 done
  1068 
  1069 lemma multiset_of_update:
  1070   "i < length ls \<Longrightarrow> multiset_of (ls[i := v]) = multiset_of ls - {#ls ! i#} + {#v#}"
  1071 proof (induct ls arbitrary: i)
  1072   case Nil then show ?case by simp
  1073 next
  1074   case (Cons x xs)
  1075   show ?case
  1076   proof (cases i)
  1077     case 0 then show ?thesis by simp
  1078   next
  1079     case (Suc i')
  1080     with Cons show ?thesis
  1081       apply simp
  1082       apply (subst union_assoc)
  1083       apply (subst union_commute [where M = "{#v#}" and N = "{#x#}"])
  1084       apply (subst union_assoc [symmetric])
  1085       apply simp
  1086       apply (rule mset_le_multiset_union_diff_commute)
  1087       apply (simp add: mset_le_single nth_mem_multiset_of)
  1088       done
  1089   qed
  1090 qed
  1091 
  1092 lemma multiset_of_swap:
  1093   "i < length ls \<Longrightarrow> j < length ls \<Longrightarrow>
  1094     multiset_of (ls[j := ls ! i, i := ls ! j]) = multiset_of ls"
  1095 apply (case_tac "i = j")
  1096  apply simp
  1097 apply (simp add: multiset_of_update)
  1098 apply (subst elem_imp_eq_diff_union[symmetric])
  1099  apply (simp add: nth_mem_multiset_of)
  1100 apply simp
  1101 done
  1102 
  1103 interpretation mset_order: order ["op \<le>#" "op <#"]
  1104 by (auto intro: order.intro mset_le_refl mset_le_antisym
  1105     mset_le_trans simp: mset_less_def)
  1106 
  1107 interpretation mset_order_cancel_semigroup:
  1108     pordered_cancel_ab_semigroup_add ["op +" "op \<le>#" "op <#"]
  1109 by unfold_locales (erule mset_le_mono_add [OF mset_le_refl])
  1110 
  1111 interpretation mset_order_semigroup_cancel:
  1112     pordered_ab_semigroup_add_imp_le ["op +" "op \<le>#" "op <#"]
  1113 by (unfold_locales) simp
  1114 
  1115 
  1116 lemma mset_lessD: "A \<subset># B \<Longrightarrow> x \<in># A \<Longrightarrow> x \<in># B"
  1117 apply (clarsimp simp: mset_le_def mset_less_def)
  1118 apply (erule_tac x=x in allE)
  1119 apply auto
  1120 done
  1121 
  1122 lemma mset_leD: "A \<subseteq># B \<Longrightarrow> x \<in># A \<Longrightarrow> x \<in># B"
  1123 apply (clarsimp simp: mset_le_def mset_less_def)
  1124 apply (erule_tac x = x in allE)
  1125 apply auto
  1126 done
  1127   
  1128 lemma mset_less_insertD: "(A + {#x#} \<subset># B) \<Longrightarrow> (x \<in># B \<and> A \<subset># B)"
  1129 apply (rule conjI)
  1130  apply (simp add: mset_lessD)
  1131 apply (clarsimp simp: mset_le_def mset_less_def)
  1132 apply safe
  1133  apply (erule_tac x = a in allE)
  1134  apply (auto split: split_if_asm)
  1135 done
  1136 
  1137 lemma mset_le_insertD: "(A + {#x#} \<subseteq># B) \<Longrightarrow> (x \<in># B \<and> A \<subseteq># B)"
  1138 apply (rule conjI)
  1139  apply (simp add: mset_leD)
  1140 apply (force simp: mset_le_def mset_less_def split: split_if_asm)
  1141 done
  1142 
  1143 lemma mset_less_of_empty[simp]: "A \<subset># {#} = False" 
  1144 by (induct A) (auto simp: mset_le_def mset_less_def)
  1145 
  1146 lemma multi_psub_of_add_self[simp]: "A \<subset># A + {#x#}"
  1147 by (auto simp: mset_le_def mset_less_def)
  1148 
  1149 lemma multi_psub_self[simp]: "A \<subset># A = False"
  1150 by (auto simp: mset_le_def mset_less_def)
  1151 
  1152 lemma mset_less_add_bothsides:
  1153   "T + {#x#} \<subset># S + {#x#} \<Longrightarrow> T \<subset># S"
  1154 by (auto simp: mset_le_def mset_less_def)
  1155 
  1156 lemma mset_less_empty_nonempty: "({#} \<subset># S) = (S \<noteq> {#})"
  1157 by (auto simp: mset_le_def mset_less_def)
  1158 
  1159 lemma mset_less_size: "A \<subset># B \<Longrightarrow> size A < size B"
  1160 proof (induct A arbitrary: B)
  1161   case (empty M)
  1162   then have "M \<noteq> {#}" by (simp add: mset_less_empty_nonempty)
  1163   then obtain M' x where "M = M' + {#x#}" 
  1164     by (blast dest: multi_nonempty_split)
  1165   then show ?case by simp
  1166 next
  1167   case (add S x T)
  1168   have IH: "\<And>B. S \<subset># B \<Longrightarrow> size S < size B" by fact
  1169   have SxsubT: "S + {#x#} \<subset># T" by fact
  1170   then have "x \<in># T" and "S \<subset># T" by (auto dest: mset_less_insertD)
  1171   then obtain T' where T: "T = T' + {#x#}" 
  1172     by (blast dest: multi_member_split)
  1173   then have "S \<subset># T'" using SxsubT 
  1174     by (blast intro: mset_less_add_bothsides)
  1175   then have "size S < size T'" using IH by simp
  1176   then show ?case using T by simp
  1177 qed
  1178 
  1179 lemmas mset_less_trans = mset_order.less_eq_less.less_trans
  1180 
  1181 lemma mset_less_diff_self: "c \<in># B \<Longrightarrow> B - {#c#} \<subset># B"
  1182 by (auto simp: mset_le_def mset_less_def multi_drop_mem_not_eq)
  1183 
  1184 
  1185 subsection {* Strong induction and subset induction for multisets *}
  1186 
  1187 text {* Well-foundedness of proper subset operator: *}
  1188 
  1189 text {* proper multiset subset *}
  1190 definition
  1191   mset_less_rel :: "('a multiset * 'a multiset) set" where
  1192   "mset_less_rel = {(A,B). A \<subset># B}"
  1193 
  1194 lemma multiset_add_sub_el_shuffle: 
  1195   assumes "c \<in># B" and "b \<noteq> c" 
  1196   shows "B - {#c#} + {#b#} = B + {#b#} - {#c#}"
  1197 proof -
  1198   from `c \<in># B` obtain A where B: "B = A + {#c#}" 
  1199     by (blast dest: multi_member_split)
  1200   have "A + {#b#} = A + {#b#} + {#c#} - {#c#}" by simp
  1201   then have "A + {#b#} = A + {#c#} + {#b#} - {#c#}" 
  1202     by (simp add: union_ac)
  1203   then show ?thesis using B by simp
  1204 qed
  1205 
  1206 lemma wf_mset_less_rel: "wf mset_less_rel"
  1207 apply (unfold mset_less_rel_def)
  1208 apply (rule wf_measure [THEN wf_subset, where f1=size])
  1209 apply (clarsimp simp: measure_def inv_image_def mset_less_size)
  1210 done
  1211 
  1212 text {* The induction rules: *}
  1213 
  1214 lemma full_multiset_induct [case_names less]:
  1215 assumes ih: "\<And>B. \<forall>A. A \<subset># B \<longrightarrow> P A \<Longrightarrow> P B"
  1216 shows "P B"
  1217 apply (rule wf_mset_less_rel [THEN wf_induct])
  1218 apply (rule ih, auto simp: mset_less_rel_def)
  1219 done
  1220 
  1221 lemma multi_subset_induct [consumes 2, case_names empty add]:
  1222 assumes "F \<subseteq># A"
  1223   and empty: "P {#}"
  1224   and insert: "\<And>a F. a \<in># A \<Longrightarrow> P F \<Longrightarrow> P (F + {#a#})"
  1225 shows "P F"
  1226 proof -
  1227   from `F \<subseteq># A`
  1228   show ?thesis
  1229   proof (induct F)
  1230     show "P {#}" by fact
  1231   next
  1232     fix x F
  1233     assume P: "F \<subseteq># A \<Longrightarrow> P F" and i: "F + {#x#} \<subseteq># A"
  1234     show "P (F + {#x#})"
  1235     proof (rule insert)
  1236       from i show "x \<in># A" by (auto dest: mset_le_insertD)
  1237       from i have "F \<subseteq># A" by (auto dest: mset_le_insertD)
  1238       with P show "P F" .
  1239     qed
  1240   qed
  1241 qed 
  1242 
  1243 text{* A consequence: Extensionality. *}
  1244 
  1245 lemma multi_count_eq: "(\<forall>x. count A x = count B x) = (A = B)"
  1246 apply (rule iffI)
  1247  prefer 2
  1248  apply clarsimp 
  1249 apply (induct A arbitrary: B rule: full_multiset_induct)
  1250 apply (rename_tac C)
  1251 apply (case_tac B rule: multiset_cases)
  1252  apply (simp add: empty_multiset_count)
  1253 apply simp
  1254 apply (case_tac "x \<in># C")
  1255  apply (force dest: multi_member_split)
  1256 apply (erule_tac x = x in allE)
  1257 apply simp
  1258 done
  1259 
  1260 lemmas multi_count_ext = multi_count_eq [THEN iffD1, rule_format]
  1261 
  1262 
  1263 subsection {* The fold combinator *}
  1264 
  1265 text {*
  1266   The intended behaviour is
  1267   @{text "fold_mset f z {#x\<^isub>1, ..., x\<^isub>n#} = f x\<^isub>1 (\<dots> (f x\<^isub>n z)\<dots>)"}
  1268   if @{text f} is associative-commutative. 
  1269 *}
  1270 
  1271 text {*
  1272   The graph of @{text "fold_mset"}, @{text "z"}: the start element,
  1273   @{text "f"}: folding function, @{text "A"}: the multiset, @{text
  1274   "y"}: the result.
  1275 *}
  1276 inductive 
  1277   fold_msetG :: "('a \<Rightarrow> 'b \<Rightarrow> 'b) \<Rightarrow> 'b \<Rightarrow> 'a multiset \<Rightarrow> 'b \<Rightarrow> bool" 
  1278   for f :: "'a \<Rightarrow> 'b \<Rightarrow> 'b" 
  1279   and z :: 'b
  1280 where
  1281   emptyI [intro]:  "fold_msetG f z {#} z"
  1282 | insertI [intro]: "fold_msetG f z A y \<Longrightarrow> fold_msetG f z (A + {#x#}) (f x y)"
  1283 
  1284 inductive_cases empty_fold_msetGE [elim!]: "fold_msetG f z {#} x"
  1285 inductive_cases insert_fold_msetGE: "fold_msetG f z (A + {#}) y" 
  1286 
  1287 definition
  1288   fold_mset :: "('a \<Rightarrow> 'b \<Rightarrow> 'b) \<Rightarrow> 'b \<Rightarrow> 'a multiset \<Rightarrow> 'b" where
  1289   "fold_mset f z A = (THE x. fold_msetG f z A x)"
  1290 
  1291 lemma Diff1_fold_msetG:
  1292   "fold_msetG f z (A - {#x#}) y \<Longrightarrow> x \<in># A \<Longrightarrow> fold_msetG f z A (f x y)"
  1293 apply (frule_tac x = x in fold_msetG.insertI)
  1294 apply auto
  1295 done
  1296 
  1297 lemma fold_msetG_nonempty: "\<exists>x. fold_msetG f z A x"
  1298 apply (induct A)
  1299  apply blast
  1300 apply clarsimp
  1301 apply (drule_tac x = x in fold_msetG.insertI)
  1302 apply auto
  1303 done
  1304 
  1305 lemma fold_mset_empty[simp]: "fold_mset f z {#} = z"
  1306 unfolding fold_mset_def by blast
  1307 
  1308 locale left_commutative = 
  1309 fixes f :: "'a => 'b => 'b"
  1310 assumes left_commute: "f x (f y z) = f y (f x z)"
  1311 begin
  1312 
  1313 lemma fold_msetG_determ:
  1314   "fold_msetG f z A x \<Longrightarrow> fold_msetG f z A y \<Longrightarrow> y = x"
  1315 proof (induct arbitrary: x y z rule: full_multiset_induct)
  1316   case (less M x\<^isub>1 x\<^isub>2 Z)
  1317   have IH: "\<forall>A. A \<subset># M \<longrightarrow> 
  1318     (\<forall>x x' x''. fold_msetG f x'' A x \<longrightarrow> fold_msetG f x'' A x'
  1319                \<longrightarrow> x' = x)" by fact
  1320   have Mfoldx\<^isub>1: "fold_msetG f Z M x\<^isub>1" and Mfoldx\<^isub>2: "fold_msetG f Z M x\<^isub>2" by fact+
  1321   show ?case
  1322   proof (rule fold_msetG.cases [OF Mfoldx\<^isub>1])
  1323     assume "M = {#}" and "x\<^isub>1 = Z"
  1324     then show ?case using Mfoldx\<^isub>2 by auto 
  1325   next
  1326     fix B b u
  1327     assume "M = B + {#b#}" and "x\<^isub>1 = f b u" and Bu: "fold_msetG f Z B u"
  1328     then have MBb: "M = B + {#b#}" and x\<^isub>1: "x\<^isub>1 = f b u" by auto
  1329     show ?case
  1330     proof (rule fold_msetG.cases [OF Mfoldx\<^isub>2])
  1331       assume "M = {#}" "x\<^isub>2 = Z"
  1332       then show ?case using Mfoldx\<^isub>1 by auto
  1333     next
  1334       fix C c v
  1335       assume "M = C + {#c#}" and "x\<^isub>2 = f c v" and Cv: "fold_msetG f Z C v"
  1336       then have MCc: "M = C + {#c#}" and x\<^isub>2: "x\<^isub>2 = f c v" by auto
  1337       then have CsubM: "C \<subset># M" by simp
  1338       from MBb have BsubM: "B \<subset># M" by simp
  1339       show ?case
  1340       proof cases
  1341         assume "b=c"
  1342         then moreover have "B = C" using MBb MCc by auto
  1343         ultimately show ?thesis using Bu Cv x\<^isub>1 x\<^isub>2 CsubM IH by auto
  1344       next
  1345         assume diff: "b \<noteq> c"
  1346         let ?D = "B - {#c#}"
  1347         have cinB: "c \<in># B" and binC: "b \<in># C" using MBb MCc diff
  1348           by (auto intro: insert_noteq_member dest: sym)
  1349         have "B - {#c#} \<subset># B" using cinB by (rule mset_less_diff_self)
  1350         then have DsubM: "?D \<subset># M" using BsubM by (blast intro: mset_less_trans)
  1351         from MBb MCc have "B + {#b#} = C + {#c#}" by blast
  1352         then have [simp]: "B + {#b#} - {#c#} = C"
  1353           using MBb MCc binC cinB by auto
  1354         have B: "B = ?D + {#c#}" and C: "C = ?D + {#b#}"
  1355           using MBb MCc diff binC cinB
  1356           by (auto simp: multiset_add_sub_el_shuffle)
  1357         then obtain d where Dfoldd: "fold_msetG f Z ?D d"
  1358           using fold_msetG_nonempty by iprover
  1359         then have "fold_msetG f Z B (f c d)" using cinB
  1360           by (rule Diff1_fold_msetG)
  1361         then have "f c d = u" using IH BsubM Bu by blast
  1362         moreover 
  1363         have "fold_msetG f Z C (f b d)" using binC cinB diff Dfoldd
  1364           by (auto simp: multiset_add_sub_el_shuffle 
  1365             dest: fold_msetG.insertI [where x=b])
  1366         then have "f b d = v" using IH CsubM Cv by blast
  1367         ultimately show ?thesis using x\<^isub>1 x\<^isub>2
  1368           by (auto simp: left_commute)
  1369       qed
  1370     qed
  1371   qed
  1372 qed
  1373         
  1374 lemma fold_mset_insert_aux:
  1375   "(fold_msetG f z (A + {#x#}) v) =
  1376     (\<exists>y. fold_msetG f z A y \<and> v = f x y)"
  1377 apply (rule iffI)
  1378  prefer 2
  1379  apply blast
  1380 apply (rule_tac A=A and f=f in fold_msetG_nonempty [THEN exE, standard])
  1381 apply (blast intro: fold_msetG_determ)
  1382 done
  1383 
  1384 lemma fold_mset_equality: "fold_msetG f z A y \<Longrightarrow> fold_mset f z A = y"
  1385 unfolding fold_mset_def by (blast intro: fold_msetG_determ)
  1386 
  1387 lemma fold_mset_insert:
  1388   "fold_mset f z (A + {#x#}) = f x (fold_mset f z A)"
  1389 apply (simp add: fold_mset_def fold_mset_insert_aux union_commute)  
  1390 apply (rule the_equality)
  1391  apply (auto cong add: conj_cong 
  1392      simp add: fold_mset_def [symmetric] fold_mset_equality fold_msetG_nonempty)
  1393 done
  1394 
  1395 lemma fold_mset_insert_idem:
  1396   "fold_mset f z (A + {#a#}) = f a (fold_mset f z A)"
  1397 apply (simp add: fold_mset_def fold_mset_insert_aux)
  1398 apply (rule the_equality)
  1399  apply (auto cong add: conj_cong 
  1400      simp add: fold_mset_def [symmetric] fold_mset_equality fold_msetG_nonempty)
  1401 done
  1402 
  1403 lemma fold_mset_commute: "f x (fold_mset f z A) = fold_mset f (f x z) A"
  1404 by (induct A) (auto simp: fold_mset_insert left_commute [of x])
  1405 
  1406 lemma fold_mset_single [simp]: "fold_mset f z {#x#} = f x z"
  1407 using fold_mset_insert [of z "{#}"] by simp
  1408 
  1409 lemma fold_mset_union [simp]:
  1410   "fold_mset f z (A+B) = fold_mset f (fold_mset f z A) B"
  1411 proof (induct A)
  1412   case empty then show ?case by simp
  1413 next
  1414   case (add A x)
  1415   have "A + {#x#} + B = (A+B) + {#x#}" by(simp add:union_ac)
  1416   then have "fold_mset f z (A + {#x#} + B) = f x (fold_mset f z (A + B))" 
  1417     by (simp add: fold_mset_insert)
  1418   also have "\<dots> = fold_mset f (fold_mset f z (A + {#x#})) B"
  1419     by (simp add: fold_mset_commute[of x,symmetric] add fold_mset_insert)
  1420   finally show ?case .
  1421 qed
  1422 
  1423 lemma fold_mset_fusion:
  1424   includes left_commutative g
  1425   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"
  1426 by (induct A) auto
  1427 
  1428 lemma fold_mset_rec:
  1429   assumes "a \<in># A" 
  1430   shows "fold_mset f z A = f a (fold_mset f z (A - {#a#}))"
  1431 proof -
  1432   from assms obtain A' where "A = A' + {#a#}"
  1433     by (blast dest: multi_member_split)
  1434   then show ?thesis by simp
  1435 qed
  1436 
  1437 end
  1438 
  1439 text {*
  1440   A note on code generation: When defining some function containing a
  1441   subterm @{term"fold_mset F"}, code generation is not automatic. When
  1442   interpreting locale @{text left_commutative} with @{text F}, the
  1443   would be code thms for @{const fold_mset} become thms like
  1444   @{term"fold_mset F z {#} = z"} where @{text F} is not a pattern but
  1445   contains defined symbols, i.e.\ is not a code thm. Hence a separate
  1446   constant with its own code thms needs to be introduced for @{text
  1447   F}. See the image operator below.
  1448 *}
  1449 
  1450 
  1451 subsection {* Image *}
  1452 
  1453 definition [code func del]: "image_mset f == fold_mset (op + o single o f) {#}"
  1454 
  1455 interpretation image_left_comm: left_commutative ["op + o single o f"]
  1456 by (unfold_locales) (simp add:union_ac)
  1457 
  1458 lemma image_mset_empty [simp, code func]: "image_mset f {#} = {#}"
  1459 by (simp add: image_mset_def)
  1460 
  1461 lemma image_mset_single [simp, code func]: "image_mset f {#x#} = {#f x#}"
  1462 by (simp add: image_mset_def)
  1463 
  1464 lemma image_mset_insert:
  1465   "image_mset f (M + {#a#}) = image_mset f M + {#f a#}"
  1466 by (simp add: image_mset_def add_ac)
  1467 
  1468 lemma image_mset_union[simp, code func]:
  1469   "image_mset f (M+N) = image_mset f M + image_mset f N"
  1470 apply (induct N)
  1471  apply simp
  1472 apply (simp add: union_assoc [symmetric] image_mset_insert)
  1473 done
  1474 
  1475 lemma size_image_mset [simp]: "size (image_mset f M) = size M"
  1476 by (induct M) simp_all
  1477 
  1478 lemma image_mset_is_empty_iff [simp]: "image_mset f M = {#} \<longleftrightarrow> M = {#}"
  1479 by (cases M) auto
  1480 
  1481 
  1482 syntax
  1483   comprehension1_mset :: "'a \<Rightarrow> 'b \<Rightarrow> 'b multiset \<Rightarrow> 'a multiset"
  1484       ("({#_/. _ :# _#})")
  1485 translations
  1486   "{#e. x:#M#}" == "CONST image_mset (%x. e) M"
  1487 
  1488 syntax
  1489   comprehension2_mset :: "'a \<Rightarrow> 'b \<Rightarrow> 'b multiset \<Rightarrow> bool \<Rightarrow> 'a multiset"
  1490       ("({#_/ | _ :# _./ _#})")
  1491 translations
  1492   "{#e | x:#M. P#}" => "{#e. x :# {# x:#M. P#}#}"
  1493 
  1494 text {*
  1495   This allows to write not just filters like @{term "{#x:#M. x<c#}"}
  1496   but also images like @{term "{#x+x. x:#M #}"} and @{term [source]
  1497   "{#x+x|x:#M. x<c#}"}, where the latter is currently displayed as
  1498   @{term "{#x+x|x:#M. x<c#}"}.
  1499 *}
  1500 
  1501 end