1 (* Title: HOL/Tools/function_package/fundef_package.ML
3 Author: Alexander Krauss, TU Muenchen
5 A package for general recursive function definitions.
7 Automatic splitting of overlapping constructor patterns. This is a preprocessing step which
8 turns a specification with overlaps into an overlap-free specification.
12 signature FUNDEF_SPLIT =
14 val split_some_equations :
15 Proof.context -> (bool * term) list -> term list list
17 val split_all_equations :
18 Proof.context -> term list -> term list list
21 structure FundefSplit : FUNDEF_SPLIT =
26 (* We use proof context for the variable management *)
29 fun new_var ctx vs T =
31 val [v] = Variable.variant_frees ctx vs [("v", T)]
33 (Free v :: vs, Free v)
36 fun saturate ctx vs t =
37 fold (fn T => fn (vs, t) => new_var ctx vs T |> apsnd (curry op $ t))
38 (binder_types (fastype_of t)) (vs, t)
41 (* This is copied from "fundef_datatype.ML" *)
42 fun inst_constrs_of thy (T as Type (name, _)) =
43 map (fn (Cn,CT) => Envir.subst_TVars (Sign.typ_match thy (body_type CT, T) Vartab.empty) (Const (Cn, CT)))
44 (the (DatatypePackage.get_datatype_constrs thy name))
45 | inst_constrs_of thy t = (print t; sys_error "inst_constrs_of")
50 fun join ((vs1,sub1), (vs2,sub2)) = (merge (op aconv) (vs1,vs2), sub1 @ sub2)
51 fun join_product (xs, ys) = map join (product xs ys)
54 | join_list xs = foldr1 (join_product) xs
59 fun pattern_subtract_subst ctx vs t t' =
62 fun pattern_subtract_subst_aux vs _ (Free v2) = []
63 | pattern_subtract_subst_aux vs (v as (Free (_, T))) t' =
67 val (vs', t) = saturate ctx vs constr
68 val substs = pattern_subtract_subst ctx vs' t t'
70 map (fn (vs, subst) => (vs, (v,t)::subst)) substs
73 flat (map foo (inst_constrs_of (ProofContext.theory_of ctx) T))
75 | pattern_subtract_subst_aux vs t t' =
77 val (C, ps) = strip_comb t
78 val (C', qs) = strip_comb t'
81 then flat (map2 (pattern_subtract_subst_aux vs) ps qs)
85 pattern_subtract_subst_aux vs t t'
86 handle DISJ => [(vs, [])]
91 fun pattern_subtract ctx eq2 eq1 =
93 val thy = ProofContext.theory_of ctx
95 val (vs, feq1 as (_ $ (_ $ lhs1 $ _))) = dest_all_all eq1
96 val (_, _ $ (_ $ lhs2 $ _)) = dest_all_all eq2
98 val substs = pattern_subtract_subst ctx vs lhs1 lhs2
100 fun instantiate (vs', sigma) =
102 val t = Pattern.rewrite_term thy sigma [] feq1
104 fold_rev mk_forall (map Free (frees_in_term ctx t) inter vs') t
107 map instantiate substs
112 fun pattern_subtract_from_many ctx p'=
113 flat o map (pattern_subtract ctx p')
115 (* in reverse order *)
116 fun pattern_subtract_many ctx ps' =
117 fold_rev (pattern_subtract_from_many ctx) ps'
121 fun split_some_equations ctx eqns =
123 fun split_aux prev [] = []
124 | split_aux prev ((true, eq) :: es) = pattern_subtract_many ctx prev [eq]
125 :: split_aux (eq :: prev) es
126 | split_aux prev ((false, eq) :: es) = [eq]
127 :: split_aux (eq :: prev) es
132 fun split_all_equations ctx =
133 split_some_equations ctx o map (pair true)