src/Tools/isac/Interpret/ptyps.sml
author Mathias Lehnfeld <s1210629013@students.fh-hagenberg.at>
Fri, 25 Oct 2013 20:58:28 +0100
changeset 52159 db46e97751eb
parent 52153 26f274076fd2
child 55321 c08e1f460023
permissions -rw-r--r--
removed all code concerned with "calclist' = Unsynchronized.ref"
     1 (* the problems and methods as stored in hierarchies
     2    author Walther Neuper 1998, Mathias Lehnfeld
     3    (c) due to copyright terms
     4 
     5 use"ME/ptyps.sml";
     6 use"ptyps.sml";
     7 *)
     8 
     9 (*-----------------------------------------vvv-(1) aus modspec.sml 23.3.02*)
    10 val dsc_unknown = (term_of o the o (parseold @{theory Script})) 
    11   "unknown::'a => unknow";
    12 (*-----------------------------------------^^^-(1) aus modspec.sml 23.3.02*)
    13 
    14 
    15 (*-----------------------------------------vvv-(2) aus modspec.sml 23.3.02*)
    16 
    17 fun itm_2item thy (Cor ((d,ts),_)) = 
    18     Correct (term2str (comp_dts (d,ts)))
    19   | itm_2item _ (Syn c)            = SyntaxE c
    20   | itm_2item _ (Typ c)            = TypeE c
    21   | itm_2item thy (Inc ((d,ts),_)) = 
    22     Incompl (term2str (comp_dts (d,ts)))
    23   | itm_2item thy (Sup (d,ts))     = 
    24     Superfl (term2str (comp_dts (d,ts)))
    25   | itm_2item _ (Mis (d,pid))   =
    26     Missing (term2str d ^ " " ^ term2str pid);
    27 
    28 
    29 (* --- 8.3.00
    30 fun get_dsc_in dscppc sel = ((the (assoc (dscppc, sel))):term list)
    31   handle _ => error ("get_dsc_in not for "^sel);
    32 
    33 fun dscs_in dscppc = 
    34   ((get_dsc_in dscppc "#Given") @
    35    (get_dsc_in dscppc "#Find") @
    36    (get_dsc_in dscppc "#Relate")):term list;
    37 
    38    --- 26.1.88
    39 fun get_dsc_of pblID sel = (the (assoc((snd o get_pbt) pblID, sel)));
    40 fun get_dsc pblID = 
    41   (get_dsc_of pblID "#Given") @
    42   (get_dsc_of pblID "#Find") @
    43   (get_dsc_of pblID "#Relate");
    44  --- *)
    45 
    46 fun mappc f ({Given=gi,Where=wh,Find=fi,With=wi,Relate=re}:'a ppc) = 
    47   {Given=map f gi, Where=map f wh,
    48    Find=map f fi, With=map f wi, Relate=map f re}:'b ppc;
    49 fun appc f ({Given=gi,Where=wh,Find=fi,With=wi,Relate=re}:'a ppc) = 
    50   {Given=f gi, Where=f wh,
    51    Find=f fi, With=f wi, Relate=f re}:'b ppc;
    52 
    53 (*for ppc of changing type*)
    54 fun sel_ppc sel ppc =
    55   case sel of
    56     "#Given" => #Given (ppc:'a ppc)
    57   | "#Where" => #Where (ppc:'a ppc)
    58   | "#Find" => #Find (ppc:'a ppc)
    59   | "#With" => #With (ppc:'a ppc)
    60   | "#Relate" => #Relate (ppc:'a ppc)
    61   | _  => error ("sel_ppc tried to select by '"^sel^"'");
    62 
    63 fun repl_sel_ppc sel
    64   ({Given=gi,Where=wh,Find=fi,With=wi,Relate=re}:'a ppc) x =
    65   case sel of
    66     "#Given" => ({Given= x,Where=wh,Find=fi,With=wi,Relate=re}:'a ppc)
    67   | "#Where" => {Given=gi,Where= x,Find=fi,With=wi,Relate=re}
    68   | "#Find" => {Given=gi,Where=wh,Find= x,With=wi,Relate=re}
    69   | "#With" => {Given=gi,Where=wh,Find=fi,With= x,Relate=re}
    70   | "#Relate" => {Given=gi,Where=wh,Find=fi,With=wi,Relate= x}
    71   | _  => error ("repl_sel_ppc tried to select by '"^sel^"'");
    72 
    73 fun add_sel_ppc thy sel
    74   ({Given=gi,Where=wh,Find=fi,With=wi,Relate=re}:'a ppc) x =
    75   case sel of
    76     "#Given" => ({Given=gi@[x],Where=wh,Find=fi,With=wi,Relate=re}:'a ppc)
    77   | "#Where" => {Given=gi,Where=wh@[x],Find=fi,With=wi,Relate=re}
    78   | "#Find"  => {Given=gi,Where=wh,Find=fi@[x],With=wi,Relate=re}
    79   | "#Relate"=> {Given=gi,Where=wh,Find=fi,With=wi,Relate=re@[x]}
    80   | "#undef" => {Given=gi@[x],Where=wh,Find=fi,With=wi,Relate=re}(*ori2itmSup*)
    81   | _  => error ("add_sel_ppc tried to select by '"^sel^"'");
    82 fun add_where ({Given=gi,Find=fi,With=wi,Relate=re,...}:'a ppc) wh =
    83     ({Given=gi,Where=wh,Find=fi,With=wi,Relate=re}:'a ppc);
    84 
    85 (*decompose a problem-type into description and identifier
    86   FIXME split_dsc: no term list !!! (just for quick redoing prep_ori) *)
    87 fun split_dsc thy t =
    88   (let val (hd,args) = strip_comb t
    89    in if is_dsc hd
    90       then (hd, args)
    91        else (e_term, [t])    (*??? 9.01 just copied*)
    92    end)
    93   handle _ => error ("split_dsc: called with " ^ term2str t);
    94 (*
    95 > val t1 = (term_of o the o (parse thy)) "errorBound err_";
    96 > split_dsc t1;
    97 (Const ("Descript.errorBound","bool => Tools.nam"),Free ("err_","bool"))
    98   : term * term
    99 > val t3 = (term_of o the o (parse thy)) "valuesFor vs_";
   100 > split_dsc t3;
   101 (Const ("Descript.valuesFor","bool List.list => Tools.toreall"),
   102    Free ("vs_","bool List.list")) : term * term*)
   103 
   104 
   105 
   106 (*. take the first two return-values; for prep_ori .*)
   107 (*WN.13.5.03fun split_dts' thy t =
   108     let val (d, ts, _) = split_dts thy t
   109     in (d, ts) end;*)
   110 (*WN.8.12.03 quick for prep_ori'*)
   111 fun split_dsc' t =
   112   (let val dsc $ var = t
   113   in var end)
   114   handle _ => error ("split_dsc': called with "^term2str t);
   115 
   116 (*9.3.00*)
   117 (* split a term into description and (id | structured variable)
   118    for pbt, met.ppc *)
   119 fun split_did t =
   120   (let val (hd,[arg]) = strip_comb t
   121   in (hd,arg) end)
   122   handle _ => 
   123          error ("split_did: doesn't match (hd,[arg]) for t = " ^term2str t);
   124 
   125 
   126 
   127 (*create output-string for itm_*)
   128 fun itm_out thy (Cor ((d,ts),_)) = term2str (comp_dts (d,ts))
   129   | itm_out thy (Syn c)      = c
   130   | itm_out thy (Typ c)      = c
   131   | itm_out thy (Inc ((d,ts),_)) = term2str (comp_dts (d,ts))
   132   | itm_out thy (Sup (d,ts)) = term2str (comp_dts (d,ts))
   133   | itm_out thy (Mis (d,pid)) = term2str d ^ " " ^ term2str pid;
   134 
   135 fun boolterm2item (true, term) = Correct (term2str term)
   136   | boolterm2item (false, term) = False (term2str term);
   137 
   138 (* use"ME/modspec.sml";
   139    *)
   140 fun itms2itemppc thy (itms:itm list) (pre:(bool * term) list) =
   141   let
   142     fun coll ppc [] = ppc
   143       | coll ppc ((_,_,_,field,itm_)::itms) = 
   144       coll (add_sel_ppc thy field ppc (itm_2item thy itm_)) itms;
   145     val gfr = coll empty_ppc itms;
   146   in add_where gfr (map boolterm2item pre) end;
   147 
   148 (* 9.3.00
   149    compare d and dsc in pbt and transfer field to pre-ori *)
   150 fun add_field thy pbt (d,ts) = 
   151   let fun eq d pt = (d = (fst o snd) pt);
   152   in case filter (eq d) pbt of
   153        [(fi,(dsc,_))] => (fi,d,ts)
   154      | [] => ("#undef",d,ts)   (*may come with met.ppc*)
   155      | _ => error ("add_field: " ^ term2str d ^ " more than once in pbt")
   156   end;
   157 
   158 (*. take over field from met.ppc at 'Specify_Method' into ori,
   159    i.e. also removes "#undef" fields                        .*)
   160 (* val (mpc, ori) =  ((#ppc o get_met) mID, oris);
   161    *)
   162 fun add_field' thy mpc (ori:ori list) =
   163   let fun eq d pt = (d = (fst o snd) pt);
   164     fun repl mpc (i,v,_,d,ts) = 
   165       case filter (eq d) mpc of
   166 	[(fi,(dsc,_))] => [(i,v,fi,d,ts)]
   167       | [] => [] (*25.2.02: dsc in ori, but not in met -> superfluous*)    
   168       | _ => error ("add_field': " ^ term2str d ^ " more than once in met");
   169   in (flat ((map (repl mpc)) ori)):ori list end;
   170 
   171 
   172 (*.mark an element with the position within a plateau;
   173    a plateau with length 1 is marked with 0        .*)
   174 fun mark eq [] = error "mark []"
   175   | mark eq xs =
   176   let
   177     fun mar xx eq [x] n = xx @ [(if n=1 then 0 else n,x)]
   178       | mar xx eq (x::x'::xs) n = 
   179       if eq(x,x') then mar (xx @ [(n,x)]) eq (x'::xs) (n+1)
   180       else mar (xx @ [(if n=1 then 0 else n,x)]) eq (x'::xs) 1;
   181   in mar [] eq xs 1 end;
   182 (*
   183 > val xs = [1,1,1,2,4,4,5];
   184 > mark (op=) xs;
   185 val it = [(1,1),(2,1),(3,1),(0,2),(1,4),(2,4),(0,5)]
   186 *)
   187 
   188 (*.assumes equal descriptions to be in adjacent 'plateaus',
   189    items at a certain position within the plateaus form a variant;
   190    length = 1 ... marked with 0: covers all variants           .*)
   191 fun add_variants fdts = 
   192   let 
   193     fun eq (a,b) = curry op= (snd3 a) (snd3 b);
   194   in mark eq fdts end;
   195 
   196 (* collect equal elements: the model for coll_variants *)
   197 fun coll eq xs =
   198   let
   199     fun col xs eq x [] = xs @ [x]
   200       | col xs eq x (y::ys) = 
   201       if eq(x,y) then col xs eq x ys
   202       else col (xs @ [x]) eq y ys;
   203   in col [] eq (hd xs) xs end;
   204 (* 
   205 > val xs = [1,1,1,2,4,4,4];
   206 > coll (op=) xs;
   207 val it = [1,2,4] : int list
   208 *)
   209 
   210 fun max [] = error "max of []"
   211   | max (y::ys) =
   212   let fun mx x [] = x
   213 	| mx x (y::ys) = if x < y then mx y ys else mx x ys;
   214 in mx y ys end;
   215 fun gen_max _ [] = error "gen_max of []"
   216   | gen_max ord (y::ys) =
   217   let fun mx x [] = x
   218 	| mx x (y::ys) = if ord (x, y) then mx y ys else mx x ys;
   219 in mx y ys end;
   220 
   221 
   222 
   223 (* assumes *)
   224 fun coll_variants (((v,x)::vxs)) =
   225   let
   226     fun col xs (vs,x) [] = xs @ [(vs,x)]
   227       | col xs (vs,x) ((v',x')::vxs') = 
   228       if x=x' then col xs (vs @ [v'], x') vxs'
   229       else col (xs @ [(vs,x)]) ([v'], x') vxs';
   230   in col [] ([v],x) vxs end;
   231 (* val xs = [(1,1),(2,1),(3,1),(0,2),(1,4),(2,4),(0,5)];
   232 > col [] ([(fst o hd) xs],(snd o hd) xs) (tl xs);
   233 val it = [([1,2,3],1),([0],2),([1,2],4),([0],5)]  *)
   234 
   235 
   236 fun replace_0 vm [0] = intsto vm
   237   | replace_0 vm vs = vs;
   238 
   239 fun add_id [] = error "add_id []"
   240   | add_id xs =
   241   let fun add n [] = []
   242 	| add n (x::xs) = (n,x) :: add (n+1) xs;
   243 in add 1 xs end;
   244 (*
   245 > val xs = [([1,2,3],1),([0],2),([1,2],4),([0],5)];
   246 > add_id xs;
   247 val it = [(1,([#,#,#],1)),(2,([#],2)),(3,([#,#],4)),(4,([#],5))]
   248  *)
   249 
   250 fun flattup (a,(b,(c,d,e))) = (a,b,c,d,e);
   251 fun flattup' (a,(b,((c,d),e))) = (a,b,c,d,e);
   252 fun flat3 (a,(b,c)) = (a,b,c);
   253 (*
   254  val pI = pI';
   255  !pbts;
   256 *)
   257 (* in root (only!) fmz may be empty: fill with ..,dsc,[]
   258 fun init_ori fmz thy pI =
   259   if fmz <> [] then prep_ori fmz thy pI (*fmz assumed complete*)
   260   else
   261     let 
   262       val fds = map (cons2 (fst, fst o snd)) (get_pbt pI);
   263       val vfds = map ((pair [1]) o (rpair [])) fds;
   264       val ivfds = add_id vfds
   265     in (map flattup' ivfds):ori list end;   10.3.00---*)
   266 (* val fmz = ctl; val pI=["sqroot-test","univariate","equation"];
   267    val (thy,pbt) = (assoc_thy dI',(#ppc o get_pbt) pI');
   268    val (fmz, thy, pbt) = (fmz, thy, ((#ppc o get_pbt) pI));
   269    *)
   270 
   271 fun prep_ori [] _ _ = ([], e_ctxt)
   272   | prep_ori fmz thy pbt =
   273       let
   274         val ctxt = Proof_Context.init_global thy |> fold declare_constraints fmz;
   275         val ori = map (add_field thy pbt o split_dts o the o parseNEW ctxt) fmz
   276           |> add_variants;
   277         val maxv = map fst ori |> max;
   278         val maxv = if maxv = 0 then 1 else maxv;
   279         val oris = coll_variants ori
   280           |> map (replace_0 maxv |> apfst)
   281           |> add_id
   282           |> map flattup;
   283       in (oris, ctxt) end;
   284 
   285 (*.the pattern for an item of a problems model or a methods guard.*)
   286 type pat =
   287   (string *     (* field               *)
   288 	  (term *     (* description         *)
   289 	     term))   (* id | arbitrary term *);
   290 fun pat2str ((field, (dsc, id)):pat) = 
   291     pair2str (field, pair2str (term2str dsc, term2str id));
   292 fun pats2str pats = (strs2str o (map pat2str)) pats;
   293 
   294 val e_errpat = ("e_errpatID", [parse_patt @{theory} "?a = ?b"], [@{thm refl}]): errpat
   295 val e_fillpat = ("e_fillpatID", parse_patt @{theory} "?a = _", "e_errpatID")
   296 
   297 (* data for methods stored in 'methods'-database*)
   298 type met = 
   299      {guh        : guh,        (*unique within this isac-knowledge           *)
   300       mathauthors: string list,(*copyright                                   *)
   301       init       : pblID,      (*WN060721 introduced mistakenly--TODO.REMOVE!*)
   302       rew_ord'   : rew_ord',   (*for rules in Detail
   303 			                           TODO.WN0509 store fun itself, see 'type pbt'*)
   304       erls       : rls,        (*the eval_rls for cond. in rules FIXME "rls'
   305 				                         instead erls in "fun prep_met"              *)
   306       srls       : rls,        (*for evaluating list expressions in scr      *)
   307       prls       : rls,        (*for evaluating predicates in modelpattern   *)
   308       crls       : rls,        (*for check_elementwise, ie. formulae in calc.*)
   309       nrls       : rls,        (*canonical simplifier specific for this met  *)
   310       errpats    : errpat list,(*error patterns expected in this method      *)
   311       calc       : calc list,  (*Theory_Data in fun prep_met                 *)
   312       (*branch   : TransitiveB set in append_problem at generation ob pblobj
   313           FIXXXME.0308: set branch from met in Apply_Method ?                *)
   314       ppc        : pat list,   (*.items in given, find, relate;
   315 	      items (in "#Find") which need not occur in the arg-list of a SubProblem
   316         are 'copy-named' with an identifier "*'.'".
   317         copy-named items are 'generating' if they are NOT "*'''" ?WN120516??
   318         see ME/calchead.sml 'fun is_copy_named'.                              *)
   319       pre        : term list,  (*preconditions in where                       *)
   320       scr        : scr         (*prep_met gets progam or string "empty_script"*)
   321 	   };
   322 val e_met = {guh="met_empty",mathauthors=[],init=e_metID,
   323 	     rew_ord' = "e_rew_ord'": rew_ord',
   324 	      erls = e_rls, srls = e_rls, prls = e_rls,
   325 	      calc = [], crls = e_rls, errpats = [], nrls= e_rls,
   326 	      ppc = []: (string * (term * term)) list,
   327 	      pre = []: term list,
   328 	      scr = EmptyScr: scr}:met;
   329 
   330 
   331 (** problem-types stored in format for usage in specify  **)
   332 (*25.8.01 ----
   333 val pbltypes = Unsynchronized.ref ([(e_pblID,[])]:(pblID * ((string * (* field "#Given",..*)
   334 			     (term *   (* description      *)
   335 			      term))    (* id | struct-var  *)
   336 			     list)
   337 		    ) list);*)
   338 
   339 type pbt_ = (string *  (* field "#Given",..*)(*deprecated due to 'type pat'*)
   340 	      (term *   (* description      *)
   341 	       term));   (* id | struct-var  *)
   342 val e_pbt_ = ("#Undef", (e_term, e_term)):pbt_;
   343 type pbt = 
   344      {guh  : guh,         (*unique within this isac-knowledge*)
   345       mathauthors: string list, (*copyright*)
   346       init  : pblID,      (*to start refinement with*)
   347       thy   : theory,     (* which allows to compile that pbt
   348 			  TODO: search generalized for subthy (ref.p.69*)
   349       (*^^^ WN050912 NOT used during application of the problem,
   350        because applied terms may be from 'subthy' as well as from super;
   351        thus we take 'maxthy'; see match_ags !*)
   352       cas   : term option,(*'CAS-command'*)
   353       prls  : rls,        (* for preds in where_*)
   354       where_: term list,  (* where - predicates*)
   355       ppc   : pat list,
   356       (*this is the model-pattern; 
   357        it contains "#Given","#Where","#Find","#Relate"-patterns
   358        for constraints on identifiers see "fun cpy_nam"*)
   359       met   : metID list}; (* methods solving the pbt*)
   360 val e_pbt = {guh="pbl_empty",mathauthors=[],init=e_pblID,thy=Thy_Info.get_theory "Pure",
   361 	     cas=NONE,prls=Erls,where_=[],ppc=[],met=[]}:pbt;
   362 fun pbt2 (str, (t1, t2)) = 
   363     pair2str (str, pair2str (term2str t1, term2str t2));
   364 fun pbt2str pbt = (strs2str o (map (linefeed o pbt2))) pbt;
   365 
   366 
   367 val e_Ptyp = Ptyp ("e_pblID",[e_pbt],[]);
   368 val e_Mets = Ptyp ("e_metID",[e_met],[]);
   369 
   370 type ptyps = (pbt ptyp) list;
   371 val ptyps = Unsynchronized.ref ([e_Ptyp]:ptyps);
   372 
   373 type mets = (met ptyp) list;
   374 val mets = Unsynchronized.ref ([e_Mets]:mets);
   375 
   376 
   377 (**+ breadth-first search on hierarchy of problem-types +**)
   378 
   379 type pblRD = pblID;(*pblID are Reverted _on calling_ the retrieve-funs*)
   380      (* eg. ["equations","univariate","normalize"] while
   381 	    ["normalize","univariate","equations"] is the related pblID
   382       WN.24.4.03: also used for metID*)
   383 
   384 fun get_py thy d _ [] = 
   385     error ("get_pbt not found: "^(strs2str d))
   386   | get_py thy d [k] ((Ptyp (k',[py],_))::pys) =
   387     if k=k' then py
   388     else get_py thy d ([k]:pblRD) pys
   389   | get_py thy d (k::ks) ((Ptyp (k',_,pys))::pys') =
   390     if k=k' then get_py thy d ks pys
   391     else get_py thy d (k::ks) pys';
   392 (*> ptyps:= 
   393 [Ptyp ("1",[("ptyp 1",([],[]))],
   394 	[Ptyp ("11",[("ptyp 11",([],[]))],
   395 		[])
   396 	 ]),
   397  Ptyp ("2",[("ptyp 2",([],[]))],
   398 	[Ptyp ("21",[("ptyp 21",([],[]))],
   399 		[])
   400 	 ])
   401  ];
   402 > get_py SqRoot.thy ["1"] ["1"] (!ptyps);
   403 > get_py SqRoot.thy ["2","21"] ["2","21"] (!ptyps);
   404          _REVERSE_  .......... !!!!!!!!!!*)
   405 
   406 (*TODO: search generalized for subthy*)
   407 fun get_pbt (pblID:pblID) =
   408     let val pblRD = rev pblID;
   409     in get_py (Thy_Info.get_theory "Pure") pblID pblRD (!ptyps) end;
   410 (* get_pbt thy ["1"];
   411    get_pbt thy ["21","2"];
   412    *)
   413 
   414 (*TODO: throws exn 'get_pbt not found: ' ... confusing !!
   415   take 'ketype' as an argument !!!!!*)
   416 fun get_met (metID:metID) = get_py  (Thy_Info.get_theory "Pure") metID metID (!mets);
   417 fun get_the (theID:theID) = get_py  (Thy_Info.get_theory "Pure") theID theID (! thehier);
   418 
   419 
   420 
   421 fun del_eq k ptyps =
   422 let fun del k ptyps [] = ptyps
   423       | del k ptyps ((Ptyp (k', [p], ps))::pys) =
   424 	if k=k' then del k ptyps pys
   425 	else del k (ptyps @ [Ptyp (k', [p], ps)]) pys;
   426 in del k [] ptyps end;
   427 
   428 fun insrt _ pbt [k] [] = [Ptyp (k, [pbt],[])]
   429 			 
   430   | insrt d pbt [k] ((Ptyp (k', [p], ps))::pys) =
   431 ((*tracing("### insert 1: ks = "^(strs2str [k])^"    k'= "^k');*)
   432      if k=k'
   433      then ((Ptyp (k', [pbt], ps))::pys)
   434      else (*ev.newly added pbt is free _only_ with 'last_elem pblID'*)
   435 	 ((Ptyp (k', [p], ps))::(insrt d pbt [k] pys))
   436 )			 
   437   | insrt d pbt (k::ks) ((Ptyp (k', [p], ps))::pys) =
   438 ((*tracing("### insert 2: ks = "^(strs2str (k::ks))^"    k'= "^k');*)
   439      if k=k'
   440      then ((Ptyp (k', [p], insrt d pbt ks ps))::pys)
   441      else 
   442 	 if length pys = 0
   443 	 then error ("insert: not found "^(strs2str (d:pblID)))
   444 	 else ((Ptyp (k', [p], ps))::(insrt d pbt (k::ks) pys))
   445 );
   446 
   447 
   448 fun coll_pblguhs pbls =
   449     let fun node coll (Ptyp (_,[n],ns)) =
   450 	    [(#guh : pbt -> guh) n] @ (nodes coll ns)
   451 	and nodes coll [] = coll
   452 	  | nodes coll (n::ns) = (node coll n) @ (nodes coll ns);
   453     in nodes [] pbls end;
   454 fun coll_metguhs mets =
   455     let fun node coll (Ptyp (_,[n],ns)) =
   456 	    [(#guh : met -> guh) n]
   457 	and nodes coll [] = coll
   458 	  | nodes coll (n::ns) = (node coll n) @ (nodes coll ns);
   459     in nodes [] mets end;
   460 
   461 (*.lookup a guh in hierarchy or methods depending on fst chars in guh.*)
   462 fun guh2kestoreID (guh:guh) =
   463     case (implode o (take_fromto 1 4) o Symbol.explode) guh of
   464 	"pbl_" =>
   465 	let fun node ids gu (Ptyp (id,[n as {guh,...} : pbt], ns)) =
   466 		if gu = guh 
   467 		then SOME ((ids@[id]) : kestoreID)
   468 		else nodes (ids@[id]) gu ns
   469 	    and nodes _ _ [] = NONE 
   470 	      | nodes ids gu (n::ns) = 
   471 		case node ids gu n of SOME id => SOME id
   472 				    | NONE =>  nodes ids gu ns
   473 	in case nodes [] guh (!ptyps) of
   474 	       SOME id => rev id
   475 	     | NONE => error ("guh2kestoreID: '" ^ guh ^ "' " ^
   476 				    "not found in (!ptyps)")
   477 	end
   478       | "met_" =>
   479 	let fun node ids gu (Ptyp (id,[n as {guh,...} : met], ns)) =
   480 		if gu = guh 
   481 		then SOME ((ids@[id]) : kestoreID)
   482 		else nodes (ids@[id]) gu ns
   483 	    and nodes _ _ [] = NONE 
   484 	      | nodes ids gu (n::ns) = 
   485 		case node ids gu n of SOME id => SOME id
   486 				    | NONE =>  nodes ids gu ns
   487 	in case nodes [] guh (!mets) of
   488 	       SOME id => id
   489 	     | NONE => error ("guh2kestoreID: '" ^ guh ^ "' " ^
   490 				    "not found in (!mets)") end
   491       | _ => error ("guh2kestoreID called with '" ^ guh ^ "'");
   492 (*> guh2kestoreID "pbl_equ_univ_lin";
   493 val it = ["linear", "univariate", "equation"] : string list*)
   494 
   495    
   496 fun check_pblguh_unique (guh:guh) (pbls: (pbt ptyp) list) =
   497     if member op = (coll_pblguhs pbls) guh
   498     then error ("check_guh_unique failed with '"^guh^"';\n"^
   499 		      "use 'sort_pblguhs()' for a list of guhs;\n"^
   500 		      "consider setting 'check_guhs_unique := false'")
   501     else ();
   502 (* val (guh, mets) = ("met_test", !mets);
   503    *)
   504 fun check_metguh_unique (guh:guh) (mets: (met ptyp) list) =
   505     if member op = (coll_metguhs mets) guh
   506     then error ("check_guh_unique failed with '"^guh^"';\n"^
   507 		      "use 'sort_metguhs()' for a list of guhs;\n"^
   508 		      "consider setting 'check_guhs_unique := false'")
   509     else ();
   510 
   511 
   512 
   513 (*.the pblID has the leaf-element as first; better readability achieved;.*)
   514 fun store_pbt (pbt as {guh,...}, pblID) = 
   515     (if (!check_guhs_unique) then check_pblguh_unique guh (!ptyps) else ();
   516      ptyps:= insrt pblID pbt (rev pblID) (!ptyps));
   517 
   518 (*.the metID has the root-element as first; compare 'fun store_pbt'.*)
   519 fun store_met (met as {guh,...}, metID) =
   520     (if (!check_guhs_unique) then check_metguh_unique guh (!mets) else ();
   521      mets:= insrt metID met metID (!mets));
   522 
   523 
   524 (*. prepare problem-types before storing in pbltypes; 
   525     dont forget to 'check_guh_unique' before ins.*)
   526 fun prep_pbt thy guh maa init
   527 	     (pblID, dsc_dats: (string * (string list)) list, 
   528 		  ev:rls, ca: string option, metIDs:metID list) =
   529 (* val (thy, (pblID, dsc_dats: (string * (string list)) list, 
   530 		  ev:rls, ca: string option, metIDs:metID list)) =
   531        ((EqSystem.thy, (["system"],
   532 		       [("#Given" ,["equalities es_", "solveForVars vs_"]),
   533 			("#Find"  ,["solution ss___"](*___ is copy-named*))
   534 			],
   535 		       append_rls "e_rls" e_rls [(*for preds in where_*)], 
   536 		       SOME "solveSystem es_ vs_", 
   537 		       [])));
   538    *)
   539     let fun eq f (f', _) = f = f';
   540 	val gi = filter (eq "#Given") dsc_dats;
   541 (*val gi = [("#Given",["equality e_","solveFor v_"])]
   542   : (string * string list) list*)
   543 	val gi = (case gi of
   544 		     [] => []
   545 		   | ((_,gi')::[]) => 
   546 		     ((map (split_did o term_of o the o (parse thy)) gi')
   547 		     handle _ => error 
   548 			("prep_pbt: syntax error in '#Given' of "^
   549 			 (strs2str pblID)))
   550 		   | _ =>
   551 		     (error ("prep_pbt: more than one '#Given' in "^
   552 				  (strs2str pblID))));
   553 (*val gi =
   554   [(Const ("Descript.equality","bool => Tools.una"),Free ("e_","bool")),
   555    (Const ("Descript.solveFor","RealDef.real => Tools.una"),
   556     Free ("v_","RealDef.real"))] : (term * term) list  *)
   557 	val gi = map (pair "#Given") gi;
   558 (*val gi =
   559   [("#Given",
   560     (Const ("Descript.equality","bool => Tools.una"),Free ("e_","bool"))),
   561    ("#Given",
   562     (Const ("Descript.solveFor","RealDef.real => Tools.una"),
   563      Free ("v_","RealDef.real")))] : (string * (term * term)) list*)
   564 
   565 	val fi = filter (eq "#Find") dsc_dats;
   566 	val fi = (case fi of
   567 		     [] => [](*28.8.01: ["tool"] ...// error 
   568 			("prep_pbt: no '#Find' in "^(strs2str pblID))*)
   569 (* val ((_,fi')::[]) = fi;
   570    *)
   571 		   | ((_,fi')::[]) => 
   572 		     ((map (split_did o term_of o the o (parse thy)) fi')
   573 		     handle _ => error 
   574 			("prep_pbt: syntax error in '#Find' of "^
   575 			 (strs2str pblID)))
   576 		   | _ =>
   577 		     (error ("prep_pbt: more than one '#Find' in "^
   578 				  (strs2str pblID))));
   579 	val fi = map (pair "#Find") fi;
   580 
   581 	val re = filter (eq "#Relate") dsc_dats;
   582 	val re = (case re of
   583 		     [] => []
   584 		   | ((_,re')::[]) => 
   585 		     ((map (split_did o term_of o the o (parse thy)) re')
   586 		     handle _ => error 
   587 			("prep_pbt: syntax error in '#Relate' of "^
   588 			 (strs2str pblID)))
   589 		   | _ =>
   590 		     (error ("prep_pbt: more than one '#Relate' in "^
   591 				  (strs2str pblID))));
   592 	val re = map (pair "#Relate") re;
   593 
   594 	val wh = filter (eq "#Where") dsc_dats;
   595 	val wh = (case wh of
   596 		     [] => []
   597 		   | ((_,wh')::[]) => 
   598 		     ((map (parse_patt thy) wh')
   599 		      handle _ => error 
   600 			("prep_pbt: syntax error in '#Where' of "^
   601 			 (strs2str pblID)))
   602 		   | _ =>
   603 		     (error ("prep_pbt: more than one '#Where' in "^
   604 				  (strs2str pblID))));
   605     in ({guh=guh,mathauthors=maa,init=init,
   606 	 thy=thy,cas= case ca of NONE => NONE
   607 			       | SOME s => 
   608 				 SOME ((term_of o the o (parse thy)) s),
   609 	 prls=ev,where_=wh,ppc= gi @ fi @ re,
   610 	 met=metIDs}, pblID):pbt * pblID end;
   611 (* prep_pbt thy (pblID, dsc_dats, metIDs);   
   612  val it =
   613   ({met=[],
   614     ppc=[("#Given",(Const (#,#),Free (#,#))),
   615          ("#Given",(Const (#,#),Free (#,#))),
   616          ("#Find",(Const (#,#),Free (#,#)))],
   617     thy={ProtoPure, ..., Atools, RatArith},
   618     where_=[Const ("Descript.solutions","bool List.list => Tools.toreall") $
   619             Free ("v_i_","bool List.list")]},["equation"]) : pbt * pblID    *)
   620 
   621 
   622 
   623 
   624 (*. prepare met for storage analogous to pbt .*)
   625 fun prep_met thy guh maa init
   626 	     (metID, ppc: (string * string list) list (*'#Where' -> #pre*),
   627     {rew_ord'=ro, rls'=rls, srls=srls, prls=prls, 
   628      calc = scr_isa_fns(*FIXME.040207: del - auto-done*),
   629      crls=cr, errpats = ep, nrls= nr}, scr) =
   630     let fun eq f (f', _) = f = f';
   631 	(*val thy = (assoc_thy o fst) metID*)
   632 	val gi = filter (eq "#Given") ppc;
   633 	val gi = (case gi of
   634 		     [] => (writeln ("prep_met: in " ^ guh ^ " #Given is empty ?!?"); [])
   635 		   | ((_,gi')::[]) => 
   636 		     ((map (split_did o term_of o the o (parse thy)) gi')
   637 		     handle _ => error 
   638 			("prep_pbt: syntax error in '#Given' of "^
   639 			 (strs2str metID)))
   640 		   | _ =>
   641 		     (error ("prep_pbt: more than one '#Given' in "^
   642 				  (strs2str metID))));
   643 	val gi = map (pair "#Given") gi;
   644 
   645 	val fi = filter (eq "#Find") ppc;
   646 	val fi = (case fi of
   647 		     [] => (writeln ("prep_met: in " ^ guh ^ " #Find is empty ?!?"); [])
   648 		   | ((_,fi')::[]) => 
   649 		     ((map (split_did o term_of o the o (parse thy)) fi')
   650 		     handle _ => error 
   651 			("prep_pbt: syntax error in '#Find' of "^
   652 			 (strs2str metID)))
   653 		   | _ =>
   654 		     (error ("prep_pbt: more than one '#Find' in "^
   655 				  (strs2str metID))));
   656 	val fi = map (pair "#Find") fi;
   657 
   658 	val re = filter (eq "#Relate") ppc;
   659 	val re = (case re of
   660 		     [] => (writeln ("prep_met: in " ^ guh ^ " #Relate is empty ?!?"); [])
   661 		   | ((_,re')::[]) => 
   662 		     ((map (split_did o term_of o the o (parse thy)) re')
   663 		     handle _ => error 
   664 			("prep_pbt: syntax error in '#Relate' of "^
   665 			 (strs2str metID)))
   666 		   | _ =>
   667 		     (error ("prep_pbt: more than one '#Relate' in "^
   668 				  (strs2str metID))));
   669 	val re = map (pair "#Relate") re;
   670 
   671 	val wh = filter (eq "#Where") ppc;
   672 	val wh = (case wh of
   673 		     [] => (writeln ("prep_met: in " ^ guh ^ " #Where is empty ?!?"); [])
   674 		   | ((_,wh')::[]) => 
   675 		     ((map (parse_patt thy) wh')
   676 		     handle _ => error 
   677 			("prep_pbt: syntax error in '#Where' of "^
   678 			 (strs2str metID)))
   679 		   | _ =>
   680 		     (error ("prep_pbt: more than one '#Where' in "^
   681 				  (strs2str metID))));
   682 	val sc = (((inst_abs thy) o term_of o the o (parse thy)) scr)
   683     in ({guh=guh,mathauthors=maa,init=init,
   684 	 ppc=gi@fi@re, pre=wh, rew_ord'=ro, erls=rls, srls=srls, prls=prls,
   685 	 calc = if scr = "empty_script" then []
   686 		else ((assoc_calc' thy |> map) o (map op_of_calc) o 
   687 		      (filter is_calc) o stacpbls) sc, 
   688 	 crls=cr, errpats = ep, nrls= nr, scr = Prog sc}:met,
   689 	metID:metID)
   690     end;
   691 
   692 
   693 (**. get pblIDs of all entries in mat3D .**)
   694 
   695 
   696 fun format_pblID strl = enclose " [" "]" (commas_quote strl);
   697 fun format_pblIDl strll = enclose "[\n" "\n]\n" 
   698     (space_implode ",\n" (map format_pblID strll));
   699 
   700 fun scan _  [] = [] (* no base case, for empty doms only *)
   701   | scan id ((Ptyp ((i,_,[])))::[]) =      [id@[i]]
   702   | scan id ((Ptyp ((i,_,pl)))::[]) = scan (id@[i]) pl
   703   | scan id ((Ptyp ((i,_,[])))::ps) =      [id@[i]]    @(scan id ps)
   704   | scan id ((Ptyp ((i,_,pl)))::ps) =(scan (id@[i]) pl)@(scan id ps);
   705 
   706 fun show_ptyps () = (writeln o format_pblIDl o (scan [])) (!ptyps);
   707 (* ptyps:=[];
   708    show_ptyps();
   709    *)
   710 fun show_mets () = (writeln o format_pblIDl o (scan [])) (!mets);
   711 
   712 
   713 
   714 (*vvvvv---------- preparational work 8.01. UNUSED *)
   715 (**+ instantiate a problem-type +**)
   716 
   717 (*+ transform oris +*)
   718 
   719 fun coll_vats (vats, ((_,vs,_,_,_):ori)) = union op = vats vs;
   720 (*> coll_vats [11,22] (hd oris);
   721 val it = [22,11,1,2,3] : int list
   722 
   723 > foldl coll_vats ([],oris);
   724 val it = [1,2,3] : int list
   725 
   726 > val i=1;
   727 > filter ((curry (op mem) i) o #2) oris;
   728 val it =
   729   [(1,[1,2,3],"#Given",Const (#,#),[# $ #]),
   730    (2,[1,2,3],"#Find",Const (#,#),[Free #]),
   731    (3,[1,2,3],"#Find",Const (#,#),[# $ #,# $ #]),
   732    (4,[1,2],"#Relate",Const (#,#),[# $ #,# $ #]),
   733    (6,[1],"#undef",Const (#,#),[Free #]),
   734    (9,[1,2],"#undef",Const (#,#),[# $ #]),
   735    (11,[1,2,3],"#undef",Const (#,#),[# $ #])] : ori list *)    
   736 
   737 local infix mem; (*from Isabelle2002*)
   738 fun x mem [] = false
   739   | x mem (y :: ys) = x = y orelse x mem ys;
   740 in
   741 fun filter_vat oris i = 
   742     filter ((curry (op mem) i) o (#2 : ori -> int list)) oris;
   743 end;
   744 (*> map (filter_vat oris) [1,2,3];
   745 val it =
   746   [[(1,[1,2,3],"#Given",Const (#,#),[# $ #]),
   747     (2,[1,2,3],"#Find",Const (#,#),[Free #]),
   748     (3,[1,2,3],"#Find",Const (#,#),[# $ #,# $ #]),
   749     (4,[1,2],"#Relate",Const (#,#),[# $ #,# $ #]),
   750     (6,[1],"#undef",Const (#,#),[Free #]),
   751     (9,[1,2],"#undef",Const (#,#),[# $ #]),
   752     (11,[1,2,3],"#undef",Const (#,#),[# $ #])],
   753    [(1,[1,2,3],"#Given",Const (#,#),[# $ #]),
   754     (2,[1,2,3],"#Find",Const (#,#),[Free #]),
   755     (3,[1,2,3],"#Find",Const (#,#),[# $ #,# $ #]),
   756     (4,[1,2],"#Relate",Const (#,#),[# $ #,# $ #]),
   757     (7,[2],"#undef",Const (#,#),[Free #]),
   758     (9,[1,2],"#undef",Const (#,#),[# $ #]),
   759     (11,[1,2,3],"#undef",Const (#,#),[# $ #])],
   760    [(1,[1,2,3],"#Given",Const (#,#),[# $ #]),
   761     (2,[1,2,3],"#Find",Const (#,#),[Free #]),
   762     (3,[1,2,3],"#Find",Const (#,#),[# $ #,# $ #]),
   763     (5,[3],"#Relate",Const (#,#),[# $ #,# $ #,# $ #]),
   764     (8,[3],"#undef",Const (#,#),[Free #]),
   765     (10,[3],"#undef",Const (#,#),[# $ #]),
   766     (11,[1,2,3],"#undef",Const (#,#),[# $ #])]] : ori list list*)
   767 
   768 fun separate_vats oris =
   769     let val vats = foldl coll_vats ([] : int list, oris);
   770     in map (filter_vat oris) vats end;
   771 (*^^^ end preparational work 8.01.*)
   772 
   773 
   774 
   775 (**. check a problem (ie. itm list) for matching a problemtype .**)
   776 
   777 fun eq1 d (_,(d',_)) = (d = d');
   778 fun itm_id ((i,_,_,_,_):itm) = i;
   779 fun ori_id ((i,_,_,_,_):ori) = i;
   780 fun ori2itmSup ((i,v,_,d,ts):ori) = ((i,v,true,"#Given",Sup(d,ts)):itm);
   781 (*see + add_sel_ppc                             ~~~~~~~*)
   782 fun field_eq f ((_,_,f',_,_):ori) = f = f';
   783 
   784 (*. check an item (with arbitrary itm_ from previous matchings) 
   785     for matching a problemtype; returns true only for itms found in pbt .*)
   786 fun chk_ thy pbt ((i,vats,b,f,Cor ((d,vs),_)):itm) =
   787     (case find_first (eq1 d) pbt of 
   788 	 SOME (_,(_,id)) => ((i,vats,b,f,Cor ((d,vs),
   789 					      (id, pbl_ids' d vs))):itm)
   790        | NONE => (i,vats,false,f,Sup (d,vs)))
   791   | chk_ thy pbt ((i,vats,b,f,Inc ((d,vs),_)):itm) =
   792     (case find_first (eq1 d) pbt of 
   793 	SOME (_,(_,id)) => ((i,vats,b,f,Cor ((d,vs),
   794 					     (id, pbl_ids' d vs))):itm)
   795       | NONE => (i,vats,false,f,Sup (d,vs)))
   796 
   797   | chk_ thy pbt (itm as (i,vats,b,f,Syn ct):itm) = itm
   798   | chk_ thy pbt (itm as (i,vats,b,f,Typ ct):itm) = itm
   799 
   800   | chk_ thy pbt ((i,vats,b,f,Sup (d,vs)):itm) =
   801     (case find_first (eq1 d) pbt of 
   802 	SOME (_,(_,id)) => ((i,vats,b,f,Cor ((d,vs),
   803 					     (id, pbl_ids' d vs))):itm)
   804       | NONE => (i,vats,false,f,Sup (d,vs)))
   805 (* val (i,vats,b,f,Mis (d,vs)) = i4;
   806    *)
   807   | chk_ thy pbt ((i,vats,b,f,Mis (d,vs)):itm) =
   808     (case find_first (eq1 d) pbt of
   809 (* val SOME (_,(_,id)) = find_first (eq1 d) pbt;
   810    *) 
   811 	SOME (_,(_,id)) => error "chk_: ((i,vats,b,f,Cor ((d,vs),\
   812 				   \(id, pbl_ids' d vs))):itm)"
   813       | NONE => (i,vats,false,f,Sup (d,[vs])));
   814 
   815 (* chk_ thy pbt i
   816     *)
   817 
   818 fun eq2 (_,(d,_)) ((_,_,_,_,itm_):itm) = d = d_in itm_;
   819 fun eq2' (_,(d,_)) ((_,_,_,d',_):ori) = d = d';
   820 fun eq0 ((0,_,_,_,_):itm) = true
   821   | eq0 _ = false;
   822 fun max_i i [] = i
   823   | max_i i ((id,_,_,_,_)::is) = 
   824     if i > id then max_i i is else max_i id is;
   825 fun max_id [] = 0
   826   | max_id ((id,_,_,_,_)::is) = max_i id is;
   827 fun add_idvat itms _ _ [] = itms
   828   | add_idvat itms i mvat (((_,_,b,f,itm_):itm)::its) =
   829     add_idvat (itms @ [(i,[(*mvat ...meaningless with pbl-identifier *)
   830 			     ],b,f,itm_):itm]) (i+1) mvat its;
   831 
   832 
   833 (*. find elements of pbt not contained in itms;
   834     if such one is untouched, return this one, otherwise create new itm .*)
   835 fun chk_m (itms:itm list) untouched (p as (f,(d,id))) = 
   836     case find_first (eq2 p) itms of
   837 	SOME _ => []
   838       | NONE => (case find_first (eq2 p) untouched of
   839 		     SOME itm => [itm]
   840 		   | NONE => [(0,[],false,f,Mis (d,id)):itm]);
   841 (* val itms = itms'';
   842    *) 
   843 fun chk_mis mvat itms untouched pbt = 
   844     let val mis = (flat o (map (chk_m itms untouched))) pbt; 
   845         val mid = max_id itms;
   846     in add_idvat [] (mid + 1) mvat mis end;
   847 
   848 (*. check a problem (ie. itm list) for matching a problemtype, 
   849     takes the max_vt for concluding completeness (could be another!) .*)
   850 (* val itms = itms'; val (pbt,pre) = (ppc, pre);
   851    val itms = itms; val (pbt,pre) = (ppc, pre);
   852    *)
   853 fun match_itms thy itms (pbt,pre,prls) = 
   854     (let fun okv mvat (_,vats,b,_,_) = member op = vats mvat
   855 				       andalso b;
   856 	val itms' = map (chk_ thy pbt) itms; (*all found are #3 true*)
   857         val mvat = max_vt itms';
   858 	val itms'' = filter (okv mvat) itms';
   859 	val untouched = filter eq0 itms;(*i.e. dsc only (from init)*)
   860 	val mis = chk_mis mvat itms'' untouched pbt;
   861 	val pre' = check_preconds' prls pre itms'' mvat
   862 	val pb = foldl and_ (true, map fst pre')
   863     in (length mis = 0 andalso pb, (itms'@ mis, pre')) end);
   864 
   865 (*. check a problem pbl (ie. itm list) for matching a problemtype pbt,
   866     for missing items get data from formalization (ie. ori list); 
   867     takes the max_vt for concluding completeness (could be another!) .*)
   868 (*  (0) determine the most frequent variant mv in pbl
   869     ALL pbt. (1) dsc(pbt) notmem dsc(pbls) =>
   870              (2) filter (dsc(pbt) = dsc(oris)) oris; -> news;
   871              (3) newitms = filter (mv mem vat(news)) news 
   872     (4) pbt @ newitms                                           *)
   873 (* val (pbl, pbt, pre) = (met, mtt, pre);
   874    val (pbl, pbt, pre) = (itms, #ppc pbt, #where_ pbt);
   875    val (pbl, pbt, pre) = (itms, ppc, where_);
   876    *)
   877 fun match_itms_oris thy (pbl:itm list) (pbt, pre, prls) oris =
   878   let 
   879  (*0*)val mv = max_vt pbl;
   880 
   881       fun eqdsc_pbt_itm ((_,(d,_))) ((_,_,_,_,itm_):itm) = d = d_in itm_;
   882       fun notmem pbl pbt1 = case find_first (eqdsc_pbt_itm pbt1) pbl of
   883 				SOME _ => false | NONE => true;
   884  (*1*)val mis = (*(map (cons2 (fst, fst o snd)))o*) (filter (notmem pbl)) pbt;
   885 
   886       fun eqdsc_ori (_,(d,_)) ((_,_,_,d',_):ori) = d = d';
   887       fun ori2itmMis (f,(d,pid)) ((i,v,_,_,ts):ori) = 
   888 	  (i,v,false,f,Mis (d,pid)):itm;
   889  (*2*)fun oris2itms oris mis1 = 
   890 	  ((map (ori2itmMis mis1)) o (filter (eqdsc_ori mis1))) oris;
   891       val news = (flat o (map (oris2itms oris))) mis;
   892  (*3*)fun mem_vat (_,vats,b,_,_) = member op = vats mv;
   893       val newitms = filter mem_vat news;
   894  (*4*)val itms' = pbl @ newitms;
   895       val pre' = check_preconds' prls pre itms' mv
   896       val pb = foldl and_ (true, map fst pre')
   897   in (length mis = 0 andalso pb, (itms', pre')) end;
   898     (*handle _ => (false,([],[]))*);
   899 
   900 
   901 (*vvv--- doubled 20.9.01: ... 7.3.02 itms  -->  oris, because oris
   902   allow for faster access to descriptions and terms *)
   903 (**. check a problem (ie. itm list) for matching a problemtype .**)
   904 
   905 (*. check an ori for matching a problemtype by description; 
   906     returns true only for itms found in pbt .*)
   907 fun chk1_ thy pbt ((i,vats,f,d,vs):ori) =
   908     case find_first (eq1 d) pbt of 
   909 	SOME (_,(_,id)) => [(i,vats,true,f,
   910 			     Cor ((d,vs), (id, pbl_ids' d vs))):itm]
   911       | NONE => [];
   912 
   913 (* elem 'p' of pbt contained in itms ? *)
   914 fun chk1_m (itms:itm list) p = 
   915     case find_first (eq2 p) itms of
   916 	SOME _ => true | NONE => false;
   917 fun chk1_m' (oris: ori list) (p as (f,(d,t))) = 
   918     case find_first (eq2' p) oris of
   919 	SOME _ => []
   920       | NONE => [(f, Mis (d, t))];
   921 fun pair0vatsfalse (f,itm_) = (0,[],false,f,itm_):itm;
   922 
   923 fun chk1_mis mvat itms ppc = foldl and_ (true, map (chk1_m itms) ppc);
   924 fun chk1_mis' oris ppc = 
   925     map pair0vatsfalse ((flat o (map (chk1_m' oris))) ppc);
   926 
   927   
   928 (*. check a problem (ie. ori list) for matching a problemtype, 
   929     takes the max_vt for concluding completeness (FIXME could be another!) .*)
   930 (* val (prls,oris,pbt,pre)=(#prls py, ori, #ppc py, #where_ py);
   931    *)
   932 fun match_oris thy prls oris (pbt,pre) = 
   933     let val itms = (flat o (map (chk1_ thy pbt))) oris;
   934         val mvat = max_vt itms;
   935 	val complete = chk1_mis mvat itms pbt;
   936 	val pre' = check_preconds' prls pre itms mvat
   937 	val pb = foldl and_ (true, map fst pre')
   938     in if complete andalso pb then true else false end;
   939 
   940 (*. check a problem (ie. ori list) for matching a problemtype, 
   941     returns items for output to math-experts .*)
   942 fun match_oris' thy oris (ppc,pre,prls) =
   943 (* val (thy, oris, (ppc,pre,prls)) = (thy, oris, (ppc, where_, prls));
   944    *)
   945     let val itms = (flat o (map (chk1_ thy ppc))) oris;
   946 	val sups = ((map ori2itmSup) o (filter(field_eq "#undef")))oris;
   947         val mvat = max_vt itms;
   948 	val miss = chk1_mis' oris ppc;
   949 	val pre' = check_preconds' prls pre itms mvat
   950 	val pb = foldl and_ (true, map fst pre')
   951     in (miss = [] andalso pb, (itms @ miss @ sups, pre')) end;
   952 
   953 (* for the user *)
   954 datatype match' = 
   955   Matches' of item ppc
   956 | NoMatch' of item ppc;
   957 
   958 (* match a formalization with a problem type *)
   959 fun match_pbl (fmz:fmz_) ({thy=thy,where_=pre,ppc,prls=er,...}:pbt) =
   960     let val oris = prep_ori fmz thy ppc |> #1;
   961 	val (bool, (itms, pre')) = match_oris' thy oris (ppc,pre,er);
   962     in if bool then Matches' (itms2itemppc thy itms pre')
   963        else NoMatch' (itms2itemppc thy itms pre') end;
   964 (* 
   965 val fmz = ["equality (sqrt(9+4*x)=sqrt x + sqrt(5+x))",
   966 	      "solveFor x","errorBound (eps=0)","solutions L"];
   967 val pbt as {thy = thy, where_ = pre, ppc = ppc,...} =
   968     get_pbt ["univariate","equation"];
   969 match_pbl fmz pbt;
   970 *)
   971 
   972 
   973 (*. refine a problem; construct pblRD while scanning .*)
   974 (* val (pblRD,ori)=("xxx",oris);
   975  val py = get_pbt ["equation"];
   976  val py = get_pbt ["univariate","equation"];
   977  val py = get_pbt ["linear","univariate","equation"];
   978  val py = get_pbt ["root'","univariate","equation"];
   979  match_oris (#prls py) ori (#ppc py, #where_ py);
   980 
   981   *)
   982 fun refin (pblRD:pblRD) ori 
   983 ((Ptyp (pI,[py],[])):pbt ptyp) =
   984     if match_oris (#thy py) (#prls py) ori (#ppc py, #where_ py) 
   985     then SOME ((pblRD @ [pI]):pblRD)
   986     else NONE
   987   | refin pblRD ori (Ptyp (pI,[py],pys)) =
   988     if match_oris (#thy py) (#prls py) ori (#ppc py, #where_ py) 
   989     then (case refins (pblRD @ [pI]) ori pys of
   990 	      SOME pblRD' => SOME pblRD'
   991 	    | NONE => SOME (pblRD @ [pI]))
   992     else NONE
   993 and refins pblRD ori [] = NONE
   994   | refins pblRD ori ((p as Ptyp (pI,_,_))::pts) =
   995     (case refin pblRD ori p of
   996 	 SOME pblRD' => SOME pblRD'
   997        | NONE => refins pblRD ori pts);
   998 
   999 (*. refine a problem; version providing output for math-experts .*)
  1000 fun refin' (pblRD: pblRD) fmz pbls ((Ptyp (pI, [py], [])):pbt ptyp) =
  1001     let
  1002       val _ = (tracing o ((curry op ^)"*** pass ") o strs2str) (pblRD @ [pI])
  1003       val {thy, ppc, where_, prls, ...} = py 
  1004       val oris = prep_ori fmz thy ppc |> #1;
  1005       (*8.3.02: itms!: oris ev. are _not_ complete here*)
  1006       val (b, (itms, pre')) = match_oris' thy oris (ppc, where_, prls)
  1007     in if b
  1008       then pbls @ [Matches (rev (pblRD @ [pI]), itms2itemppc thy itms pre')]
  1009       else pbls @ [NoMatch (rev (pblRD @ [pI]), itms2itemppc thy itms pre')]
  1010     end
  1011 
  1012   | refin' pblRD fmz pbls (Ptyp (pI, [py], pys)) =
  1013     let
  1014       val _ = (tracing o ((curry op ^)"*** pass ") o strs2str) (pblRD @ [pI])
  1015       val {thy, ppc, where_, prls, ...} = py 
  1016       val oris = prep_ori fmz thy ppc |> #1;
  1017       (*8.3.02: itms!: oris ev. are _not_ complete here*)
  1018       val(b, (itms, pre')) = match_oris' thy oris (ppc,where_,prls);
  1019     in if b 
  1020       then let val pbl = Matches (rev (pblRD @ [pI]), itms2itemppc thy itms pre')
  1021 	      in refins' (pblRD @ [pI]) fmz (pbls @ [pbl]) pys end
  1022       else (pbls @ [NoMatch (rev (pblRD @ [pI]), itms2itemppc thy itms pre')])
  1023     end
  1024 
  1025 and refins' pblRD fmz pbls [] = pbls
  1026   | refins' pblRD fmz pbls ((p as Ptyp (pI, _, _))::pts) =
  1027     let val pbls' = refin' pblRD fmz pbls p
  1028     in case last_elem pbls' of
  1029         Matches _ => pbls'
  1030       | NoMatch _ => refins' pblRD fmz pbls' pts
  1031     end;
  1032 
  1033 (*. refine a problem; version for tactic Refine_Problem .*)
  1034 fun refin'' thy (pblRD:pblRD) itms pbls ((Ptyp (pI,[py],[])):pbt ptyp) =
  1035     let (*val _ = tracing("### refin''1: pI="^pI);*)
  1036 	val {thy,ppc,where_,prls,...} = py 
  1037 	val (b, (itms', pre')) = match_itms thy itms (ppc,where_,prls);
  1038     in if b then pbls @ [Match_ (rev (pblRD @ [pI]), (itms', pre'))]
  1039        else pbls @ [NoMatch_] 
  1040     end
  1041 (* val pblRD = (rev o tl) pblID; val pbls = []; 
  1042    val Ptyp (pI,[py],pys) = app_ptyp I pblID (rev pblID) (!ptyps);
  1043    *)
  1044   | refin'' thy pblRD itms pbls (Ptyp (pI,[py],pys)) =
  1045     let (*val _ = tracing("### refin''2: pI="^pI);*)
  1046 	val {thy,ppc,where_,prls,...} = py 
  1047 	val(b, (itms', pre')) = match_itms thy itms (ppc,where_,prls);
  1048     in if b 
  1049        then let val pbl = Match_ (rev (pblRD @ [pI]), (itms', pre'))
  1050 	    in refins'' thy (pblRD @ [pI]) itms (pbls @ [pbl]) pys end
  1051        else (pbls @ [NoMatch_])
  1052     end
  1053 and refins'' thy pblRD itms pbls [] = pbls
  1054   | refins'' thy pblRD itms pbls ((p as Ptyp (pI,_,_))::pts) =
  1055     let val pbls' = refin'' thy pblRD itms pbls p
  1056     in case last_elem pbls' of
  1057 	 Match_ _ => pbls'
  1058        | NoMatch_ => refins'' thy pblRD itms pbls' pts end;
  1059 
  1060 
  1061 (*. apply a fun to a ptyps node; copied from get_py .*)
  1062 fun app_ptyp f (d:pblID) _ [] = 
  1063     error ("app_ptyp not found: "^(strs2str d))
  1064   | app_ptyp f d (k::[]) ((p as Ptyp (k',[py],_))::pys) =
  1065     if k=k' then f p
  1066     else app_ptyp f d ([k]:pblRD) pys
  1067   | app_ptyp f d (k::ks) ((Ptyp (k',_,pys))::pys') =
  1068     if k=k' then app_ptyp f d ks pys
  1069     else app_ptyp f d (k::ks) pys';
  1070 
  1071 (*. for tactic Refine_Tacitly .*)
  1072 (*!!! oris are already created wrt. some pbt; pbt contains thy for parsing*)
  1073 (* val (thy,pblID) = (assoc_thy dI',pI);
  1074    *)
  1075 fun refine_ori oris (pblID:pblID) =
  1076     let val opt = app_ptyp (refin ((rev o tl) pblID) oris) 
  1077 			   pblID (rev pblID) (!ptyps);
  1078     in case opt of 
  1079 	   SOME pblRD => let val (pblID':pblID) =(rev pblRD)
  1080 			 in if pblID' = pblID then NONE
  1081 			    else SOME pblID' end
  1082 	 | NONE => NONE end;
  1083 fun refine_ori' oris pI = (the (refine_ori oris pI)) handle _ => pI;
  1084 
  1085 (*. for tactic Refine_Problem .*); 
  1086 (* 10.03: returnvalue -> (pIrefined, itm list) would be sufficient *)
  1087 (* val pblID = pI; app_ptyp I pblID (rev pblID) (!ptyps);
  1088    *)
  1089 fun refine_pbl thy (pblID:pblID) itms =
  1090     case refined_ (app_ptyp (refin'' thy ((rev o tl) pblID) itms []) 
  1091 			    pblID (rev pblID) (!ptyps)) of
  1092 	NONE => NONE
  1093       | SOME (Match_ (rfd as (pI',_))) => 
  1094 	if pblID = pI' then NONE else SOME rfd;
  1095 
  1096 
  1097 (*. for math-experts .*)
  1098 (*FIXME.WN021019: needs thy for parsing fmz*)
  1099 (* val fmz = fmz1; val pblID = ["pbla"]; val pblRD = (rev o tl) pblID; 
  1100    val pbls = []; val ptys = !ptyps;
  1101    *)
  1102 fun refine (fmz:fmz_) (pblID:pblID) =
  1103   app_ptyp (refin' ((rev o tl) pblID) fmz []) pblID (rev pblID) (!ptyps);
  1104 
  1105 
  1106 (*.make a guh from a reference to an element in the kestore;
  1107    EXCEPT theory hierarchy ... compare 'fun keref2xml'.*)
  1108 fun pblID2guh (pblID:pblID) =
  1109     (((#guh o get_pbt) pblID)
  1110      handle _ => error ("pblID2guh: not for '"^strs2str' pblID ^ "'"));
  1111 fun metID2guh (metID:metID) =
  1112     (((#guh o get_met) metID)
  1113      handle _ => error ("metID2guh: no 'Met_' for '"^
  1114 			      strs2str' metID ^ "'"));
  1115 fun kestoreID2guh Pbl_ (kestoreID:kestoreID) = pblID2guh kestoreID
  1116   | kestoreID2guh Met_ (kestoreID:kestoreID) = metID2guh kestoreID
  1117   | kestoreID2guh ketype kestoreID =
  1118     error ("kestoreID2guh: '" ^ ketype2str ketype ^ "' not for '" ^
  1119 		 strs2str' kestoreID ^ "'");
  1120 
  1121 fun show_pblguhs () =
  1122     (print_depth 999; 
  1123      (tracing o strs2str o (map linefeed)) (coll_pblguhs (!ptyps)); 
  1124      print_depth 3);
  1125 fun sort_pblguhs () =
  1126     (print_depth 999; 
  1127      (tracing o strs2str o (map linefeed)) 
  1128 	 (((sort string_ord) o coll_pblguhs) (!ptyps)); 
  1129      print_depth 3);
  1130 
  1131 fun show_metguhs () =
  1132     (print_depth 999; 
  1133      (tracing o strs2str o (map linefeed)) (coll_metguhs (!mets)); 
  1134      print_depth 3);
  1135 fun sort_metguhs () =
  1136     (print_depth 999; 
  1137      (tracing o strs2str o (map linefeed)) 
  1138 	 (((sort string_ord) o coll_metguhs) (!mets)); 
  1139      print_depth 3);