src/Tools/isac/ProgLang/termC.sml
author Walther Neuper <neuper@ist.tugraz.at>
Sat, 07 Jan 2012 10:06:06 +0100
changeset 42360 2c8de368c64c
parent 42359 b9d382f20232
child 42376 9e59542132b3
permissions -rw-r--r--
invisible changes in calculations are possible now.

Build_Inverse_Z_Transform came up with the Program:
:
" eq = (Try (Rewrite_Set ansatz False)) eq; " ^
" eq = drop_questionmarks eq; " ^
" (z1::real) = (rhs (NTH 1 L_L)); " ^
" (eq_a::bool) = (Substitute [zzz=z1]) eq; " ^
:
BEFORE Substitute was done on the result from Rewrite_Set ansatz,
i.e. drop_questionmarks was useless: "?A", "?B" still existed.
NOW the result from Substitute has "A", "B";
however, we have to observe not to cause confusion on the user.

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