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