src/Pure/isac/Scripts/term_G.sml
author Walther Neuper <neuper@ist.tugraz.at>
Wed, 21 Jul 2010 13:53:39 +0200
branchisac-from-Isabelle2009-2
changeset 37871 875b6efa7ced
child 37876 902c99093693
permissions -rw-r--r--
added isac-hook in Pure/thm and isac-code
     1 (* extends Isabelle/src/Pure/term.ML
     2    (c) Walther Neuper 1999
     3 
     4 use"Scripts/term_G.sml";
     5 use"term_G.sml";
     6 *)
     7 
     8 (*
     9 > cterm_of (sign_of thy) a_term;
    10 val it = "empty" : cterm        *)
    11 
    12 (*1003 fun match thy t pat =
    13     (snd (Pattern.match (Sign.tsig_of (sign_of thy)) (pat, t)))
    14     handle _ => [];
    15 fn : Theory.theory ->
    16      Term.term -> Term.term -> (Term.indexname * Term.term) list*)
    17 (*see src/Tools/eqsubst.ML fun clean_match*)
    18 (*1003 fun matches thy tm pa = if match thy tm pa = [] then false else true;*)
    19 fun matches thy tm pa = 
    20     (Pattern.match thy (pa, tm) (Vartab.empty, Vartab.empty); true)
    21     handle _ => false
    22 
    23 fun atomtyp t = (*see raw_pp_typ*)
    24   let
    25     fun ato n (Type (s,[])) = 
    26       ("\n*** "^indent n^"Type ("^s^",[])")
    27       | ato n (Type (s,Ts)) =
    28       ("\n*** "^indent n^"Type ("^s^",["^ atol (n+1) Ts)
    29 
    30       | ato n (TFree (s,sort)) =
    31       ("\n*** "^indent n^"TFree ("^s^",["^ strs2str' sort)
    32 
    33       | ato n (TVar ((s,i),sort)) =
    34       ("\n*** "^indent n^"TVar (("^s^","^ 
    35        string_of_int i ^ strs2str' sort)
    36     and atol n [] = 
    37       ("\n*** "^indent n^"]")
    38       | atol n (T::Ts) = (ato n T ^ atol n Ts)
    39 (*in print (ato 0 t ^ "\n") end;  TODO TUM10*)
    40 in writeln(ato 0 t) end;
    41 
    42 (*Prog.Tutorial.p.34*)
    43 local
    44    fun pp_pair (x, y) = Pretty.list "(" ")" [x, y]
    45    fun pp_list xs = Pretty.list "[" "]" xs
    46    fun pp_str s   = Pretty.str s
    47    fun pp_qstr s = Pretty.quote (pp_str s)
    48    fun pp_int i   = pp_str (string_of_int i)
    49    fun pp_sort S = pp_list (map pp_qstr S)
    50    fun pp_constr a args = Pretty.block [pp_str a, Pretty.brk 1, args]
    51 in
    52 fun raw_pp_typ (TVar ((a, i), S)) =
    53        pp_constr "TVar" (pp_pair (pp_pair (pp_qstr a, pp_int i), pp_sort S))
    54    | raw_pp_typ (TFree (a, S)) =
    55        pp_constr "TFree" (pp_pair (pp_qstr a, pp_sort S))
    56    | raw_pp_typ (Type (a, tys)) =
    57        pp_constr "Type" (pp_pair (pp_qstr a, pp_list (map raw_pp_typ tys)))
    58 end
    59 (* install
    60 PolyML.addPrettyPrinter
    61   (fn _ => fn _ => ml_pretty o Pretty.to_ML o raw_pp_typ);
    62 de-install
    63 PolyML.addPrettyPrinter
    64   (fn _ => fn _ => ml_pretty o Pretty.to_ML o Proof_Display.pp_typ Pure.thy);
    65 *)
    66 
    67 (*
    68 > val T = (type_of o term_of o the o (parse thy)) "a::[real,int] => nat";
    69 > atomtyp T;
    70 *** Type (fun,[
    71 ***   Type (RealDef.real,[])
    72 ***   Type (fun,[
    73 ***     Type (IntDef.int,[])
    74 ***     Type (nat,[])
    75 ***     ]
    76 ***   ]
    77 *)
    78 
    79 fun atomt t =
    80     let fun ato (Const(a,T))     n = 
    81 	("\n*** "^indent n^"Const ("^a^")")
    82 	  | ato (Free (a,T))     n =  
    83 	("\n*** "^indent n^"Free ("^a^", "^")")
    84 	  | ato (Var ((a,ix),T)) n =
    85 	("\n*** "^indent n^"Var (("^a^", "^(string_of_int ix)^"), "^")")
    86 	  | ato (Bound ix)       n = 
    87 	("\n*** "^indent n^"Bound "^(string_of_int ix))
    88 	  | ato (Abs(a,T,body))  n = 
    89 	("\n*** "^indent n^"Abs("^a^",..")^ato body (n+1)
    90 	  | ato (f$t')           n = (ato f n; ato t' (n+1))
    91     in writeln("\n*** -------------"^ ato t 0 ^"\n***") end;
    92 
    93 fun term_detail2str t =
    94     let fun ato (Const (a, T))     n = 
    95 	    "\n*** "^indent n^"Const ("^a^", "^string_of_typ T^")"
    96 	  | ato (Free (a, T))     n =  
    97 	    "\n*** "^indent n^"Free ("^a^", "^string_of_typ T^")"
    98 	  | ato (Var ((a, ix), T)) n =
    99 	    "\n*** "^indent n^"Var (("^a^", "^string_of_int ix^"), "^
   100 	    string_of_typ T^")"
   101 	  | ato (Bound ix)       n = 
   102 	    "\n*** "^indent n^"Bound "^string_of_int ix
   103 	  | ato (Abs(a, T, body))  n = 
   104 	    "\n*** "^indent n^"Abs ("^a^", "^
   105 	       (string_of_typ T)^",.."
   106 	    ^ato body (n + 1)
   107 	  | ato (f $ t')           n = ato f n^ato t' (n+1)
   108     in "\n*** "^ato t 0^"\n***" end;
   109 fun atomty t = (writeln o term_detail2str) t;
   110 
   111 fun term_str thy (Const(s,_)) = s
   112   | term_str thy (Free(s,_)) = s
   113   | term_str thy (Var((s,i),_)) = s^(string_of_int i)
   114   | term_str thy (Bound i) = "B."^(string_of_int i)
   115   | term_str thy (Abs(s,_,_)) = s
   116   | term_str thy t = raise error("term_str not for "^term2str t);
   117 
   118 (*.contains the fst argument the second argument (a leave! of term).*)
   119 fun contains_term (Abs(_,_,body)) t = contains_term body t 
   120   | contains_term (f $ f') t = 
   121     contains_term f t orelse contains_term f' t
   122   | contains_term s t = t = s;
   123 (*.contains the term a VAR(("*",_),_) ?.*)
   124 fun contains_Var (Abs(_,_,body)) = contains_Var body
   125   | contains_Var (f $ f') = contains_Var f orelse contains_Var f'
   126   | contains_Var (Var _) = true
   127   | contains_Var _ = false;
   128 (* contains_Var (str2term "?z = 3") (*true*);
   129    contains_Var (str2term "z = 3")  (*false*);
   130    *)
   131 
   132 (*fun int_of_str str =
   133     let val ss = explode str
   134 	val str' = case ss of
   135 	   "("::s => drop_last s | _ => ss
   136     in case BasisLibrary.Int.fromString (implode str') of
   137 	     SOME i => SOME i
   138 	   | NONE => NONE end;*)
   139 fun int_of_str str =
   140     let val ss = explode str
   141 	val str' = case ss of
   142 	   "("::s => drop_last s | _ => ss
   143     in (SOME (ThyOutput.integer (implode str'))) handle _ => NONE end;
   144 (*
   145 > int_of_str "123";
   146 val it = SOME 123 : int option                                                 > int_of_str "(-123)";
   147 val it = SOME 123 : int option                                                 > int_of_str "#123";
   148 val it = NONE : int option                                                     > int_of_str "-123";
   149 val it = SOME ~123 : int option                                                *)
   150 fun int_of_str' str = 
   151     case int_of_str str of
   152 	SOME i => i
   153       | NONE => raise TERM ("int_of_string: no int-string",[]);
   154 val str2int = int_of_str';
   155     
   156 fun is_numeral str = case int_of_str str of
   157 			 SOME _ => true
   158 		       | NONE => false;
   159 val is_no = is_numeral;
   160 fun is_num (Free (s,_)) = if is_numeral s then true else false
   161   | is_num _ = false;
   162 (*>
   163 > is_num ((term_of o the o (parse thy)) "#1");
   164 val it = true : bool
   165 > is_num ((term_of o the o (parse thy)) "#-1");
   166 val it = true : bool
   167 > is_num ((term_of o the o (parse thy)) "a123");
   168 val it = false : bool
   169 *)
   170 
   171 (*fun int_of_Free (Free (intstr, _)) =
   172     (case BasisLibrary.Int.fromString intstr of
   173 	     SOME i => i
   174 	   | NONE => raise error ("int_of_Free ( "^ intstr ^", _)"))
   175   | int_of_Free t = raise error ("int_of_Free ( "^ term2str t ^" )");*)
   176 fun int_of_Free (Free (intstr, _)) = (ThyOutput.integer intstr
   177     handle _ => raise error ("int_of_Free ( "^ intstr ^", _)"))
   178   | int_of_Free t = raise error ("int_of_Free ( "^ term2str t ^" )");
   179 
   180 fun vars t =
   181   let
   182     fun scan vs (Const(s,T)) = vs
   183       | scan vs (t as Free(s,T)) = if is_no s then vs else t::vs
   184       | scan vs (t as Var((s,i),T)) = t::vs
   185       | scan vs (Bound i) = vs 
   186       | scan vs (Abs(s,T,t)) = scan vs t
   187       | scan vs (t1 $ t2) = (scan vs t1) @ (scan vs t2)
   188   in (distinct o (scan [])) t end;
   189 
   190 fun is_Free (Free _) = true
   191   | is_Free _ = false;
   192 fun is_fun_id (Const _) = true
   193   | is_fun_id (Free _) = true
   194   | is_fun_id _ = false;
   195 fun is_f_x (f $ x) = is_fun_id f andalso is_Free x
   196   | is_f_x _ = false;
   197 (* is_f_x (str2term "q_0/2 * L * x") (*false*);
   198    is_f_x (str2term "M_b x") (*true*);
   199   *)
   200 fun vars_str t =
   201   let
   202     fun scan vs (Const(s,T)) = vs
   203       | scan vs (t as Free(s,T)) = if is_no s then vs else s::vs
   204       | scan vs (t as Var((s,i),T)) = (s^"_"^(string_of_int i))::vs
   205       | scan vs (Bound i) = vs 
   206       | scan vs (Abs(s,T,t)) = scan vs t
   207       | scan vs (t1 $ t2) = (scan vs t1) @ (scan vs t2)
   208   in (distinct o (scan [])) t end;
   209 
   210 fun ids2str t =
   211   let
   212     fun scan vs (Const(s,T)) = if is_no s then vs else s::vs
   213       | scan vs (t as Free(s,T)) = if is_no s then vs else s::vs
   214       | scan vs (t as Var((s,i),T)) = (s^"_"^(string_of_int i))::vs
   215       | scan vs (Bound i) = vs 
   216       | scan vs (Abs(s,T,t)) = scan (s::vs) t
   217       | scan vs (t1 $ t2) = (scan vs t1) @ (scan vs t2)
   218   in (distinct o (scan [])) t end;
   219 fun is_bdv str =
   220     case explode str of
   221 	"b"::"d"::"v"::_ => true
   222       | _ => false;
   223 fun is_bdv_ (Free (s,_)) = is_bdv s
   224   | is_bdv_ _ = false;
   225 
   226 fun free2str (Free (s,_)) = s
   227   | free2str t = raise error ("free2str not for "^ term2str t);
   228 fun free2int (t as Free (s, _)) = ((str2int s)
   229     handle _ => raise error ("free2int: "^term_detail2str t))
   230   | free2int t = raise error ("free2int: "^term_detail2str t);
   231 
   232 (*27.8.01: unused*)
   233 fun var2free (t as Const(s,T)) = t
   234   | var2free (t as Free(s,T)) = t
   235   | var2free (Var((s,i),T)) = Free(s,T)
   236   | var2free (t as Bound i) = t 
   237   | var2free (Abs(s,T,t)) = Abs(s,T,var2free t)
   238   | var2free (t1 $ t2) = (var2free t1) $ (var2free t2);
   239   
   240 (*27.8.01: doesn't find some subterm ???!???*)
   241 (*2010 Logic.varify !!!*)
   242 fun free2var (t as Const(s,T)) = t
   243   | free2var (t as Free(s,T)) = if is_no s then t else Var((s,0),T)
   244   | free2var (t as Var((s,i),T)) = t
   245   | free2var (t as Bound i) = t 
   246   | free2var (Abs(s,T,t)) = Abs(s,T,free2var t)
   247   | free2var (t1 $ t2) = (free2var t1) $ (free2var t2);
   248   
   249 
   250 fun mk_listT T = Type ("List.list", [T]);
   251 fun list_const T = 
   252   Const("List.list.Cons", [T, mk_listT T] ---> mk_listT T);
   253 (*28.8.01: TODO: get type from head of list: 1 arg less!!!*)
   254 fun list2isalist T [] = Const("List.list.Nil",mk_listT T)
   255   | list2isalist T (t::ts) = (list_const T) $ t $ (list2isalist T ts);
   256 (*
   257 > val tt = (term_of o the o (parse thy)) "R=(R::real)";
   258 > val TT = type_of tt;
   259 > val ss = list2isalist TT [tt,tt,tt];
   260 > cterm_of (sign_of thy) ss;
   261 val it = "[R = R, R = R, R = R]" : cterm  *)
   262 
   263 fun isapair2pair (Const ("Pair",_) $ a $ b) = (a,b)
   264   | isapair2pair t = 
   265     raise error ("isapair2pair called with "^term2str t);
   266 
   267 val listType = Type ("List.list",[Type ("bool",[])]);
   268 fun isalist2list ls =
   269   let
   270     fun get es (Const("List.list.Cons",_) $ t $ ls) = get (t::es) ls
   271       | get es (Const("List.list.Nil",_)) = es
   272       | get _ t = 
   273 	raise error ("isalist2list applied to NON-list '"^term2str t^"'")
   274   in (rev o (get [])) ls end;
   275 (*      
   276 > val il = str2term "[a=b,c=d,e=f]";
   277 > val l = isalist2list il;
   278 > (writeln o terms2str) l;
   279 ["a = b","c = d","e = f"]
   280 
   281 > val il = str2term "ss___::bool list";
   282 > val l = isalist2list il;
   283 [Free ("ss___", "bool List.list")]
   284 *)
   285 
   286 
   287 (*review Isabelle2009/src/HOL/Tools/hologic.ML*)
   288 val prop = Type ("prop",[]);     (* ~/Diss.99/Integers-Isa/tools.sml*)
   289 val bool = Type ("bool",[]);     (* 2002 Integ.int *)
   290 val Trueprop = Const("Trueprop",bool-->prop);
   291 fun mk_prop t = Trueprop $ t;
   292 val true_as_term = Const("True",bool);
   293 val false_as_term = Const("False",bool);
   294 val true_as_cterm = cterm_of HOL true_as_term;
   295 val false_as_cterm = cterm_of HOL false_as_term;
   296 
   297 infixr 5 -->;                    (*2002 /Pure/term.ML *)
   298 infixr --->;			 (*2002 /Pure/term.ML *)
   299 fun S --> T = Type("fun",[S,T]); (*2002 /Pure/term.ML *)
   300 val op ---> = foldr (op -->);    (*2002 /Pure/term.ML *)
   301 fun list_implies ([], B) = B : term (*2002 /term.ML *)
   302   | list_implies (A::AS, B) = Logic.implies $ A $ list_implies(AS,B);
   303 
   304 
   305 
   306 (** substitution **)
   307 
   308 fun match_bvs(Abs(x,_,s),Abs(y,_,t), al) =      (* = thm.ML *)
   309       match_bvs(s, t, if x="" orelse y="" then al
   310                                           else (x,y)::al)
   311   | match_bvs(f$s, g$t, al) = match_bvs(f,g,match_bvs(s,t,al))
   312   | match_bvs(_,_,al) = al;
   313 fun ren_inst(insts,prop,pat,obj) =              (* = thm.ML *)
   314   let val ren = match_bvs(pat,obj,[])
   315       fun renAbs(Abs(x,T,b)) =
   316             Abs(case assoc_string(ren,x) of NONE => x 
   317 	  | SOME(y) => y, T, renAbs(b))
   318         | renAbs(f$t) = renAbs(f) $ renAbs(t)
   319         | renAbs(t) = t
   320   in subst_vars insts (if null(ren) then prop else renAbs(prop)) end;
   321 
   322 
   323 
   324 
   325 
   326 
   327 fun dest_equals' (Const("op =",_) $ t $ u)  =  (t,u)(* logic.ML: Const("=="*)
   328   | dest_equals' t = raise TERM("dest_equals'", [t]);
   329 val lhs_ = (fst o dest_equals');
   330 val rhs_ = (snd o dest_equals');
   331 
   332 fun is_equality (Const("op =",_) $ t $ u)  =  true  (* logic.ML: Const("=="*)
   333   | is_equality _ = false;
   334 fun mk_equality (t,u) = (Const("op =",[type_of t,type_of u]--->bool) $ t $ u); 
   335 fun is_expliceq (Const("op =",_) $ (Free _) $ u)  =  true
   336   | is_expliceq _ = false;
   337 fun strip_trueprop (Const("Trueprop",_) $ t) = t
   338   | strip_trueprop t = t;
   339 (*  | strip_trueprop t = raise TERM("strip_trueprop", [t]);
   340 *)
   341 
   342 (*.(A1==>...An==>B) goes to (A1==>...An==>).*)
   343 fun strip_imp_prems' (Const("==>", T) $ A $ t) = 
   344     let fun coll_prems As (Const("==>", _) $ A $ t) = 
   345 	    coll_prems (As $ (Logic.implies $ A)) t
   346 	  | coll_prems As _ = SOME As
   347     in coll_prems (Logic.implies $ A) t end
   348   | strip_imp_prems' _ = NONE;  (* logic.ML: term -> term list*)
   349 (*
   350   val thm = real_mult_div_cancel1;
   351   val prop = (#prop o rep_thm) thm;
   352   atomt prop;
   353 *** -------------
   354 *** Const ( ==>)
   355 *** . Const ( Trueprop)
   356 *** . . Const ( Not)
   357 *** . . . Const ( op =)
   358 *** . . . . Var ((k, 0), )
   359 *** . . . . Const ( 0)
   360 *** . Const ( Trueprop)
   361 *** . . Const ( op =)                                                          *** .............
   362   val SOME t = strip_imp_prems' ((#prop o rep_thm) thm);
   363   atomt t;
   364 *** -------------
   365 *** Const ( ==>)
   366 *** . Const ( Trueprop)
   367 *** . . Const ( Not)
   368 *** . . . Const ( op =)
   369 *** . . . . Var ((k, 0), )
   370 *** . . . . Const ( 0)
   371 
   372   val thm = real_le_anti_sym;
   373   val prop = (#prop o rep_thm) thm;
   374   atomt prop;
   375 *** -------------
   376 *** Const ( ==>)
   377 *** . Const ( Trueprop)
   378 *** . . Const ( op <=)
   379 *** . . . Var ((z, 0), )
   380 *** . . . Var ((w, 0), )
   381 *** . Const ( ==>)
   382 *** . . Const ( Trueprop)
   383 *** . . . Const ( op <=)
   384 *** . . . . Var ((w, 0), )
   385 *** . . . . Var ((z, 0), )
   386 *** . . Const ( Trueprop)
   387 *** . . . Const ( op =)
   388 *** .............
   389   val SOME t = strip_imp_prems' ((#prop o rep_thm) thm);
   390   atomt t;
   391 *** -------------
   392 *** Const ( ==>)
   393 *** . Const ( Trueprop)
   394 *** . . Const ( op <=)
   395 *** . . . Var ((z, 0), )
   396 *** . . . Var ((w, 0), )
   397 *** . Const ( ==>)
   398 *** . . Const ( Trueprop)
   399 *** . . . Const ( op <=)
   400 *** . . . . Var ((w, 0), )
   401 *** . . . . Var ((z, 0), )
   402 *)
   403 
   404 (*. (A1==>...An==>) (B) goes to (A1==>...An==>B), where B is lowest branch.*)
   405 fun ins_concl (Const("==>", T) $ A $ t) B = Logic.implies $ A $ (ins_concl t B)
   406   | ins_concl (Const("==>", T) $ A    ) B = Logic.implies $ A $ B
   407   | ins_concl t B =  raise TERM("ins_concl", [t, B]);
   408 (*
   409   val thm = real_le_anti_sym;
   410   val prop = (#prop o rep_thm) thm;
   411   val concl = Logic.strip_imp_concl prop;
   412   val SOME prems = strip_imp_prems' prop;
   413   val prop' = ins_concl prems concl;
   414   prop = prop';
   415   atomt prop;
   416   atomt prop';
   417 *)
   418 
   419 
   420 fun vperm (Var _, Var _) = true  (*2002 Pure/thm.ML *)
   421   | vperm (Abs (_, _, s), Abs (_, _, t)) = vperm (s, t)
   422   | vperm (t1 $ t2, u1 $ u2) = vperm (t1, u1) andalso vperm (t2, u2)
   423   | vperm (t, u) = (t = u);
   424 
   425 (*2002 cp from Pure/term.ML --- since 2009 in Pure/old_term.ML*)
   426 fun mem_term (_, []) = false
   427   | mem_term (t, t'::ts) = t aconv t' orelse mem_term(t,ts);
   428 fun subset_term ([], ys) = true
   429   | subset_term (x :: xs, ys) = mem_term (x, ys) andalso subset_term(xs, ys);
   430 fun eq_set_term (xs, ys) =
   431     xs = ys orelse (subset_term (xs, ys) andalso subset_term (ys, xs));
   432 (*a total, irreflexive ordering on index names*)
   433 fun xless ((a,i), (b,j): indexname) = i<j  orelse  (i=j andalso a<b);
   434 (*a partial ordering (not reflexive) for atomic terms*)
   435 fun atless (Const (a,_), Const (b,_))  =  a<b
   436   | atless (Free (a,_), Free (b,_)) =  a<b
   437   | atless (Var(v,_), Var(w,_))  =  xless(v,w)
   438   | atless (Bound i, Bound j)  =   i<j
   439   | atless _  =  false;
   440 (*insert atomic term into partially sorted list, suppressing duplicates (?)*)
   441 fun insert_aterm (t,us) =
   442   let fun inserta [] = [t]
   443         | inserta (us as u::us') =
   444               if atless(t,u) then t::us
   445               else if t=u then us (*duplicate*)
   446               else u :: inserta(us')
   447   in  inserta us  end;
   448 
   449 (*Accumulates the Vars in the term, suppressing duplicates*)
   450 fun add_term_vars (t, vars: term list) = case t of
   451     Var   _ => insert_aterm(t,vars)
   452   | Abs (_,_,body) => add_term_vars(body,vars)
   453   | f$t =>  add_term_vars (f, add_term_vars(t, vars))
   454   | _ => vars;
   455 fun term_vars t = add_term_vars(t,[]);
   456 
   457 
   458 fun var_perm (t, u) = (*2002 Pure/thm.ML *)
   459   vperm (t, u) andalso eq_set_term (term_vars t, term_vars u);
   460     
   461 (*2002 fun decomp_simp, Pure/thm.ML *)
   462 fun perm lhs rhs = var_perm (lhs, rhs) andalso not (lhs aconv rhs)
   463     andalso not (is_Var lhs);
   464 
   465 
   466 fun str_of_int n = 
   467   if n < 0 then "-"^((string_of_int o abs) n)
   468   else string_of_int n;
   469 (*
   470 > str_of_int 1;
   471 val it = "1" : string                                                          > str_of_int ~1;
   472 val it = "-1" : string
   473 *)
   474 
   475 
   476 fun power b 0 = 1
   477   | power b n = 
   478   if n>0 then b*(power b (n-1))
   479   else raise error ("power "^(str_of_int b)^" "^(str_of_int n));
   480 (*
   481 > power 2 3;
   482 val it = 8 : int
   483 > power ~2 3;
   484 val it = ~8 : int
   485 > power ~3 2;
   486 val it = 9 : int
   487 > power 3 ~2;
   488 *)
   489 fun gcd 0 b = b
   490   | gcd a b = if a < b then gcd (b mod a) a
   491 	      else gcd (a mod b) b;
   492 fun sign n = if n < 0 then ~1
   493 	     else if n = 0 then 0 else 1;
   494 fun sign2 n1 n2 = (sign n1) * (sign n2);
   495 
   496 infix dvd;
   497 fun d dvd n = n mod d = 0;
   498 
   499 fun divisors n =
   500   let fun pdiv ds d n = 
   501     if d=n then d::ds
   502     else if d dvd n then pdiv (d::ds) d (n div d)
   503 	 else pdiv ds (d+1) n
   504   in pdiv [] 2 n end;
   505 
   506 divisors 30;
   507 divisors 32;
   508 divisors 60;
   509 divisors 11;
   510 
   511 fun doubles ds = (* ds is ordered *)
   512   let fun dbls ds [] = ds
   513 	| dbls ds [i] = ds
   514 	| dbls ds (i::i'::is) = if i=i' then dbls (i::ds) is
   515 				else dbls ds (i'::is)
   516   in dbls [] ds end;
   517 (*> doubles [2,3,4];
   518 val it = [] : int list
   519 > doubles [2,3,3,5,5,7];
   520 val it = [5,3] : int list*)
   521 
   522 fun squfact 0 = 0
   523   | squfact 1 = 1
   524   | squfact n = foldl op* (1, (doubles o divisors) n);
   525 (*> squfact 30;
   526 val it = 1 : int
   527 > squfact 32;
   528 val it = 4 : int
   529 > squfact 60;
   530 val it = 2 : int
   531 > squfact 11;
   532 val it = 1 : int*)
   533 
   534 
   535 fun dest_type (Type(T,[])) = T
   536   | dest_type T = 
   537     (atomtyp T;
   538      raise error ("... dest_type: not impl. for this type"));
   539 
   540 fun term_of_num ntyp n = Free (str_of_int n, ntyp);
   541 
   542 fun pairT T1 T2 = Type ("*", [T1, T2]);
   543 (*> val t = str2term "(1,2)";
   544 > type_of t = pairT HOLogic.realT HOLogic.realT;
   545 val it = true : bool
   546 *)
   547 fun PairT T1 T2 = ([T1, T2] ---> Type ("*", [T1, T2]));
   548 (*> val t = str2term "(1,2)";
   549 > val Const ("Pair",pT) $ _ $ _ = t;
   550 > pT = PairT HOLogic.realT HOLogic.realT;
   551 val it = true : bool
   552 *)
   553 fun pairt t1 t2 =
   554     Const ("Pair", PairT (type_of t1) (type_of t2)) $ t1 $ t2;
   555 (*> val t = str2term "(1,2)";
   556 > val (t1, t2) = (str2term "1", str2term "2");
   557 > t = pairt t1 t2;
   558 val it = true : bool*)
   559 
   560 
   561 fun num_of_term (t as Free (s,_)) = 
   562     (case int_of_str s of
   563 	 SOME s' => s'
   564        | NONE => raise error ("num_of_term not for "^ term2str t))
   565   | num_of_term t = raise error ("num_of_term not for "^term2str t);
   566 
   567 fun mk_factroot op_(*=thy.sqrt*) T fact root = 
   568   Const ("op *", [T, T] ---> T) $ (term_of_num T fact) $
   569   (Const (op_, T --> T) $ term_of_num T root);
   570 (*
   571 val T =  (type_of o term_of o the) (parse thy "#12::real");
   572 val t = mk_factroot "SqRoot.sqrt" T 2 3;
   573 cterm_of (sign_of thy) t;
   574 val it = "#2 * sqrt #3 " : cterm
   575 *)
   576 fun var_op_num v op_ optype ntyp n =
   577   Const (op_, optype) $ v $ 
   578    Free (str_of_int  n, ntyp);
   579 
   580 fun num_op_var v op_ optype ntyp n =
   581   Const (op_,optype) $  
   582    Free (str_of_int n, ntyp) $ v;
   583 
   584 fun num_op_num T1 T2 (op_,Top) n1 n2 = 
   585   Const (op_,Top) $ 
   586   Free (str_of_int n1, T1) $ Free (str_of_int n2, T2);
   587 (*
   588 > val t = num_op_num "Int" 3 4;
   589 > atomty t;
   590 > string_of_cterm (cterm_of (sign_of thy) t);
   591 *)
   592 
   593 fun const_in str (Const _) = false
   594   | const_in str (Free (s,_)) = if strip_thy s = str then true else false
   595   | const_in str (Bound _) = false
   596   | const_in str (Var _) = false
   597   | const_in str (Abs (_,_,body)) = const_in str body
   598   | const_in str (f$u) = const_in str f orelse const_in str u;
   599 (*
   600 > val t = (term_of o the o (parse thy)) "6 + 5 * sqrt 4 + 3";
   601 > const_in "sqrt" t;
   602 val it = true : bool
   603 > val t = (term_of o the o (parse thy)) "6 + 5 * 4 + 3";
   604 > const_in "sqrt" t;
   605 val it = false : bool
   606 *)
   607 
   608 (*used for calculating built in binary operations in Isabelle2002->Float.ML*)
   609 (*fun calc "op +"  (n1, n2) = n1+n2
   610   | calc "op -"  (n1, n2) = n1-n2
   611   | calc "op *"  (n1, n2) = n1*n2
   612   | calc "HOL.divide"(n1, n2) = n1 div n2
   613   | calc "Atools.pow"(n1, n2) = power n1 n2
   614   | calc op_ _ = raise error ("calc: operator = "^op_^" not defined");-----*)
   615 fun calc_equ "op <"  (n1, n2) = n1 < n2
   616   | calc_equ "op <=" (n1, n2) = n1 <= n2
   617   | calc_equ op_ _ = 
   618   raise error ("calc_equ: operator = "^op_^" not defined");
   619 fun sqrt (n:int) = if n < 0 then 0
   620     (*FIXME ~~~*)  else (trunc o Math.sqrt o Real.fromInt) n;
   621 
   622 fun mk_thmid thmid op_ n1 n2 = 
   623   thmid ^ (strip_thy n1) ^ "_" ^ (strip_thy n2);
   624 
   625 fun dest_binop_typ (Type("fun",[range,Type("fun",[arg2,arg1])])) =
   626   (arg1,arg2,range)
   627   | dest_binop_typ _ = raise error "dest_binop_typ: not binary";
   628 (* -----
   629 > val t = (term_of o the o (parse thy)) "#3^#4";
   630 > val hT = type_of (head_of t);
   631 > dest_binop_typ hT;
   632 val it = ("'a","nat","'a") : typ * typ * typ
   633  ----- *)
   634 
   635 
   636 (** transform binary numeralsstrings **)
   637 (*Makarius 100308, hacked by WN*)
   638 val numbers_to_string =
   639   let
   640     fun dest_num t =
   641       (case try HOLogic.dest_number t of
   642         SOME (T, i) =>
   643           (*if T = @{typ int} orelse T = @{typ real} then WN*)
   644             SOME (Free (signed_string_of_int i, T))
   645           (*else NONE  WN*)
   646       | NONE => NONE);
   647 
   648     fun to_str (Abs (x, T, b)) = Abs (x, T, to_str b)
   649       | to_str (t as (u1 $ u2)) =
   650           (case dest_num t of
   651             SOME t' => t'
   652           | NONE => to_str u1 $ to_str u2)
   653       | to_str t = perhaps dest_num t;
   654   in to_str end
   655 
   656 (*.make uminus uniform: 
   657    Const ("uminus", _) $ Free ("2", "RealDef.real") --> Free ("-2", _)
   658 to be used immediately before evaluation of numerals; 
   659 see Scripts/calculate.sml .*)
   660 (*2002 fun(*app_num_tr'2 (Const("0",T)) = Free("0",T)
   661   | app_num_tr'2 (Const("1",T)) = Free("1",T)
   662   |*)app_num_tr'2 (t as Const("uminus",_) $ Free(s,T)) = 
   663     (case int_of_str s of Some i => 
   664 			  if i > 0 then Free("-"^s,T) else Free(s,T)
   665 		       | None => t)
   666 (*| app_num_tr'2 (t as Const(s,T)) = t
   667   | app_num_tr'2 (Const("Numeral.number_of",Type ("fun", [_, T])) $ t) = 
   668     Free(NumeralSyntax.dest_bin_str t, T)
   669   | app_num_tr'2 (t as Free(s,T)) = t
   670   | app_num_tr'2 (t as Var(n,T)) = t
   671   | app_num_tr'2 (t as Bound i) = t
   672 *)| app_num_tr'2 (Abs(s,T,body)) = Abs(s,T, app_num_tr'2 body)
   673   | app_num_tr'2 (t1 $ t2) = (app_num_tr'2 t1) $ (app_num_tr'2 t2)
   674   | app_num_tr'2 t = t;
   675 *)
   676 val uminus_to_string =
   677     let
   678 	fun dest_num t =
   679 	    (case t of
   680 		 (Const ("HOL.uminus_class.uminus", _) $ Free (s, T)) => 
   681 		 (case int_of_str s of
   682 		      SOME i => 
   683 		      SOME (Free (signed_string_of_int (~1 * i), T))
   684 		    | NONE => NONE)
   685 	       | _ => NONE);
   686 	    
   687 	fun to_str (Abs (x, T, b)) = Abs (x, T, to_str b)
   688 	  | to_str (t as (u1 $ u2)) =
   689             (case dest_num t of
   690 		 SOME t' => t'
   691                | NONE => to_str u1 $ to_str u2)
   692 	  | to_str t = perhaps dest_num t;
   693     in to_str end;
   694 
   695 
   696 (*2002 fun num_str thm =
   697   let 
   698     val {sign_ref = sign_ref, der = der, maxidx = maxidx,
   699 	    shyps = shyps, hyps = hyps, (*tpairs = tpairs,*) prop = prop} = 
   700 	rep_thm_G thm;
   701     val prop' = app_num_tr'1 prop;
   702   in assbl_thm sign_ref der maxidx shyps hyps (*tpairs*) prop' end;*)
   703 fun num_str thm =
   704   let val (deriv, 
   705 	   {thy_ref = thy_ref, tags = tags, maxidx = maxidx, shyps = shyps, 
   706 	    hyps = hyps, tpairs = tpairs, prop = prop}) = rep_thm_G thm
   707     val prop' = numbers_to_string prop;
   708   in assbl_thm deriv thy_ref tags maxidx shyps hyps tpairs prop' end;
   709 
   710 fun get_thm' xstring = (*?covers 2009 Thm?!, replaces 2002 fun get_thm :
   711 val it = fn : Theory.theory -> xstring -> Thm.thm*)
   712     Thm (xstring, 
   713 	 num_str (ProofContext.get_thm (ctxt_Isac"") xstring)); 
   714 
   715 (** get types of Free and Abs for parse' **)
   716 (*11.1.00: not used, fix-typed +,*,-,^ instead *)
   717 
   718 val dummyT = Type ("dummy",[]);
   719 val dummyT = TVar (("DUMMY",0),[]);
   720 
   721 (* assumes only 1 type for numerals 
   722    and different identifiers for Const, Free and Abs *)
   723 fun get_types t = 
   724   let
   725     fun get ts  (Const(s,T)) = (s,T)::ts
   726       | get ts  (Free(s,T)) = if is_no s 
   727 				then ("#",T)::ts else (s,T)::ts
   728       | get ts  (Var(n,T)) = ts
   729       | get ts  (Bound i) = ts
   730       | get ts  (Abs(s,T,body)) = get ((s,T)::ts)  body
   731       | get ts  (t1 $ t2) = (get ts  t1) @ (get ts  t2)
   732   in distinct (get [] t) end;
   733 (*
   734 val t = (term_of o the o (parse thy)) "sqrt(#9+#4*x)=sqrt x + sqrt(#-3+x)";
   735 get_types t;
   736 *)
   737 
   738 (*11.1.00: not used, fix-typed +,*,-,^ instead *)
   739 fun set_types al (Const(s,T)) = 
   740     (case assoc (al,s) of
   741        SOME T' => Const(s,T')
   742      | NONE => (warning ("set_types: no type for "^s); Const(s,dummyT)))
   743   | set_types al (Free(s,T)) = 
   744   if is_no s then
   745     (case assoc (al,"#") of
   746       SOME T' => Free(s,T')
   747     | NONE => (warning ("set_types: no type for numerals"); Free(s,T)))
   748   else (case assoc (al,s) of
   749 	       SOME T' => Free(s,T')
   750 	     | NONE => (warning ("set_types: no type for "^s); Free(s,T)))
   751   | set_types al (Var(n,T)) = Var(n,T)
   752   | set_types al (Bound i) = Bound i
   753   | set_types al (Abs(s,T,body)) = 
   754 		 (case assoc (al,s) of
   755 		    SOME T'  => Abs(s,T', set_types al body)
   756 		  | NONE => (warning ("set_types: no type for "^s);
   757 			     Abs(s,T, set_types al body)))
   758   | set_types al (t1 $ t2) = (set_types al t1) $ (set_types al t2);
   759 (*
   760 val t = (term_of o the o (parse thy)) "sqrt(#9+#4*x)=sqrt x + sqrt(#-3+x)";
   761 val al = get_types t;
   762 
   763 val t = (term_of o the o (parse thy)) "x = #0 + #-1 * #-4";
   764 atomty t;                         (* 'a *)
   765 val t' = set_types al t;
   766 atomty t';                        (*real*)
   767 cterm_of (sign_of thy) t';
   768 val it = "x = #0 + #-1 * #-4" : cterm
   769 
   770 val t = (term_of o the o (parse thy)) 
   771   "#5 * x + x ^^^ #2 = (#2 + x) ^^^ #2";
   772 atomty t;
   773 val t' = set_types al t;
   774 atomty t';
   775 cterm_of (sign_of thy) t';
   776 uncaught exception TYPE               (*^^^ is new, NOT in al*)
   777 *)
   778       
   779 
   780 (** from Descript.ML **)
   781 
   782 (** decompose an isa-list to an ML-list 
   783     i.e. [] belong to the meta-language, too **)
   784 
   785 fun is_list ((Const("List.list.Cons",_)) $ _ $ _) = true
   786   | is_list _ = false;
   787 (* val (SOME ct) = parse thy "lll::real list";
   788 > val ty = (#t o rep_cterm) ct;
   789 > is_list ty;
   790 val it = false : bool
   791 > val (SOME ct) = parse thy "[lll]";
   792 > val ty = (#t o rep_cterm) ct;
   793 > is_list ty;
   794 val it = true : bool *)
   795 
   796 
   797 
   798 fun mk_Free (s,T) = Free(s,T);
   799 fun mk_free T s =  Free(s,T);
   800 
   801 (*instantiate let; necessary for ass_up*)
   802 fun inst_abs thy (Const sT) = Const sT
   803   | inst_abs thy (Free sT) = Free sT
   804   | inst_abs thy (Bound n) = Bound n
   805   | inst_abs thy (Var iT) = Var iT
   806   | inst_abs thy (Const ("Let",T1) $ e $ (Abs (v,T2,b))) = 
   807   let val (v',b') = variant_abs (v,T2,b);     (*fun variant_abs: term.ML*)
   808   in Const ("Let",T1) $ inst_abs thy e $ (Abs (v',T2,inst_abs thy b')) end
   809   | inst_abs thy (t1 $ t2) = inst_abs thy t1 $ inst_abs thy t2
   810   | inst_abs thy t = 
   811     (writeln("inst_abs: unchanged t= "^ term2str t);
   812      t);
   813 (*val scr as (Script sc) = Script ((term_of o the o (parse thy))
   814  "Script Testeq (e_::bool) =                                        \
   815    \While (contains_root e_) Do                                     \
   816    \ (let e_ = Try (Repeat (Rewrite rroot_square_inv False e_));    \
   817    \      e_ = Try (Repeat (Rewrite square_equation_left True e_)) \
   818    \   in Try (Repeat (Rewrite radd_0 False e_)))                 ");
   819 ML> atomt sc;
   820 *** Const ( Script.Testeq)
   821 *** . Free ( e_, )
   822 *** . Const ( Script.While)
   823 *** . . Const ( RatArith.contains'_root)
   824 *** . . . Free ( e_, )
   825 *** . . Const ( Let)
   826 *** . . . Const ( Script.Try)
   827 *** . . . . Const ( Script.Repeat)
   828 *** . . . . . Const ( Script.Rewrite)
   829 *** . . . . . . Free ( rroot_square_inv, )
   830 *** . . . . . . Const ( False)
   831 *** . . . . . . Free ( e_, )
   832 *** . . . Abs( e_,..
   833 *** . . . . Const ( Let)
   834 *** . . . . . Const ( Script.Try)
   835 *** . . . . . . Const ( Script.Repeat)
   836 *** . . . . . . . Const ( Script.Rewrite)
   837 *** . . . . . . . . Free ( square_equation_left, )
   838 *** . . . . . . . . Const ( True)
   839 *** . . . . . . . . Bound 0                            <-- !!!
   840 *** . . . . . Abs( e_,..
   841 *** . . . . . . Const ( Script.Try)
   842 *** . . . . . . . Const ( Script.Repeat)
   843 *** . . . . . . . . Const ( Script.Rewrite)
   844 *** . . . . . . . . . Free ( radd_0, )
   845 *** . . . . . . . . . Const ( False)
   846 *** . . . . . . . . . Bound 0                          <-- !!!
   847 val it = () : unit
   848 ML> atomt (inst_abs thy sc);
   849 *** Const ( Script.Testeq)
   850 *** . Free ( e_, )
   851 *** . Const ( Script.While)
   852 *** . . Const ( RatArith.contains'_root)
   853 *** . . . Free ( e_, )
   854 *** . . Const ( Let)
   855 *** . . . Const ( Script.Try)
   856 *** . . . . Const ( Script.Repeat)
   857 *** . . . . . Const ( Script.Rewrite)
   858 *** . . . . . . Free ( rroot_square_inv, )
   859 *** . . . . . . Const ( False)
   860 *** . . . . . . Free ( e_, )
   861 *** . . . Abs( e_,..
   862 *** . . . . Const ( Let)
   863 *** . . . . . Const ( Script.Try)
   864 *** . . . . . . Const ( Script.Repeat)
   865 *** . . . . . . . Const ( Script.Rewrite)
   866 *** . . . . . . . . Free ( square_equation_left, )
   867 *** . . . . . . . . Const ( True)
   868 *** . . . . . . . . Free ( e_, )                        <-- !!!
   869 *** . . . . . Abs( e_,..
   870 *** . . . . . . Const ( Script.Try)
   871 *** . . . . . . . Const ( Script.Repeat)
   872 *** . . . . . . . . Const ( Script.Rewrite)
   873 *** . . . . . . . . . Free ( radd_0, )
   874 *** . . . . . . . . . Const ( False)
   875 *** . . . . . . . . . Free ( e_, )                      <-- ZUFALL vor 5.03!!!
   876 val it = () : unit*)
   877 
   878 
   879 
   880 
   881 fun inst_abs thy (Const sT) = Const sT
   882   | inst_abs thy (Free sT) = Free sT
   883   | inst_abs thy (Bound n) = Bound n
   884   | inst_abs thy (Var iT) = Var iT
   885   | inst_abs thy (Const ("Let",T1) $ e $ (Abs (v,T2,b))) = 
   886   let val b' = subst_bound (Free(v,T2),b);
   887   (*fun variant_abs: term.ML*)
   888   in Const ("Let",T1) $ inst_abs thy e $ (Abs (v,T2,inst_abs thy b')) end
   889   | inst_abs thy (t1 $ t2) = inst_abs thy t1 $ inst_abs thy t2
   890   | inst_abs thy t = 
   891     (writeln("inst_abs: unchanged t= "^ term2str t);
   892      t);
   893 (*val scr =    
   894    "Script Make_fun_by_explicit (f_::real) (v_::real) (eqs_::bool list) = \
   895    \ (let h_ = (hd o (filterVar f_)) eqs_;                    \
   896    \      e_1 = hd (dropWhile (ident h_) eqs_);       \
   897    \      vs_ = dropWhile (ident f_) (Vars h_);                \
   898    \      v_1 = hd (dropWhile (ident v_) vs_);                \
   899    \      (s_1::bool list)=(SubProblem(DiffApp_,[univar,equation],[no_met])\
   900    \                          [bool_ e_1, real_ v_1])\
   901    \ in Substitute [(v_1 = (rhs o hd) s_1)] h_)";
   902 > val ttt = (term_of o the o (parse thy)) scr;
   903 > writeln(term2str ttt);
   904 > atomt ttt;
   905 *** -------------
   906 *** Const ( DiffApp.Make'_fun'_by'_explicit)
   907 *** . Free ( f_, )
   908 *** . Free ( v_, )
   909 *** . Free ( eqs_, )
   910 *** . Const ( Let)
   911 *** . . Const ( Fun.op o)
   912 *** . . . Const ( List.hd)
   913 *** . . . Const ( DiffApp.filterVar)
   914 *** . . . . Free ( f_, )
   915 *** . . . Free ( eqs_, )
   916 *** . . Abs( h_,..
   917 *** . . . Const ( Let)
   918 *** . . . . Const ( List.hd)
   919 *** . . . . . Const ( List.dropWhile)
   920 *** . . . . . . Const ( Atools.ident)
   921 *** . . . . . . . Bound 0                     <---- Free ( h_, )
   922 *** . . . . . . Free ( eqs_, )
   923 *** . . . . Abs( e_1,..
   924 *** . . . . . Const ( Let)
   925 *** . . . . . . Const ( List.dropWhile)
   926 *** . . . . . . . Const ( Atools.ident)
   927 *** . . . . . . . . Free ( f_, )
   928 *** . . . . . . . Const ( Tools.Vars)
   929 *** . . . . . . . . Bound 1                       <---- Free ( h_, )
   930 *** . . . . . . Abs( vs_,..
   931 *** . . . . . . . Const ( Let)
   932 *** . . . . . . . . Const ( List.hd)
   933 *** . . . . . . . . . Const ( List.dropWhile)
   934 *** . . . . . . . . . . Const ( Atools.ident)
   935 *** . . . . . . . . . . . Free ( v_, )
   936 *** . . . . . . . . . . Bound 0                   <---- Free ( vs_, )
   937 *** . . . . . . . . Abs( v_1,..
   938 *** . . . . . . . . . Const ( Let)
   939 *** . . . . . . . . . . Const ( Script.SubProblem)
   940 *** . . . . . . . . . . . Const ( Pair)
   941 *** . . . . . . . . . . . . Free ( DiffApp_, )
   942 *** . . . . . . . . . . . . Const ( Pair)
   943 *** . . . . . . . . . . . . . Const ( List.list.Cons)
   944 *** . . . . . . . . . . . . . . Free ( univar, )
   945 *** . . . . . . . . . . . . . . Const ( List.list.Cons)
   946 *** . . . . . . . . . . . . . . . Free ( equation, )
   947 *** . . . . . . . . . . . . . . . Const ( List.list.Nil)
   948 *** . . . . . . . . . . . . . Const ( List.list.Cons)
   949 *** . . . . . . . . . . . . . . Free ( no_met, )
   950 *** . . . . . . . . . . . . . . Const ( List.list.Nil)
   951 *** . . . . . . . . . . . Const ( List.list.Cons)
   952 *** . . . . . . . . . . . . Const ( Script.bool_)
   953 *** . . . . . . . . . . . . . Bound 2                   <----- Free ( e_1, )
   954 *** . . . . . . . . . . . . Const ( List.list.Cons)
   955 *** . . . . . . . . . . . . . Const ( Script.real_)
   956 *** . . . . . . . . . . . . . . Bound 0                 <----- Free ( v_1, )
   957 *** . . . . . . . . . . . . . Const ( List.list.Nil)
   958 *** . . . . . . . . . . Abs( s_1,..
   959 *** . . . . . . . . . . . Const ( Script.Substitute)
   960 *** . . . . . . . . . . . . Const ( List.list.Cons)
   961 *** . . . . . . . . . . . . . Const ( Pair)
   962 *** . . . . . . . . . . . . . . Bound 1                 <----- Free ( v_1, )
   963 *** . . . . . . . . . . . . . . Const ( Fun.op o)
   964 *** . . . . . . . . . . . . . . . Const ( Tools.rhs)
   965 *** . . . . . . . . . . . . . . . Const ( List.hd)
   966 *** . . . . . . . . . . . . . . . Bound 0               <----- Free ( s_1, )
   967 *** . . . . . . . . . . . . . Const ( List.list.Nil)
   968 *** . . . . . . . . . . . . Bound 4                     <----- Free ( h_, )
   969 
   970 > val ttt' = inst_abs thy ttt;
   971 > writeln(term2str ttt');
   972 Script Make_fun_by_explicit f_ v_ eqs_ =  
   973   ... as above ...
   974 > atomt ttt';
   975 *** -------------
   976 *** Const ( DiffApp.Make'_fun'_by'_explicit)
   977 *** . Free ( f_, )
   978 *** . Free ( v_, )
   979 *** . Free ( eqs_, )
   980 *** . Const ( Let)
   981 *** . . Const ( Fun.op o)
   982 *** . . . Const ( List.hd)
   983 *** . . . Const ( DiffApp.filterVar)
   984 *** . . . . Free ( f_, )
   985 *** . . . Free ( eqs_, )
   986 *** . . Abs( h_,..
   987 *** . . . Const ( Let)
   988 *** . . . . Const ( List.hd)
   989 *** . . . . . Const ( List.dropWhile)
   990 *** . . . . . . Const ( Atools.ident)
   991 *** . . . . . . . Free ( h_, )                <---- Bound 0
   992 *** . . . . . . Free ( eqs_, )
   993 *** . . . . Abs( e_1,..
   994 *** . . . . . Const ( Let)
   995 *** . . . . . . Const ( List.dropWhile)
   996 *** . . . . . . . Const ( Atools.ident)
   997 *** . . . . . . . . Free ( f_, )
   998 *** . . . . . . . Const ( Tools.Vars)
   999 *** . . . . . . . . Free ( h_, )                  <---- Bound 1
  1000 *** . . . . . . Abs( vs_,..
  1001 *** . . . . . . . Const ( Let)
  1002 *** . . . . . . . . Const ( List.hd)
  1003 *** . . . . . . . . . Const ( List.dropWhile)
  1004 *** . . . . . . . . . . Const ( Atools.ident)
  1005 *** . . . . . . . . . . . Free ( v_, )
  1006 *** . . . . . . . . . . Free ( vs_, )             <---- Bound 0
  1007 *** . . . . . . . . Abs( v_1,..
  1008 *** . . . . . . . . . Const ( Let)
  1009 *** . . . . . . . . . . Const ( Script.SubProblem)
  1010 *** . . . . . . . . . . . Const ( Pair)
  1011 *** . . . . . . . . . . . . Free ( DiffApp_, )
  1012 *** . . . . . . . . . . . . Const ( Pair)
  1013 *** . . . . . . . . . . . . . Const ( List.list.Cons)
  1014 *** . . . . . . . . . . . . . . Free ( univar, )
  1015 *** . . . . . . . . . . . . . . Const ( List.list.Cons)
  1016 *** . . . . . . . . . . . . . . . Free ( equation, )
  1017 *** . . . . . . . . . . . . . . . Const ( List.list.Nil)
  1018 *** . . . . . . . . . . . . . Const ( List.list.Cons)
  1019 *** . . . . . . . . . . . . . . Free ( no_met, )
  1020 *** . . . . . . . . . . . . . . Const ( List.list.Nil)
  1021 *** . . . . . . . . . . . Const ( List.list.Cons)
  1022 *** . . . . . . . . . . . . Const ( Script.bool_)
  1023 *** . . . . . . . . . . . . . Free ( e_1, )             <----- Bound 2
  1024 *** . . . . . . . . . . . . Const ( List.list.Cons)
  1025 *** . . . . . . . . . . . . . Const ( Script.real_)
  1026 *** . . . . . . . . . . . . . . Free ( v_1, )           <----- Bound 0
  1027 *** . . . . . . . . . . . . . Const ( List.list.Nil)
  1028 *** . . . . . . . . . . Abs( s_1,..
  1029 *** . . . . . . . . . . . Const ( Script.Substitute)
  1030 *** . . . . . . . . . . . . Const ( List.list.Cons)
  1031 *** . . . . . . . . . . . . . Const ( Pair)
  1032 *** . . . . . . . . . . . . . . Free ( v_1, )           <----- Bound 1
  1033 *** . . . . . . . . . . . . . . Const ( Fun.op o)
  1034 *** . . . . . . . . . . . . . . . Const ( Tools.rhs)
  1035 *** . . . . . . . . . . . . . . . Const ( List.hd)
  1036 *** . . . . . . . . . . . . . . . Free ( s_1, )         <----- Bound 0
  1037 *** . . . . . . . . . . . . . Const ( List.list.Nil)
  1038 *** . . . . . . . . . . . . Free ( h_, )                <----- Bound 4
  1039 
  1040 Note numbering of de Bruijn indexes !
  1041 
  1042 Script Make_fun_by_explicit f_ v_ eqs_ =
  1043  let h_ = (hd o filterVar f_) eqs_; 
  1044      e_1 = hd (dropWhile (ident h_ BOUND_0) eqs_);
  1045      vs_ = dropWhile (ident f_) (Vars h_ BOUND_1);
  1046      v_1 = hd (dropWhile (ident v_) vs_ BOUND_0);
  1047      s_1 =
  1048        SubProblem (DiffApp_, [univar, equation], [no_met])
  1049         [bool_ e_1 BOUND_2, real_ v_1 BOUND_0]
  1050  in Substitute [(v_1 BOUND_1 = (rhs o hd) s_1 BOUND_0)] h_ BOUND_4
  1051 *)
  1052 
  1053 
  1054 fun T_a2real (Type (s, [])) = 
  1055     if s = "'a" orelse s = "'b" orelse s = "'c" then HOLogic.realT else Type (s, [])
  1056   | T_a2real (Type (s, Ts)) = Type (s, map T_a2real Ts)
  1057   | T_a2real (TFree (s, srt)) = 
  1058     if s = "'a" orelse s = "'b" orelse s = "'c" then HOLogic.realT else TFree (s, srt)
  1059   | T_a2real (TVar (("DUMMY",_),srt)) = HOLogic.realT;
  1060 
  1061 (*FIXME .. fixes the type (+see Typefix.thy*)
  1062 fun typ_a2real (Const( s, T)) = (Const( s, T_a2real T)) 
  1063   | typ_a2real (Free( s, T)) = (Free( s, T_a2real T))
  1064   | typ_a2real (Var( n, T)) = (Var( n, T_a2real T))
  1065   | typ_a2real (Bound i) = (Bound i)
  1066   | typ_a2real (Abs(s,T,t)) = Abs(s, T, typ_a2real t)
  1067   | typ_a2real (t1 $ t2) = (typ_a2real t1) $ (typ_a2real t2);
  1068 (*
  1069 ----------------6.8.02---------------------------------------------------
  1070  val str = "1";
  1071  val t = read_cterm (sign_of thy) (str,(TVar(("DUMMY",0),[])));
  1072  atomty (term_of t);
  1073 *** -------------
  1074 *** Const ( 1, 'a)
  1075  val t = (app_num_tr' o term_of) t;
  1076  atomty t;
  1077 *** ------------- 
  1078 *** Const ( 1, 'a)                                                              
  1079  val t = typ_a2real t;
  1080  atomty t;
  1081 *** -------------   
  1082 *** Const ( 1, real)                                                            
  1083 
  1084  val str = "2";
  1085  val t = read_cterm (sign_of thy) (str,(TVar(("DUMMY",0),[])));
  1086  atomty (term_of t);
  1087 *** -------------
  1088 *** Const ( Numeral.number_of, bin => 'a)
  1089 *** . Const ( Numeral.bin.Bit, [bin, bool] => bin)
  1090 *** . . Const ( Numeral.bin.Bit, [bin, bool] => bin)
  1091 *** . . . Const ( Numeral.bin.Pls, bin)
  1092 *** . . . Const ( True, bool)
  1093 *** . . Const ( False, bool)
  1094  val t = (app_num_tr' o term_of) t;
  1095  atomty t;
  1096 *** -------------
  1097 *** Free ( 2, 'a)
  1098  val t = typ_a2real t;
  1099  atomty t;
  1100 *** -------------
  1101 *** Free ( 2, real)
  1102 ----------------6.8.02---------------------------------------------------
  1103 
  1104 
  1105 > val str = "R";
  1106 > val t = term_of (read_cterm(sign_of thy)(str,(TVar(("DUMMY",0),[]))));
  1107 val t = Free ("R","?DUMMY") : term
  1108 > val t' = typ_a2real t;
  1109 > cterm_of (sign_of thy) t';
  1110 val it = "R::RealDef.real" : cterm
  1111 
  1112 > val str = "R=R";
  1113 > val t = term_of (read_cterm(sign_of thy)(str,(TVar(("DUMMY",0),[]))));
  1114 > atomty (typ_a2real t);
  1115 *** -------------
  1116 *** Const ( op =, [RealDef.real, RealDef.real] => bool)
  1117 ***   Free ( R, RealDef.real)
  1118 ***   Free ( R, RealDef.real)
  1119 > val t' = typ_a2real t;
  1120 > cterm_of (sign_of thy) t';
  1121 val it = "(R::RealDef.real) = R" : cterm
  1122 
  1123 > val str = "fixed_values [R=R]";
  1124 > val t = term_of (read_cterm(sign_of thy)(str,(TVar(("DUMMY",0),[]))));
  1125 > val t' = typ_a2real t;
  1126 > cterm_of (sign_of thy) t';
  1127 val it = "fixed_values [(R::RealDef.real) = R]" : cterm
  1128 *)
  1129 
  1130 (*TODO.WN0609: parse should return a term or a string 
  1131 	     (or even more comprehensive datastructure for error-messages)
  1132  i.e. in wrapping with SOME term or NONE the latter is not sufficient*)
  1133 (*2002 fun parseold thy str = 
  1134   (let 
  1135      val sgn = sign_of thy;
  1136      val t = ((*typ_a2real o*) app_num_tr'1 o term_of) 
  1137        (read_cterm sgn (str,(TVar(("DUMMY",0),[]))));
  1138    in SOME (cterm_of sgn t) end)
  1139      handle _ => NONE;*)
  1140 
  1141 
  1142 
  1143 fun parseold thy str = 
  1144   (let val t = ((*typ_a2real o*) numbers_to_string) 
  1145 		   (Syntax.read_term_global thy str)
  1146    in SOME (cterm_of thy t) end)
  1147     handle _ => NONE;
  1148 (*2002 fun parseN thy str = 
  1149   (let 
  1150      val sgn = sign_of thy;
  1151      val t = ((*typ_a2real o app_num_tr'1 o*) term_of) 
  1152        (read_cterm sgn (str,(TVar(("DUMMY",0),[]))));
  1153    in SOME (cterm_of sgn t) end)
  1154      handle _ => NONE;*)
  1155 fun parseN thy str = 
  1156   (let val t = (*(typ_a2real o numbers_to_string)*) 
  1157 	   (Syntax.read_term_global thy str)
  1158    in SOME (cterm_of thy t) end)
  1159     handle _ => NONE;
  1160 (*2002 fun parse thy str = 
  1161   (let 
  1162      val sgn = sign_of thy;
  1163      val t = (typ_a2real o app_num_tr'1 o term_of) 
  1164        (read_cterm sgn (str,(TVar(("DUMMY",0),[]))));
  1165    in SOME (cterm_of sgn t) end) (*FIXXXXME 10.8.02: return term !!!*)
  1166      handle _ => NONE;*)
  1167 (*2010 fun parse thy str = 
  1168   (let val t = (typ_a2real o app_num_tr'1) (Syntax.read_term_global thy str)
  1169    in SOME (cterm_of thy t) end) (*FIXXXXME 10.8.02: return term !!!*)
  1170      handle _ => NONE;*)
  1171 fun parse thy str = 
  1172   (let val t = (typ_a2real o numbers_to_string) 
  1173 		   (Syntax.read_term_global thy str)
  1174    in SOME (cterm_of thy t) end) (*FIXXXXME 10.8.02: return term !!!*)
  1175      handle _ => NONE;
  1176 
  1177 (* 10.8.02: for this reason we still have ^^^--------------------
  1178  val thy = SqRoot.thy;
  1179  val str = "(1::real) ^ (2::nat)";
  1180  val sgn = sign_of thy;
  1181  val ct = (read_cterm sgn (str,(TVar(("DUMMY",0),[])))) handle e =>print_exn e;
  1182 (*1*)"(1::real) ^ 2"; 
  1183  atomty (term_of ct);
  1184 *** -------------
  1185 *** Const ( Nat.power, [real, nat] => real)
  1186 *** . Const ( 1, real)
  1187 *** . Const ( Numeral.number_of, bin => nat)
  1188 *** . . Const ( Numeral.bin.Bit, [bin, bool] => bin)
  1189 *** . . . Const ( Numeral.bin.Bit, [bin, bool] => bin)
  1190 *** . . . . Const ( Numeral.bin.Pls, bin)
  1191 *** . . . . Const ( True, bool)
  1192 *** . . . Const ( False, bool)
  1193  val t = ((app_num_tr' o term_of) 
  1194 	 (read_cterm sgn (str,(TVar(("DUMMY",0),[])))))handle e => print_exn e;
  1195  val ct = (cterm_of sgn t) handle e => print_exn e;
  1196 (*2*)"(1::real) ^ (2::nat)";
  1197  atomty (term_of ct);
  1198 *** -------------
  1199 *** Const ( Nat.power, [real, nat] => real)
  1200 *** . Free ( 1, real)
  1201 *** . Free ( 2, nat)                                                            (*1*) Const("2",_) (*2*) Free("2",_)
  1202 
  1203 
  1204  val str = "(2::real) ^ (2::nat)";
  1205  val t = (read_cterm sgn (str,(TVar(("DUMMY",0),[])))) handle e => print_exn e;
  1206 val t = "(2::real) ^ 2" : cterm
  1207  val t = ((app_num_tr' o term_of) 
  1208 	 (read_cterm sgn (str,(TVar(("DUMMY",0),[])))))handle e => print_exn e;
  1209  val ct = (cterm_of sgn t) handle e => print_exn e;
  1210 Variable "2" has two distinct types
  1211 real
  1212 nat
  1213 uncaught exception TYPE
  1214   raised at: sign.ML:672.26-673.56
  1215              goals.ML:1100.61
  1216 
  1217 
  1218  val str = "(3::real) ^ (2::nat)";
  1219  val t = (read_cterm sgn (str,(TVar(("DUMMY",0),[])))) handle e => print_exn e;
  1220 val t = "(3::real) ^ 2" : cterm
  1221  val t = ((app_num_tr' o term_of) 
  1222 	 (read_cterm sgn (str,(TVar(("DUMMY",0),[])))))handle e => print_exn e;
  1223  val ct = (cterm_of sgn t) handle e => print_exn e;
  1224 val ct = "(3::real) ^ (2::nat)" : cterm
  1225 
  1226 
  1227 Conclusion: The type inference allows different types 
  1228             for one and the same  Numeral.number_of 
  1229         BUT the type inference doesn't allow 
  1230 	    Free ( 2, real) and Free ( 2, nat) within one term
  1231 ---------------       ~~~~                ~~~                  *)
  1232 (*
  1233 > val (SOME ct) = parse thy "(-#5)^^^#3"; 
  1234 > atomty (term_of ct);
  1235 *** -------------
  1236 *** Const ( Nat.op ^, ['a, nat] => 'a)
  1237 ***   Const ( uminus, 'a => 'a)
  1238 ***     Free ( #5, 'a)
  1239 ***   Free ( #3, nat)                
  1240 > val (SOME ct) = parse thy "R=R"; 
  1241 > atomty (term_of ct);
  1242 *** -------------
  1243 *** Const ( op =, [real, real] => bool)
  1244 ***   Free ( R, real)
  1245 ***   Free ( R, real)
  1246 
  1247 THIS IS THE OUTPUT FOR VERSION (3) above at typ_a2real !!!!!
  1248 *** -------------
  1249 *** Const ( op =, [RealDef.real, RealDef.real] => bool)
  1250 ***   Free ( R, RealDef.real)
  1251 ***   Free ( R, RealDef.real)                  *)
  1252 
  1253 (*version for testing local to theories*)
  1254 fun str2t thy str = (term_of o the o (parse thy )) str;
  1255 
  1256 fun str2term str = (term_of o the o (parse (assoc_thy "Isac.thy"))) str;
  1257 fun str2termN str = (term_of o the o (parseN (assoc_thy "Isac.thy"))) str;
  1258 fun strs2terms ss = map str2term ss;
  1259 
  1260 (*+ makes a substitution from the output of Pattern.match +*)
  1261 (*fun mk_subs ((id, _):indexname, t:term) = (Free (id,type_of t), t);*)
  1262 fun mk_subs (subs: ((string * int) * (Term.typ * Term.term)) list) =
  1263 let fun mk_sub ((id, _), (ty, tm)) = (Free (id, ty), tm) in
  1264 map mk_sub subs end;
  1265 
  1266 val atomthm = atomt o #prop o rep_thm;
  1267 
  1268 (*.instantiate #prop thm with bound variables (as Free).*)
  1269 fun inst_bdv [] t = t : term
  1270   | inst_bdv (instl: (term*term) list) t =
  1271       let fun subst (v as Var((s,_),T)) = 
  1272 	      (case explode s of
  1273 		   "b"::"d"::"v"::_ => 
  1274 		   if_none (assoc(instl,Free(s,T))) (Free(s,T))
  1275 		 | _ => v)
  1276             | subst (Abs(a,T,body)) = Abs(a, T, subst body)
  1277             | subst (f$t') = subst f $ subst t'
  1278             | subst t = if_none (assoc(instl,t)) t
  1279       in  subst t  end;
  1280 
  1281 
  1282 (*WN050829 caution: is_atom (str2term"q_0/2 * L * x") = true !!!
  1283   use length (vars term) = 1 instead*)
  1284 fun is_atom (Const ("Float.Float",_) $ _) = true
  1285   | is_atom (Const ("ComplexI.I'_'_",_)) = true
  1286   | is_atom (Const ("op *",_) $ t $ Const ("ComplexI.I'_'_",_)) = is_atom t
  1287   | is_atom (Const ("op +",_) $ t1 $ Const ("ComplexI.I'_'_",_)) = is_atom t1
  1288   | is_atom (Const ("op +",_) $ t1 $ 
  1289 		   (Const ("op *",_) $ t2 $ Const ("ComplexI.I'_'_",_))) = 
  1290     is_atom t1 andalso is_atom t2
  1291   | is_atom (Const _) = true
  1292   | is_atom (Free _) = true
  1293   | is_atom (Var _) = true
  1294   | is_atom _ = false;
  1295 (* val t = str2term "q_0/2 * L * x";
  1296 
  1297 
  1298 *)
  1299 (*val t = str2term "Float ((1,2),(0,0))";
  1300 > is_atom t;
  1301 val it = true : bool
  1302 > val t = str2term "Float ((1,2),(0,0)) * I__";
  1303 > is_atom t;
  1304 val it = true : bool
  1305 > val t = str2term "Float ((1,2),(0,0)) + Float ((3,4),(0,0)) * I__";
  1306 > is_atom t;
  1307 val it = true : bool
  1308 > val t = str2term "1 + 2*I__";
  1309 > val Const ("op +",_) $ t1 $ (Const ("op *",_) $ t2 $ Const ("ComplexI.I'_'_",_)) = t;
  1310 *)
  1311 
  1312 (*.adaption from Isabelle/src/Pure/term.ML; reports if ALL Free's
  1313    have found a substitution (required for evaluating the preconditions
  1314    of _incomplete_ models).*)
  1315 fun subst_atomic_all [] t = (false, (*TODO may be 'true' for some terms ?*)
  1316 			     t : term)
  1317   | subst_atomic_all (instl: (term*term) list) t =
  1318       let fun subst (Abs(a,T,body)) = 
  1319 	      let val (all, body') = subst body
  1320 	      in (all, Abs(a, T, body')) end
  1321             | subst (f$tt) = 
  1322 	      let val (all1, f') = subst f
  1323 		  val (all2, tt') = subst tt
  1324 	      in (all1 andalso all2, f' $ tt') end
  1325             | subst (t as Free _) = 
  1326 	      if is_num t then (true, t) (*numerals cannot be subst*)
  1327 	      else (case assoc(instl,t) of
  1328 					 SOME t' => (true, t')
  1329 				       | NONE => (false, t))
  1330             | subst t = (true, if_none (assoc(instl,t)) t)
  1331       in  subst t  end;
  1332 
  1333 (*.add two terms with a type given.*)
  1334 fun mk_add t1 t2 =
  1335     let val T1 = type_of t1
  1336 	val T2 = type_of t2
  1337     in if T1 <> T2 then raise TYPE ("mk_add gets ",[T1, T2],[t1,t2])
  1338        else (Const ("op +", [T1, T2] ---> T1) $ t1 $ t2)
  1339     end;
  1340