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