Move towards standard functions.
authorskalberg
Thu, 03 Mar 2005 12:43:01 +0100
changeset 15570 8d8c70b41bab
parent 15569 1b3115d1a8df
child 15571 c166086feace
Move towards standard functions.
NEWS
TFL/casesplit.ML
TFL/post.ML
TFL/rules.ML
TFL/tfl.ML
TFL/thry.ML
src/CCL/CCL.ML
src/CCL/typecheck.ML
src/CTT/CTT.ML
src/FOL/IFOL_lemmas.ML
src/FOL/eqrule_FOL_data.ML
src/FOL/intprover.ML
src/FOL/simpdata.ML
src/FOLP/IFOLP.ML
src/FOLP/classical.ML
src/FOLP/intprover.ML
src/FOLP/simp.ML
src/FOLP/simpdata.ML
src/HOL/Algebra/ringsimp.ML
src/HOL/Bali/Basis.thy
src/HOL/HOL.thy
src/HOL/Import/hol4rews.ML
src/HOL/Import/import_syntax.ML
src/HOL/Import/proof_kernel.ML
src/HOL/Import/replay.ML
src/HOL/Import/shuffler.ML
src/HOL/Integ/cooper_dec.ML
src/HOL/Integ/presburger.ML
src/HOL/IsaMakefile
src/HOL/Lambda/WeakNorm.thy
src/HOL/Library/EfficientNat.thy
src/HOL/List.thy
src/HOL/Matrix/Cplex.ML
src/HOL/Matrix/CplexMatrixConverter.ML
src/HOL/Matrix/codegen_prep.ML
src/HOL/Matrix/eq_codegen.ML
src/HOL/Matrix/fspmlp.ML
src/HOL/MicroJava/BV/BVExample.thy
src/HOL/Modelcheck/EindhovenSyn.ML
src/HOL/Modelcheck/MuckeSyn.ML
src/HOL/Modelcheck/mucke_oracle.ML
src/HOL/Product_Type.thy
src/HOL/Prolog/HOHH.ML
src/HOL/Tools/Presburger/cooper_dec.ML
src/HOL/Tools/Presburger/presburger.ML
src/HOL/Tools/datatype_abs_proofs.ML
src/HOL/Tools/datatype_aux.ML
src/HOL/Tools/datatype_codegen.ML
src/HOL/Tools/datatype_package.ML
src/HOL/Tools/datatype_prop.ML
src/HOL/Tools/datatype_realizer.ML
src/HOL/Tools/datatype_rep_proofs.ML
src/HOL/Tools/inductive_codegen.ML
src/HOL/Tools/inductive_package.ML
src/HOL/Tools/inductive_realizer.ML
src/HOL/Tools/meson.ML
src/HOL/Tools/primrec_package.ML
src/HOL/Tools/prop_logic.ML
src/HOL/Tools/recdef_package.ML
src/HOL/Tools/recfun_codegen.ML
src/HOL/Tools/record_package.ML
src/HOL/Tools/refute.ML
src/HOL/Tools/refute_isar.ML
src/HOL/Tools/rewrite_hol_proof.ML
src/HOL/Tools/sat_solver.ML
src/HOL/Tools/specification_package.ML
src/HOL/Tools/split_rule.ML
src/HOL/Tools/typedef_package.ML
src/HOL/arith_data.ML
src/HOL/cladata.ML
src/HOL/eqrule_HOL_data.ML
src/HOL/ex/svc_funcs.ML
src/HOL/hologic.ML
src/HOL/simpdata.ML
src/HOL/thy_syntax.ML
src/HOLCF/IOA/Modelcheck/MuIOAOracle.ML
src/HOLCF/IOA/meta_theory/Sequence.ML
src/HOLCF/adm.ML
src/HOLCF/cont_consts.ML
src/HOLCF/domain/axioms.ML
src/HOLCF/domain/extender.ML
src/HOLCF/domain/interface.ML
src/HOLCF/domain/library.ML
src/HOLCF/domain/syntax.ML
src/HOLCF/domain/theorems.ML
src/Provers/Arith/abel_cancel.ML
src/Provers/Arith/cancel_numeral_factor.ML
src/Provers/Arith/cancel_numerals.ML
src/Provers/Arith/combine_numerals.ML
src/Provers/Arith/extract_common_term.ML
src/Provers/Arith/fast_lin_arith.ML
src/Provers/blast.ML
src/Provers/clasimp.ML
src/Provers/classical.ML
src/Provers/ind.ML
src/Provers/induct_method.ML
src/Provers/make_elim.ML
src/Provers/order.ML
src/Provers/quasi.ML
src/Provers/simp.ML
src/Provers/splitter.ML
src/Provers/trancl.ML
src/Provers/typedsimp.ML
src/Pure/General/file.ML
src/Pure/General/graph.ML
src/Pure/General/history.ML
src/Pure/General/lazy_seq.ML
src/Pure/General/name_space.ML
src/Pure/General/path.ML
src/Pure/General/pretty.ML
src/Pure/General/scan.ML
src/Pure/General/seq.ML
src/Pure/General/symbol.ML
src/Pure/General/table.ML
src/Pure/General/xml.ML
src/Pure/IsaPlanner/isand.ML
src/Pure/IsaPlanner/isaplib.ML
src/Pure/IsaPlanner/rw_inst.ML
src/Pure/IsaPlanner/rw_tools.ML
src/Pure/IsaPlanner/term_lib.ML
src/Pure/Isar/args.ML
src/Pure/Isar/attrib.ML
src/Pure/Isar/calculation.ML
src/Pure/Isar/constdefs.ML
src/Pure/Isar/context_rules.ML
src/Pure/Isar/induct_attrib.ML
src/Pure/Isar/isar_output.ML
src/Pure/Isar/isar_syn.ML
src/Pure/Isar/isar_thy.ML
src/Pure/Isar/locale.ML
src/Pure/Isar/method.ML
src/Pure/Isar/net_rules.ML
src/Pure/Isar/object_logic.ML
src/Pure/Isar/obtain.ML
src/Pure/Isar/outer_parse.ML
src/Pure/Isar/outer_syntax.ML
src/Pure/Isar/proof.ML
src/Pure/Isar/proof_context.ML
src/Pure/Isar/rule_cases.ML
src/Pure/Isar/session.ML
src/Pure/Isar/toplevel.ML
src/Pure/Proof/extraction.ML
src/Pure/Proof/proof_rewrite_rules.ML
src/Pure/Proof/proof_syntax.ML
src/Pure/Proof/proofchecker.ML
src/Pure/Proof/reconstruct.ML
src/Pure/Syntax/ast.ML
src/Pure/Syntax/lexicon.ML
src/Pure/Syntax/mixfix.ML
src/Pure/Syntax/parser.ML
src/Pure/Syntax/printer.ML
src/Pure/Syntax/syn_ext.ML
src/Pure/Syntax/syn_trans.ML
src/Pure/Syntax/syntax.ML
src/Pure/Thy/present.ML
src/Pure/Thy/thm_deps.ML
src/Pure/Thy/thy_info.ML
src/Pure/Thy/thy_load.ML
src/Pure/Thy/thy_parse.ML
src/Pure/Thy/thy_scan.ML
src/Pure/axclass.ML
src/Pure/codegen.ML
src/Pure/display.ML
src/Pure/drule.ML
src/Pure/envir.ML
src/Pure/fact_index.ML
src/Pure/goals.ML
src/Pure/library.ML
src/Pure/meta_simplifier.ML
src/Pure/net.ML
src/Pure/pattern.ML
src/Pure/proof_general.ML
src/Pure/proofterm.ML
src/Pure/pure_thy.ML
src/Pure/search.ML
src/Pure/sign.ML
src/Pure/sorts.ML
src/Pure/tactic.ML
src/Pure/tctical.ML
src/Pure/term.ML
src/Pure/theory.ML
src/Pure/thm.ML
src/Pure/type.ML
src/Pure/type_infer.ML
src/Pure/unify.ML
src/ZF/Datatype.ML
src/ZF/Tools/cartprod.ML
src/ZF/Tools/datatype_package.ML
src/ZF/Tools/induct_tacs.ML
src/ZF/Tools/inductive_package.ML
src/ZF/Tools/primrec_package.ML
src/ZF/Tools/typechk.ML
src/ZF/arith_data.ML
src/ZF/ind_syntax.ML
src/ZF/simpdata.ML
src/ZF/thy_syntax.ML
--- a/NEWS	Thu Mar 03 09:22:35 2005 +0100
+++ b/NEWS	Thu Mar 03 12:43:01 2005 +0100
@@ -10,6 +10,37 @@
   Library.OPTION: Isabelle now uses the standard option type.  The
   functions the, is_some, is_none, etc. are still in Library, but
   the constructors are now SOME and NONE instead of Some and None.
+  They throw the exception Option.
+
+* The exception LIST is no more, the standard exceptions Empty and
+  Subscript, as well as Library.UnequalLengths are used instead.  This
+  means that function like Library.hd and Library.tl are gone, as the
+  standard hd and tl functions suffice.
+
+  A number of functions, specifically those in the LIBRARY_CLOSED
+  signature, are now no longer exported to the top ML level, as they
+  are variants of standard functions.  The following suggests how
+  one can translate existing code:
+
+    the x = valOf x
+    if_none x y = getOpt(x,y)
+    is_some x = isSome x
+    apsome f x = Option.map f x
+    rev_append xs ys = List.revAppend(xs,ys)
+    nth_elem(i,xs) = List.nth(xs,i)
+    last_elem xs = List.last xs
+    flat xss = List.concat xss
+    seq fs = app fs
+    partition P xs = List.partition P xs
+    filter P xs = List.filter P xs
+    mapfilter f xs = List.mapPartial f xs
+
+  The final four functions, take, drop, foldl, and foldr, are somewhat
+  more complicated (especially the semantics of take and drop differ
+  from the standard).
+
+  A simple solution to broken code is to include "open Library" at the
+  beginning of a structure.  Everything after that will be as before.
 
 * Document preparation: new antiquotations @{lhs thm} and @{rhs thm}
   printing the lhs/rhs of definitions, equations, inequations etc. 
--- a/TFL/casesplit.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/TFL/casesplit.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -207,7 +207,7 @@
           let val (n,ty) = Term.dest_Free x in 
             (if vstr = n orelse vstr = Syntax.dest_skolem n 
              then SOME (n,ty) else NONE )
-            handle LIST _ => NONE
+            handle Fail _ => NONE (* dest_skolem *)
           end;
       val (n,ty) = case Library.get_first getter freets 
                 of SOME (n, ty) => (n, ty)
@@ -311,7 +311,7 @@
               raise ERROR_MESSAGE "splitto: cannot find variable to split on")
             | SOME v => 
              let 
-               val gt = Data.dest_Trueprop (nth_elem(0, Thm.prems_of th));
+               val gt = Data.dest_Trueprop (List.nth(Thm.prems_of th, 0));
                val split_thm = mk_casesplit_goal_thm sgn v gt;
                val (subthms, expf) = IsaND.fixed_subgoal_thms split_thm;
              in 
@@ -340,7 +340,7 @@
    the well-foundness conditions have been solved. *)
 local
   fun get_related_thms i = 
-      mapfilter ((fn (r,x) => if x = i then SOME r else NONE));
+      List.mapPartial ((fn (r,x) => if x = i then SOME r else NONE));
       
   fun solve_eq (th, [], i) = 
       raise ERROR_MESSAGE "derive_init_eqs: missing rules"
--- a/TFL/post.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/TFL/post.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -46,7 +46,7 @@
  *--------------------------------------------------------------------------*)
 fun termination_goals rules =
     map (#1 o Type.freeze_thaw o HOLogic.dest_Trueprop)
-      (foldr (fn (th,A) => union_term (prems_of th, A)) (rules, []));
+      (Library.foldr (fn (th,A) => union_term (prems_of th, A)) (rules, []));
 
 (*---------------------------------------------------------------------------
  * Finds the termination conditions in (highly massaged) definition and
@@ -105,7 +105,7 @@
   |   _ => r RS P_imp_P_eq_True
 
 (*Is this the best way to invoke the simplifier??*)
-fun rewrite L = rewrite_rule (map mk_meta_eq (filter(not o id_thm) L))
+fun rewrite L = rewrite_rule (map mk_meta_eq (List.filter(not o id_thm) L))
 
 fun join_assums th =
   let val {sign,...} = rep_thm th
@@ -207,7 +207,7 @@
 -- Lucas Dixon, Aug 2004 *)
 local
   fun get_related_thms i = 
-      mapfilter ((fn (r,x) => if x = i then SOME r else NONE));
+      List.mapPartial ((fn (r,x) => if x = i then SOME r else NONE));
 
   fun solve_eq (th, [], i) = 
       raise ERROR_MESSAGE "derive_init_eqs: missing rules"
@@ -226,9 +226,9 @@
       val eqths = map (Thm.trivial o (Thm.cterm_of sgn) o HOLogic.mk_Trueprop) 
                       eqs
       fun countlist l = 
-          (rev o snd o (foldl (fn ((i,L), e) => (i + 1,(e,i) :: L)))) ((0,[]), l)
+          (rev o snd o (Library.foldl (fn ((i,L), e) => (i + 1,(e,i) :: L)))) ((0,[]), l)
     in
-      flat (map (fn (e,i) => solve_eq (e, (get_related_thms i rules), i))
+      List.concat (map (fn (e,i) => solve_eq (e, (get_related_thms i rules), i))
                 (countlist eqths))
     end;
 end;
--- a/TFL/rules.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/TFL/rules.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -133,7 +133,7 @@
 
 fun FILTER_DISCH_ALL P thm =
  let fun check tm = P (#t (Thm.rep_cterm tm))
- in  foldr (fn (tm,th) => if check tm then DISCH tm th else th)
+ in  Library.foldr (fn (tm,th) => if check tm then DISCH tm th else th)
               (chyps thm, thm)
  end;
 
@@ -658,7 +658,7 @@
   in (ants,get_lhs eq)
   end;
 
-fun restricted t = is_some (S.find_term
+fun restricted t = isSome (S.find_term
                             (fn (Const("Wellfounded_Recursion.cut",_)) =>true | _ => false)
                             t)
 
@@ -785,7 +785,7 @@
               val dummy = print_cterms "TC:"
                               [cterm_of sign (HOLogic.mk_Trueprop TC)]
               val dummy = tc_list := (TC :: !tc_list)
-              val nestedp = is_some (S.find_term is_func TC)
+              val nestedp = isSome (S.find_term is_func TC)
               val dummy = if nestedp then say "nested" else say "not_nested"
               val dummy = term_ref := ([func,TC]@(!term_ref))
               val th' = if nestedp then raise RULES_ERR "solver" "nested function"
@@ -808,7 +808,7 @@
       (prover names) (empty_ss addsimps [cut_lemma'] addeqcongs congs) ctm
     val th2 = equal_elim th1 th
  in
- (th2, filter (not o restricted) (!tc_list))
+ (th2, List.filter (not o restricted) (!tc_list))
  end;
 
 
--- a/TFL/tfl.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/TFL/tfl.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -201,8 +201,8 @@
 fun mk_pat (c,l) =
   let val L = length (binder_types (type_of c))
       fun build (prfx,tag,plist) =
-          let val args   = take (L,plist)
-              and plist' = drop(L,plist)
+          let val args   = Library.take (L,plist)
+              and plist' = Library.drop(L,plist)
           in (prfx,tag,list_comb(c,args)::plist') end
   in map build l end;
 
@@ -336,7 +336,7 @@
      val dummy = map (no_repeat_vars thy) pats
      val rows = ListPair.zip (map (fn x => ([]:term list,[x])) pats,
                               map (fn (t,i) => (t,(i,true))) (enumerate R))
-     val names = foldr add_term_names (R,[])
+     val names = Library.foldr add_term_names (R,[])
      val atype = type_of(hd pats)
      and aname = variant names "a"
      val a = Free(aname,atype)
@@ -433,13 +433,13 @@
 end;
 
 
-fun givens pats = map pat_of (filter given pats);
+fun givens pats = map pat_of (List.filter given pats);
 
 fun post_definition meta_tflCongs (theory, (def, pats)) =
  let val tych = Thry.typecheck theory
      val f = #lhs(S.dest_eq(concl def))
      val corollary = R.MATCH_MP Thms.WFREC_COROLLARY def
-     val pats' = filter given pats
+     val pats' = List.filter given pats
      val given_pats = map pat_of pats'
      val rows = map row_of_pat pats'
      val WFR = #ant(S.dest_imp(concl corollary))
@@ -499,7 +499,7 @@
      val tych = Thry.typecheck thy
      val WFREC_THM0 = R.ISPEC (tych functional) Thms.WFREC_COROLLARY
      val Const("All",_) $ Abs(Rname,Rtype,_) = concl WFREC_THM0
-     val R = Free (variant (foldr add_term_names (eqns,[])) Rname,
+     val R = Free (variant (Library.foldr add_term_names (eqns,[])) Rname,
                    Rtype)
      val WFREC_THM = R.ISPECL [tych R, tych g] WFREC_THM0
      val ([proto_def, WFR],_) = S.strip_imp(concl WFREC_THM)
@@ -540,7 +540,7 @@
                        prths extractants;
                        ())
                  else ()
-     val TCs = foldr (gen_union (op aconv)) (TCl, [])
+     val TCs = Library.foldr (gen_union (op aconv)) (TCl, [])
      val full_rqt = WFR::TCs
      val R' = S.mk_select{Bvar=R1, Body=S.list_mk_conj full_rqt}
      val R'abs = S.rand R'
@@ -622,7 +622,7 @@
   let val (qvars,body) = S.strip_exists tm
       val vlist = #2(S.strip_comb (S.rhs body))
       val plist = ListPair.zip (vlist, xlist)
-      val args = map (fn qv => the (gen_assoc (op aconv) (plist, qv))) qvars
+      val args = map (fn qv => valOf (gen_assoc (op aconv) (plist, qv))) qvars
                    handle Option => sys_error
                        "TFL fault [alpha_ex_unroll]: no correspondence"
       fun build ex      []   = []
@@ -682,7 +682,7 @@
                                                rows = map (expnd c) rows})
                            (U.zip3 new_formals groups constraints)
             val recursive_thms = map mk news
-            val build_exists = foldr
+            val build_exists = Library.foldr
                                 (fn((x,t), th) =>
                                  R.CHOOSE (tych x, R.ASSUME (tych t)) th)
             val thms' = ListPair.map build_exists (vexl, recursive_thms)
@@ -698,7 +698,7 @@
  let val tych = Thry.typecheck thy
      val ty_info = Thry.induct_info thy
  in fn pats =>
- let val names = foldr add_term_names (pats,[])
+ let val names = Library.foldr add_term_names (pats,[])
      val T = type_of (hd pats)
      val aname = Term.variant names "a"
      val vname = Term.variant (aname::names) "v"
@@ -733,7 +733,7 @@
 in
 fun build_ih f P (pat,TCs) =
  let val globals = S.free_vars_lr pat
-     fun nested tm = is_some (S.find_term (curry (op aconv) f) tm)
+     fun nested tm = isSome (S.find_term (curry (op aconv) f) tm)
      fun dest_TC tm =
          let val (cntxt,R_y_pat) = S.strip_imp(#2(S.strip_forall tm))
              val (R,y,_) = S.dest_relation R_y_pat
@@ -762,7 +762,7 @@
 fun build_ih f (P,SV) (pat,TCs) =
  let val pat_vars = S.free_vars_lr pat
      val globals = pat_vars@SV
-     fun nested tm = is_some (S.find_term (curry (op aconv) f) tm)
+     fun nested tm = isSome (S.find_term (curry (op aconv) f) tm)
      fun dest_TC tm =
          let val (cntxt,R_y_pat) = S.strip_imp(#2(S.strip_forall tm))
              val (R,y,_) = S.dest_relation R_y_pat
@@ -795,7 +795,7 @@
  let val tych = Thry.typecheck thy
      val antc = tych(#ant(S.dest_imp tm))
      val thm' = R.SPEC_ALL thm
-     fun nested tm = is_some (S.find_term (curry (op aconv) f) tm)
+     fun nested tm = isSome (S.find_term (curry (op aconv) f) tm)
      fun get_cntxt TC = tych(#ant(S.dest_imp(#2(S.strip_forall(concl TC)))))
      fun mk_ih ((TC,locals),th2,nested) =
          R.GENL (map tych locals)
@@ -832,7 +832,7 @@
         let val ex_tm = S.mk_exists{Bvar=v,Body=tm}
         in (ex_tm, R.CHOOSE(tych v, R.ASSUME (tych ex_tm)) thm)
         end
-      val [veq] = filter (can S.dest_eq) (#1 (R.dest_thm thm))
+      val [veq] = List.filter (can S.dest_eq) (#1 (R.dest_thm thm))
       val {lhs,rhs} = S.dest_eq veq
       val L = S.free_vars_lr rhs
   in  #2 (U.itlist CHOOSER L (veq,thm))  end;
@@ -851,7 +851,7 @@
     val (pats,TCsl) = ListPair.unzip pat_TCs_list
     val case_thm = complete_cases thy pats
     val domain = (type_of o hd) pats
-    val Pname = Term.variant (foldr (foldr add_term_names)
+    val Pname = Term.variant (Library.foldr (Library.foldr add_term_names)
                               (pats::TCsl, [])) "P"
     val P = Free(Pname, domain --> HOLogic.boolT)
     val Sinduct = R.SPEC (tych P) Sinduction
@@ -862,7 +862,7 @@
     val cases = map (fn pat => betapply (Sinduct_assumf, pat)) pats
     val tasks = U.zip3 cases TCl' (R.CONJUNCTS Rinduct_assum)
     val proved_cases = map (prove_case fconst thy) tasks
-    val v = Free (variant (foldr add_term_names (map concl proved_cases, []))
+    val v = Free (variant (Library.foldr add_term_names (map concl proved_cases, []))
                     "v",
                   domain)
     val vtyped = tych v
--- a/TFL/thry.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/TFL/thry.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -66,12 +66,12 @@
         NONE => NONE
       | SOME {nchotomy, ...} =>
           SOME {nchotomy = nchotomy,
-                constructors = the (DatatypePackage.constrs_of thy tname)};
+                constructors = valOf (DatatypePackage.constrs_of thy tname)};
 
 fun extract_info thy =
  let val infos = map snd (Symtab.dest (DatatypePackage.get_datatypes thy))
  in {case_congs = map (mk_meta_eq o #case_cong) infos,
-     case_rewrites = flat (map (map mk_meta_eq o #case_rewrites) infos)}
+     case_rewrites = List.concat (map (map mk_meta_eq o #case_rewrites) infos)}
  end;
 
 
--- a/src/CCL/CCL.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/CCL/CCL.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -59,7 +59,7 @@
 
 fun mk_inj_rl thy rews s = 
       let fun mk_inj_lemmas r = ([arg_cong] RL [(r RS (r RS eq_lemma))]);
-          val inj_lemmas = flat (map mk_inj_lemmas rews);
+          val inj_lemmas = List.concat (map mk_inj_lemmas rews);
           val tac = REPEAT (ares_tac [iffI,allI,conjI] 1 ORELSE
                             eresolve_tac inj_lemmas 1 ORELSE
                             asm_simp_tac (CCL_ss addsimps rews) 1)
@@ -99,7 +99,7 @@
   fun mk_lemma (ra,rb) = [lemma] RL [ra RS (rb RS eq_lemma)] RL 
                            [distinctness RS notE,sym RS (distinctness RS notE)];
 in
-  fun mk_lemmas rls = flat (map mk_lemma (mk_combs pair rls));
+  fun mk_lemmas rls = List.concat (map mk_lemma (mk_combs pair rls));
   fun mk_dstnct_rls thy xs = mk_combs (mk_thm_str thy) xs;
 end;
 
@@ -117,7 +117,7 @@
                                (fn _ => [simp_tac (CCL_ss addsimps (rls@inj_rls)) 1])
           in map (mk_dstnct_thm ccl_dstncts) (mk_dstnct_rls thy xs) end;
 
-fun mkall_dstnct_thms thy defs i_rls xss = flat (map (mk_dstnct_thms thy defs i_rls) xss);
+fun mkall_dstnct_thms thy defs i_rls xss = List.concat (map (mk_dstnct_thms thy defs i_rls) xss);
 
 (*** Rewriting and Proving ***)
 
--- a/src/CCL/typecheck.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/CCL/typecheck.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -85,12 +85,12 @@
 
 fun IHinst tac rls = SUBGOAL (fn (Bi,i) =>
   let val bvs = bvars Bi [];
-      val ihs = filter could_IH (Logic.strip_assums_hyp Bi);
+      val ihs = List.filter could_IH (Logic.strip_assums_hyp Bi);
       val rnames = map (fn x=>
                     let val (a,b) = get_bno [] 0 x
-                    in (nth_elem(a,bvs),b) end) ihs;
+                    in (List.nth(bvs,a),b) end) ihs;
       fun try_IHs [] = no_tac
-        | try_IHs ((x,y)::xs) = tac [("g",x)] (nth_elem(y-1,rls)) i ORELSE (try_IHs xs);
+        | try_IHs ((x,y)::xs) = tac [("g",x)] (List.nth(rls,y-1)) i ORELSE (try_IHs xs);
   in try_IHs rnames end);
 
 (*****)
--- a/src/CTT/CTT.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/CTT/CTT.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -157,7 +157,7 @@
 
 (*0 subgoals vs 1 or more*)
 val (safe0_brls, safep_brls) =
-    partition (apl(0,op=) o subgoals_of_brl) safe_brls;
+    List.partition (apl(0,op=) o subgoals_of_brl) safe_brls;
 
 fun safestep_tac thms i =
     form_tac  ORELSE  
--- a/src/FOL/IFOL_lemmas.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/FOL/IFOL_lemmas.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -384,7 +384,7 @@
 (*special cases for free variables P, Q, R, S -- up to 3 arguments*)
 
 val pred_congs = 
-    flat (map (fn c => 
+    List.concat (map (fn c => 
                map (fn th => read_instantiate [("P",c)] th)
                    [pred1_cong,pred2_cong,pred3_cong])
                (explode"PQRS"));
--- a/src/FOL/eqrule_FOL_data.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/FOL/eqrule_FOL_data.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -37,14 +37,14 @@
              (case Term.head_of p of
                 Const(a,_) =>
                   (case Library.assoc(pairs,a) of
-                     SOME(rls) => flat (map atoms ([th] RL rls))
+                     SOME(rls) => List.concat (map atoms ([th] RL rls))
                    | NONE => [th])
               | _ => [th])
          | _ => [th])
   in atoms end;
 
 val prep_meta_eq = 
-    (mapfilter  
+    (List.mapPartial  
        mk_eq
        o (mk_atomize tranformation_pairs)
        o Drule.gen_all 
--- a/src/FOL/intprover.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/FOL/intprover.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -60,7 +60,7 @@
 
 (*0 subgoals vs 1 or more: the p in safep is for positive*)
 val (safe0_brls, safep_brls) =
-    partition (apl(0,op=) o subgoals_of_brl) safe_brls;
+    List.partition (apl(0,op=) o subgoals_of_brl) safe_brls;
 
 (*Attack subgoals using safe inferences -- matching, not resolution*)
 val safe_step_tac = FIRST' [eq_assume_tac,
--- a/src/FOL/simpdata.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/FOL/simpdata.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -116,7 +116,7 @@
              (case head_of p of
                 Const(a,_) =>
                   (case assoc(pairs,a) of
-                     SOME(rls) => flat (map atoms ([th] RL rls))
+                     SOME(rls) => List.concat (map atoms ([th] RL rls))
                    | NONE => [th])
               | _ => [th])
          | _ => [th])
--- a/src/FOLP/IFOLP.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/FOLP/IFOLP.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -78,7 +78,7 @@
           and concl = discard_proof (Logic.strip_assums_concl prem)
       in  
           if exists (fn hyp => hyp aconv concl) hyps
-          then case distinct (filter (fn hyp=> could_unify(hyp,concl)) hyps) of
+          then case distinct (List.filter (fn hyp=> could_unify(hyp,concl)) hyps) of
                    [_] => assume_tac i
                  |  _  => no_tac
           else no_tac
@@ -310,7 +310,7 @@
 (*special cases for free variables P, Q, R, S -- up to 3 arguments*)
 
 val pred_congs = 
-    flat (map (fn c => 
+    List.concat (map (fn c => 
                map (fn th => read_instantiate [("P",c)] th)
                    [pred1_cong,pred2_cong,pred3_cong])
                (explode"PQRS"));
--- a/src/FOLP/classical.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/FOLP/classical.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -112,7 +112,7 @@
 (*Note that allE precedes exI in haz_brls*)
 fun make_cs {safeIs,safeEs,hazIs,hazEs} =
   let val (safe0_brls, safep_brls) = (*0 subgoals vs 1 or more*)
-          partition (apl(0,op=) o subgoals_of_brl) 
+          List.partition (apl(0,op=) o subgoals_of_brl) 
              (sort (make_ord lessb) (joinrules(safeIs, safeEs)))
   in CS{safeIs=safeIs, safeEs=safeEs, hazIs=hazIs, hazEs=hazEs,
         safe0_brls=safe0_brls, safep_brls=safep_brls,
--- a/src/FOLP/intprover.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/FOLP/intprover.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -50,7 +50,7 @@
 
 (*0 subgoals vs 1 or more: the p in safep is for positive*)
 val (safe0_brls, safep_brls) =
-    partition (apl(0,op=) o subgoals_of_brl) safe_brls;
+    List.partition (apl(0,op=) o subgoals_of_brl) safe_brls;
 
 (*Attack subgoals using safe inferences*)
 val safe_step_tac = FIRST' [uniq_assume_tac,
--- a/src/FOLP/simp.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/FOLP/simp.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -84,7 +84,7 @@
           biresolve_tac (Net.unify_term net
                        (lhs_of (strip_assums_concl prem))) i);
 
-fun nth_subgoal i thm = nth_elem(i-1,prems_of thm);
+fun nth_subgoal i thm = List.nth(prems_of thm,i-1);
 
 fun goal_concl i thm = strip_assums_concl(nth_subgoal i thm);
 
@@ -161,7 +161,7 @@
                      in case f of
                             Const(c,T) => 
                                 if c mem ccs
-                                then foldr add_hvars (args,hvars)
+                                then Library.foldr add_hvars (args,hvars)
                                 else add_term_vars(tm,hvars)
                           | _ => add_term_vars(tm,hvars)
                      end
@@ -173,7 +173,7 @@
                 if at then vars else add_term_vars(tm,vars)
         fun add_list(tm,al,vars) = let val (_,tml) = strip_comb tm
                 in if length(tml)=length(al)
-                   then foldr itf (tml~~al,vars)
+                   then Library.foldr itf (tml~~al,vars)
                    else vars
                 end
         fun add_vars (tm,vars) = case tm of
@@ -194,12 +194,12 @@
     val lhs = rhs_of_eq 1 thm'
     val rhs = lhs_of_eq nops thm'
     val asms = tl(rev(tl(prems_of thm')))
-    val hvars = foldr (add_hidden_vars ccs) (lhs::rhs::asms,[])
+    val hvars = Library.foldr (add_hidden_vars ccs) (lhs::rhs::asms,[])
     val hvars = add_new_asm_vars new_asms (rhs,hvars)
     fun it_asms (asm,hvars) =
         if atomic asm then add_new_asm_vars new_asms (asm,hvars)
         else add_term_frees(asm,hvars)
-    val hvars = foldr it_asms (asms,hvars)
+    val hvars = Library.foldr it_asms (asms,hvars)
     val hvs = map (#1 o dest_Var) hvars
     val refl1_tac = refl_tac 1
     fun norm_step_tac st = st |>
@@ -216,7 +216,7 @@
 
 fun add_norm_tags congs =
     let val ccs = map cong_const congs
-        val new_asms = filter (exists not o #2)
+        val new_asms = List.filter (exists not o #2)
                 (ccs ~~ (map (map atomic o prems_of) congs));
     in add_norms(congs,ccs,new_asms) end;
 
@@ -252,7 +252,7 @@
     (writeln"\nDuplicate rewrite or congruence rule:"; print_thm th;
      net);
 
-val insert_thms = foldr insert_thm_warn;
+val insert_thms = Library.foldr insert_thm_warn;
 
 fun addrew(SS{auto_tac,congs,cong_net,mk_simps,simps,simp_net}, thm) =
 let val thms = mk_simps thm
@@ -260,7 +260,7 @@
       simps = (thm,thms)::simps, simp_net = insert_thms(thms,simp_net)}
 end;
 
-val op addrews = foldl addrew;
+val op addrews = Library.foldl addrew;
 
 fun op addcongs(SS{auto_tac,congs,cong_net,mk_simps,simps,simp_net}, thms) =
 let val congs' = thms @ congs;
@@ -278,10 +278,10 @@
     (writeln"\nNo such rewrite or congruence rule:";  print_thm th;
      net);
 
-val delete_thms = foldr delete_thm_warn;
+val delete_thms = Library.foldr delete_thm_warn;
 
 fun op delcongs(SS{auto_tac,congs,cong_net,mk_simps,simps,simp_net}, thms) =
-let val congs' = foldl (gen_rem Drule.eq_thm_prop) (congs,thms)
+let val congs' = Library.foldl (gen_rem Drule.eq_thm_prop) (congs,thms)
 in SS{auto_tac=auto_tac, congs= congs',
       cong_net= delete_thms(map mk_trans thms,cong_net),
       mk_simps= normed_rews congs', simps=simps, simp_net=simp_net}
@@ -298,7 +298,7 @@
       simps = simps', simp_net = delete_thms(thms,simp_net)}
 end;
 
-val op delrews = foldl delrew;
+val op delrews = Library.foldl delrew;
 
 
 fun op setauto(SS{congs,cong_net,mk_simps,simps,simp_net,...}, auto_tac) =
@@ -426,9 +426,9 @@
             SOME(thm',_) =>
                     let val ps = prems_of thm and ps' = prems_of thm';
                         val n = length(ps')-length(ps);
-                        val a = length(strip_assums_hyp(nth_elem(i-1,ps)))
+                        val a = length(strip_assums_hyp(List.nth(ps,i-1)))
                         val l = map (fn p => length(strip_assums_hyp(p)))
-                                    (take(n,drop(i-1,ps')));
+                                    (Library.take(n,Library.drop(i-1,ps')));
                     in (simp_refl(rev(l),a,REW::ss),thm',anet,ats,cs) end
           | NONE => (REW::ss,thm,anet,ats,cs);
 
@@ -437,9 +437,9 @@
 fun add_asms(ss,thm,a,anet,ats,cs) =
     let val As = strip_varify(nth_subgoal i thm, a, []);
         val thms = map (trivial o cterm_of(#sign(rep_thm(thm))))As;
-        val new_rws = flat(map mk_rew_rules thms);
-        val rwrls = map mk_trans (flat(map mk_rew_rules thms));
-        val anet' = foldr lhs_insert_thm (rwrls,anet)
+        val new_rws = List.concat(map mk_rew_rules thms);
+        val rwrls = map mk_trans (List.concat(map mk_rew_rules thms));
+        val anet' = Library.foldr lhs_insert_thm (rwrls,anet)
     in  if !tracing andalso not(null new_rws)
         then (writeln"Adding rewrites:";  prths new_rws;  ())
         else ();
@@ -539,7 +539,7 @@
 fun Pinst(f,fT,(eq,eqT),k,i,T,yik,Ts) =
 let fun xn_list(x,n) =
         let val ixs = map (fn i => (x^(radixstring(26,"a",i)),0)) (0 upto n);
-        in ListPair.map eta_Var (ixs, take(n+1,Ts)) end
+        in ListPair.map eta_Var (ixs, Library.take(n+1,Ts)) end
     val lhs = list_comb(f,xn_list("X",k-1))
     val rhs = list_comb(f,xn_list("X",i-1) @ [Bound 0] @ yik)
 in Abs("", T, Const(eq,[fT,fT]--->eqT) $ lhs $ rhs) end;
@@ -596,7 +596,7 @@
     val T' = incr_tvar 9 T;
 in mk_cong_type sg (Const(f,T'),T') end;
 
-fun mk_congs thy = flat o map (mk_cong_thy thy);
+fun mk_congs thy = List.concat o map (mk_cong_thy thy);
 
 fun mk_typed_congs thy =
 let val sg = sign_of thy;
@@ -606,7 +606,7 @@
             val t = case Sign.const_type sg f of
                       SOME(_) => Const(f,T) | NONE => Free(f,T)
         in (t,T) end
-in flat o map (mk_cong_type sg o readfT) end;
+in List.concat o map (mk_cong_type sg o readfT) end;
 
 end (* local *)
 end (* SIMP *);
--- a/src/FOLP/simpdata.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/FOLP/simpdata.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -85,7 +85,7 @@
              (case head_of p of
                 Const(a,_) =>
                   (case assoc(pairs,a) of
-                     SOME(rls) => flat (map atoms ([th] RL rls))
+                     SOME(rls) => List.concat (map atoms ([th] RL rls))
                    | NONE => [th])
               | _ => [th])
          | _ => [th])
--- a/src/HOL/Algebra/ringsimp.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/HOL/Algebra/ringsimp.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -74,17 +74,17 @@
       handle TERM _ => [];
 
     val prems = ProofContext.prems_of ctxt;
-    val rings = flat (map (ring_filter o #prop o rep_thm) prems);
-    val comms = flat (map (comm_filter o #prop o rep_thm) prems);
+    val rings = List.concat (map (ring_filter o #prop o rep_thm) prems);
+    val comms = List.concat (map (comm_filter o #prop o rep_thm) prems);
     val non_comm_rings = rings \\ comms;
     val comm_rings = rings inter_string comms;
     val _ = tracing
       ("Non-commutative rings in proof context: " ^ commas non_comm_rings ^
        "\nCommutative rings in proof context: " ^ commas comm_rings);
     val simps =
-      flat (map (fn s => ProofContext.get_thms ctxt (s ^ ".ring_simprules", NONE))
+      List.concat (map (fn s => ProofContext.get_thms ctxt (s ^ ".ring_simprules", NONE))
         non_comm_rings) @
-      flat (map (fn s => ProofContext.get_thms ctxt (s ^ ".cring_simprules", NONE))
+      List.concat (map (fn s => ProofContext.get_thms ctxt (s ^ ".cring_simprules", NONE))
         comm_rings);
   in Method.SIMPLE_METHOD' HEADGOAL (asm_full_simp_tac (cring_ss addsimps simps))
   end;
--- a/src/HOL/Bali/Basis.thy	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/HOL/Bali/Basis.thy	Thu Mar 03 12:43:01 2005 +0100
@@ -188,7 +188,7 @@
 (*###to be phased out *)
 ML {* 
 fun noAll_simpset () = simpset() setmksimps 
-	mksimps (filter (fn (x,_) => x<>"All") mksimps_pairs)
+	mksimps (List.filter (fn (x,_) => x<>"All") mksimps_pairs)
 *}
 
 lemma All_Ex_refl_eq2 [simp]: 
--- a/src/HOL/HOL.thy	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/HOL/HOL.thy	Thu Mar 03 12:43:01 2005 +0100
@@ -771,7 +771,7 @@
   fun wrong_prem (Const ("All", _) $ (Abs (_, _, t))) = wrong_prem t
   |   wrong_prem (Bound _) = true
   |   wrong_prem _ = false
-  val filter_right = filter (fn t => not (wrong_prem (HOLogic.dest_Trueprop (hd (Thm.prems_of t)))))
+  val filter_right = List.filter (fn t => not (wrong_prem (HOLogic.dest_Trueprop (hd (Thm.prems_of t)))))
 in
   fun smp i = funpow i (fn m => filter_right ([spec] RL m)) ([mp])
   fun smp_tac j = EVERY'[dresolve_tac (smp j), atac]
--- a/src/HOL/Import/hol4rews.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/HOL/Import/hol4rews.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -614,7 +614,7 @@
 	    then
 		let
 		    val paths = NameSpace.unpack isa
-		    val i = drop(length paths - 2,paths)
+		    val i = Library.drop(length paths - 2,paths)
 		in
 		    case i of
 			[seg,con] => output_thy ^ "." ^ seg ^ "." ^ con
--- a/src/HOL/Import/import_syntax.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/HOL/Import/import_syntax.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -49,7 +49,7 @@
 		val thyname = get_generating_thy thy
 		val segname = get_import_segment thy
 		val (int_thms,facts) = Replay.setup_int_thms thyname thy
-		val thmnames = filter (not o should_ignore thyname thy) facts
+		val thmnames = List.filter (not o should_ignore thyname thy) facts
 	    in
 		thy |> clear_import_thy
 		    |> set_segment thyname segname
@@ -68,7 +68,7 @@
 				      let
 					  val thyname = get_import_thy thy
 				      in
-					  foldl (fn (thy,thmname) => ignore_hol4 thyname thmname thy) (thy,ignored)
+					  Library.foldl (fn (thy,thmname) => ignore_hol4 thyname thmname thy) (thy,ignored)
 				      end)
 
 val thm_maps = Scan.repeat1 (P.name --| P.$$$ ">" -- P.xname)
@@ -77,7 +77,7 @@
 				   let
 				       val thyname = get_import_thy thy
 				   in
-				       foldl (fn (thy,(hol,isa)) => add_hol4_mapping thyname hol isa thy) (thy,thmmaps)
+				       Library.foldl (fn (thy,(hol,isa)) => add_hol4_mapping thyname hol isa thy) (thy,thmmaps)
 				   end)
 
 val type_maps = Scan.repeat1 (P.name --| P.$$$ ">" -- P.xname)
@@ -86,7 +86,7 @@
 				    let
 					val thyname = get_import_thy thy
 				    in
-					foldl (fn (thy,(hol,isa)) => add_hol4_type_mapping thyname hol false isa thy) (thy,typmaps)
+					Library.foldl (fn (thy,(hol,isa)) => add_hol4_type_mapping thyname hol false isa thy) (thy,typmaps)
 				    end)
 
 val def_maps = Scan.repeat1 (P.name --| P.$$$ ">" -- P.xname)
@@ -95,7 +95,7 @@
 				   let
 				       val thyname = get_import_thy thy
 				   in
-				       foldl (fn (thy,(hol,isa)) => add_defmap thyname hol isa thy) (thy,defmaps)
+				       Library.foldl (fn (thy,(hol,isa)) => add_defmap thyname hol isa thy) (thy,defmaps)
 				   end)
 
 val const_renames = Scan.repeat1 (P.name --| P.$$$ ">" -- P.name)
@@ -104,7 +104,7 @@
 					let
 					    val thyname = get_import_thy thy
 					in
-					    foldl (fn (thy,(hol,isa)) => add_hol4_const_renaming thyname hol isa thy) (thy,renames)
+					    Library.foldl (fn (thy,(hol,isa)) => add_hol4_const_renaming thyname hol isa thy) (thy,renames)
 					end)
 																      
 val const_maps = Scan.repeat1 (P.name --| P.$$$ ">" -- P.xname -- Scan.option (P.$$$ "::" |-- P.typ))
@@ -113,7 +113,7 @@
 				     let
 					 val thyname = get_import_thy thy
 				     in
-					 foldl (fn (thy,((hol,isa),NONE)) => add_hol4_const_mapping thyname hol false isa thy
+					 Library.foldl (fn (thy,((hol,isa),NONE)) => add_hol4_const_mapping thyname hol false isa thy
 						 | (thy,((hol,isa),SOME ty)) => add_hol4_const_wt_mapping thyname hol false isa (typ_of (read_ctyp (sign_of thy) ty)) thy) (thy,constmaps)
 				     end)
 
@@ -123,7 +123,7 @@
 				      let
 					  val thyname = get_import_thy thy
 				      in
-					  foldl (fn (thy,((hol,isa),NONE)) => add_hol4_const_mapping thyname hol true isa thy
+					  Library.foldl (fn (thy,((hol,isa),NONE)) => add_hol4_const_mapping thyname hol true isa thy
 						  | (thy,((hol,isa),SOME ty)) => add_hol4_const_wt_mapping thyname hol true isa (typ_of (read_ctyp (sign_of thy) ty)) thy) (thy,constmaps)
 				      end)
 
@@ -138,7 +138,7 @@
 			 Scan.empty_lexicon)
 	val get_lexes = fn () => !lexes
 	val token_source = OuterLex.source false get_lexes (Position.line 1) symb_source
-	val token_list = filter (not o (OuterLex.is_kind OuterLex.Space)) (Source.exhaust token_source)
+	val token_list = filter_out (OuterLex.is_kind OuterLex.Space) (Source.exhaust token_source)
 	val import_segmentP = OuterParse.$$$ "import_segment" |-- import_segment
 	val type_mapsP = OuterParse.$$$ "type_maps" |-- type_maps
 	val def_mapsP = OuterParse.$$$ "def_maps" |-- def_maps
--- a/src/HOL/Import/proof_kernel.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/HOL/Import/proof_kernel.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -580,7 +580,7 @@
 		 else find ps
 	     end) handle OS.SysErr _ => find ps
     in
-	apsome (fn p => OS.Path.joinDirFile {dir = p, file = thyname}) (find path)
+	Option.map (fn p => OS.Path.joinDirFile {dir = p, file = thyname}) (find path)
     end
 			   
 fun proof_file_name thyname thmname thy =
@@ -675,7 +675,7 @@
 		val (c,asl) = case terms of
 				  [] => raise ERR "x2p" "Bad oracle description"
 				| (hd::tl) => (hd,tl)
-		val tg = foldr (fn (oracle,tg) => Tag.merge (Tag.read oracle) tg) (ors,Tag.empty_tag)
+		val tg = Library.foldr (fn (oracle,tg) => Tag.merge (Tag.read oracle) tg) (ors,Tag.empty_tag)
 	    in
 		mk_proof (POracle(tg,map xml_to_term asl,xml_to_term c))
 	    end
@@ -916,7 +916,7 @@
     end
 
 fun implies_elim_all th =
-    foldl (fn (th,p) => implies_elim th (assume p)) (th,cprems_of th)
+    Library.foldl (fn (th,p) => implies_elim th (assume p)) (th,cprems_of th)
 
 fun norm_hyps th =
     th |> beta_eta_thm
@@ -1064,7 +1064,7 @@
 	  | process _ = raise ERR "disamb_helper" "Internal error"
 
 	val (vars',rens',inst) =
-	    foldr process (varstm,(vars,rens,[]))
+	    Library.foldr process (varstm,(vars,rens,[]))
     in
 	({vars=vars',rens=rens'},inst)
     end
@@ -1100,7 +1100,7 @@
     end
 
 fun disamb_terms_from info tms =
-    foldr (fn (tm,(info,tms)) =>
+    Library.foldr (fn (tm,(info,tms)) =>
 	      let
 		  val (info',tm') = disamb_term_from info tm
 	      in
@@ -1109,7 +1109,7 @@
 	  (tms,(info,[]))
 
 fun disamb_thms_from info hthms =
-    foldr (fn (hthm,(info,thms)) =>
+    Library.foldr (fn (hthm,(info,thms)) =>
 	      let
 		  val (info',tm') = disamb_thm_from info hthm
 	      in
@@ -1127,7 +1127,7 @@
     let
 	val vars = collect_vars (prop_of th)
 	val (rens',inst,_) =
-	    foldr (fn((ren as (vold as Free(vname,_),vnew)),
+	    Library.foldr (fn((ren as (vold as Free(vname,_),vnew)),
 		      (rens,inst,vars)) =>
 		     (case Library.find_first (fn Free(v,_) => v = vname | _ => false) vars of
 			  SOME v' => if v' = vold
@@ -1139,7 +1139,7 @@
 	val (dom,rng) = ListPair.unzip inst
 	val th' = mk_INST (map (cterm_of sg) dom) (map (cterm_of sg) rng) th
 	val nvars = collect_vars (prop_of th')
-	val rens' = filter (fn(_,v) => v mem nvars) rens
+	val rens' = List.filter (fn(_,v) => v mem nvars) rens
 	val res = HOLThm(rens',th')
     in
 	res
@@ -1167,7 +1167,7 @@
 	end
 
 fun non_trivial_term_consts tm =
-    filter (fn c => not (c = "Trueprop" orelse
+    List.filter (fn c => not (c = "Trueprop" orelse
 			 c = "All" orelse
 			 c = "op -->" orelse
 			 c = "op &" orelse
@@ -1239,7 +1239,7 @@
 		val th1 = (SOME (transform_error (PureThy.get_thm thy) (thmname, NONE))
 			   handle ERROR_MESSAGE _ =>
 				  (case split_name thmname of
-				       SOME (listname,idx) => (SOME (nth_elem(idx-1,PureThy.get_thms thy (listname, NONE)))
+				       SOME (listname,idx) => (SOME (List.nth(PureThy.get_thms thy (listname, NONE),idx-1))
 							       handle _ => NONE)
 				     | NONE => NONE))
 	    in
@@ -1794,7 +1794,7 @@
 		      | inst_type ty1 ty2 (ty as Type(name,tys)) =
 			Type(name,map (inst_type ty1 ty2) tys)
 		in
-		    foldr (fn (v,th) =>
+		    Library.foldr (fn (v,th) =>
 			      let
 				  val cdom = fst (dom_rng (fst (dom_rng cty)))
 				  val vty  = type_of v
@@ -1806,7 +1806,7 @@
 		end
 	      | SOME _ => raise ERR "GEN_ABS" "Bad constant"
 	      | NONE => 
-		foldr (fn (v,th) => mk_ABS v th sg) (vlist',th)
+		Library.foldr (fn (v,th) => mk_ABS v th sg) (vlist',th)
 	val res = HOLThm(rens_of info',th1)
 	val _ = message "RESULT:"
 	val _ = if_debug pth res
@@ -1876,7 +1876,7 @@
     let
 	val constname = rename_const thyname thy constname
         val sg = sign_of thy
-        val redeclared = is_some (Sign.const_type sg (Sign.intern_const sg constname));
+        val redeclared = isSome (Sign.const_type sg (Sign.intern_const sg constname));
 	val _ = warning ("Introducing constant " ^ constname)
 	val (thmname,thy) = get_defname thyname constname thy
 	val (info,rhs') = disamb_term rhs
@@ -1956,21 +1956,21 @@
 				 | dest_exists tm =
 				   raise ERR "new_specification" "Bad existential formula"
 					 
-			       val (consts,_) = foldl (fn ((cs,ex),cname) =>
+			       val (consts,_) = Library.foldl (fn ((cs,ex),cname) =>
 							  let
 							      val (_,cT,p) = dest_exists ex
 							  in
 							      ((cname,cT,mk_syn thy cname)::cs,p)
 							  end) (([],HOLogic.dest_Trueprop (concl_of th)),names)
 			       val sg = sign_of thy
-			       val str = foldl (fn (acc,(c,T,csyn)) =>
+			       val str = Library.foldl (fn (acc,(c,T,csyn)) =>
 						   acc ^ "\n  " ^ (quotename c) ^ " :: \"" ^ string_of_ctyp (ctyp_of sg T) ^ "\" " ^ (Syntax.string_of_mixfix csyn)) ("consts",consts)
 			       val thy' = add_dump str thy
 			   in
 			       Theory.add_consts_i consts thy'
 			   end
 
-	    val thy1 = foldr (fn(name,thy)=>
+	    val thy1 = Library.foldr (fn(name,thy)=>
 				snd (get_defname thyname name thy)) (names,thy1)
 	    fun new_name name = fst (get_defname thyname name thy1)
 	    val (thy',res) = SpecificationPackage.add_specification_i NONE
@@ -1989,7 +1989,7 @@
 		     then quotename name
 		     else (quotename newname) ^ ": " ^ (quotename name),thy')
 		end
-	    val (new_names,thy') = foldr (fn(name,(names,thy)) =>
+	    val (new_names,thy') = Library.foldr (fn(name,(names,thy)) =>
 					    let
 						val (name',thy') = handle_const (name,thy)
 					    in
--- a/src/HOL/Import/replay.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/HOL/Import/replay.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -25,7 +25,7 @@
 	    end
 	  | rp (PSubst(prfs,ctxt,prf)) thy =
 	    let
-		val (thy',ths) = foldr (fn (p,(thy,ths)) =>
+		val (thy',ths) = Library.foldr (fn (p,(thy,ths)) =>
 					   let
 					       val (thy',th) = rp' p thy
 					   in
@@ -319,7 +319,7 @@
 	    in
 		fst (replay_proof int_thms thyname thmname prf thy)
 	    end
-	val res_thy = foldl replay_fact (thy,thmnames)
+	val res_thy = Library.foldl replay_fact (thy,thmnames)
     in
 	res_thy
     end
--- a/src/HOL/Import/shuffler.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/HOL/Import/shuffler.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -42,17 +42,17 @@
   case e of
      THM (msg,i,thms) =>
 	 (writeln ("Exception THM " ^ string_of_int i ^ " raised:\n" ^ msg);
-	  seq print_thm thms)
+	  List.app print_thm thms)
    | THEORY (msg,thys) =>
 	 (writeln ("Exception THEORY raised:\n" ^ msg);
-	  seq (Pretty.writeln o Display.pretty_theory) thys)
+	  List.app (Pretty.writeln o Display.pretty_theory) thys)
    | TERM (msg,ts) =>
 	 (writeln ("Exception TERM raised:\n" ^ msg);
-	  seq (writeln o Sign.string_of_term sign) ts)
+	  List.app (writeln o Sign.string_of_term sign) ts)
    | TYPE (msg,Ts,ts) =>
 	 (writeln ("Exception TYPE raised:\n" ^ msg);
-	  seq (writeln o Sign.string_of_typ sign) Ts;
-	  seq (writeln o Sign.string_of_term sign) ts)
+	  List.app (writeln o Sign.string_of_typ sign) Ts;
+	  List.app (writeln o Sign.string_of_term sign) ts)
    | e => raise e
 
 (*Prints an exception, then fails*)
@@ -251,7 +251,7 @@
 	val tvars = term_tvars t
 	val tfree_names = add_term_tfree_names(t,[])
 	val (type_inst,_) =
-	    foldl (fn ((inst,used),(w as (v,_),S)) =>
+	    Library.foldl (fn ((inst,used),(w as (v,_),S)) =>
 		      let
 			  val v' = variant used v
 		      in
@@ -553,13 +553,13 @@
     end
     
 val collect_ignored =
-    foldr (fn (thm,cs) =>
+    Library.foldr (fn (thm,cs) =>
 	      let
 		  val (lhs,rhs) = Logic.dest_equals (prop_of thm)
 		  val ignore_lhs = term_consts lhs \\ term_consts rhs
 		  val ignore_rhs = term_consts rhs \\ term_consts lhs
 	      in
-		  foldr (op ins_string) (ignore_lhs @ ignore_rhs,cs)
+		  Library.foldr (op ins_string) (ignore_lhs @ ignore_rhs,cs)
 	      end)
 
 (* set_prop t thms tries to make a theorem with the proposition t from
@@ -570,7 +570,7 @@
     let
 	val sg = sign_of thy
 	val vars = add_term_frees (t,add_term_vars (t,[]))
-	val closed_t = foldr (fn (v,body) => let val vT = type_of v
+	val closed_t = Library.foldr (fn (v,body) => let val vT = type_of v
 					     in all vT $ (Abs("x",vT,abstract_over(v,body))) end) (vars,t)
 	val rew_th = norm_term thy closed_t
 	val rhs = snd (dest_equals (cprop_of rew_th))
@@ -614,13 +614,13 @@
 	val rel_consts = term_consts t \\ ignored
 	val pot_thms = PureThy.thms_containing_consts thy rel_consts
     in
-	filter (match_consts ignored t) pot_thms
+	List.filter (match_consts ignored t) pot_thms
     end
 
 fun gen_shuffle_tac thy search thms i st =
     let
 	val _ = message ("Shuffling " ^ (string_of_thm st))
-	val t = nth_elem(i-1,prems_of st)
+	val t = List.nth(prems_of st,i-1)
 	val set = set_prop thy t
 	fun process_tac thms st =
 	    case set thms of
--- a/src/HOL/Integ/cooper_dec.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/HOL/Integ/cooper_dec.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -442,7 +442,7 @@
    val ts = coeffs_of t
    in case ts of
      [] => raise DVD_UNKNOWN
-    |_  => foldr (fn(k,r) => r andalso (k mod dn = 0)) (ts,true)
+    |_  => Library.foldr (fn(k,r) => r andalso (k mod dn = 0)) (ts,true)
    end;
 
 
@@ -736,7 +736,7 @@
              in (rw,HOLogic.mk_disj(F',rf)) 
 	     end)
     val f = if b then linear_add else linear_sub
-    val p_elements = foldr (fn (i,l) => l union (map (fn e => f [] e (mk_numeral i)) st)) (1 upto d,[])
+    val p_elements = Library.foldr (fn (i,l) => l union (map (fn e => f [] e (mk_numeral i)) st)) (1 upto d,[])
     in h p_elements
     end;
 
@@ -873,7 +873,7 @@
 fun lift_qelim afn nfn qfn isat = 
  let   fun qelim x vars p = 
   let val cjs = conjuncts p 
-      val (ycjs,ncjs) = partition (has_bound) cjs in 
+      val (ycjs,ncjs) = List.partition (has_bound) cjs in 
       (if ycjs = [] then p else 
                           let val q = (qfn vars ((HOLogic.exists_const HOLogic.intT 
 			  ) $ Abs(x,HOLogic.intT,(list_conj ycjs)))) in 
--- a/src/HOL/Integ/presburger.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/HOL/Integ/presburger.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -148,21 +148,21 @@
       if body_type T mem [iT, nT] 
          andalso not (ts = []) andalso forall (null o loose_bnos) ts 
       then [fm]
-      else foldl op union ([], map getfuncs ts)
+      else Library.foldl op union ([], map getfuncs ts)
   | (Var (_, T), ts as _ :: _) =>
       if body_type T mem [iT, nT] 
          andalso not (ts = []) andalso forall (null o loose_bnos) ts then [fm]
-      else foldl op union ([], map getfuncs ts)
+      else Library.foldl op union ([], map getfuncs ts)
   | (Const (s, T), ts) =>
       if (s, T) mem allowed_consts orelse not (body_type T mem [iT, nT])
-      then foldl op union ([], map getfuncs ts)
+      then Library.foldl op union ([], map getfuncs ts)
       else [fm]
   | (Abs (s, T, t), _) => getfuncs t
   | _ => [];
 
 
 fun abstract_pres sg fm = 
-  foldr (fn (t, u) =>
+  Library.foldr (fn (t, u) =>
       let val T = fastype_of t
       in all T $ Abs ("x", T, abstract_over (t, u)) end)
          (getfuncs fm, fm);
@@ -198,7 +198,7 @@
  abstracted over.*)
  
 fun relevant ps t = (term_typed_consts t) subset allowed_consts andalso 
-  map (fn i => snd (nth_elem (i, ps))) (loose_bnos t) @
+  map (fn i => snd (List.nth (ps, i))) (loose_bnos t) @
   map (snd o dest_Free) (term_frees t) @ map (snd o dest_Var) (term_vars t)
   subset [iT, nT]
   andalso not (has_free_funcs t);
@@ -217,13 +217,13 @@
         (HOLogic.all_const T $ Abs (s, T, P), n)
       else (incr_boundvars ~1 P, n-1)
     fun mk_all2 (v, t) = HOLogic.all_const (fastype_of v) $ lambda v t;
-    val (rhs,irhs) = partition (relevant (rev ps)) hs
+    val (rhs,irhs) = List.partition (relevant (rev ps)) hs
     val np = length ps
-    val (fm',np) =  foldr (fn ((x, T), (fm,n)) => mk_all ((x, T), (fm,n)))
-      (ps,(foldr HOLogic.mk_imp (rhs, c), np))
-    val (vs, _) = partition (fn t => q orelse (type_of t) = nT)
+    val (fm',np) =  Library.foldr (fn ((x, T), (fm,n)) => mk_all ((x, T), (fm,n)))
+      (ps,(Library.foldr HOLogic.mk_imp (rhs, c), np))
+    val (vs, _) = List.partition (fn t => q orelse (type_of t) = nT)
       (term_frees fm' @ term_vars fm');
-    val fm2 = foldr mk_all2 (vs, fm')
+    val fm2 = Library.foldr mk_all2 (vs, fm')
   in (fm2, np + length vs, length rhs) end;
 
 (*Object quantifier to meta --*)
@@ -300,7 +300,7 @@
  in
    Method.simple_args 
   (Scan.optional (Args.$$$ "(" |-- Scan.repeat1 parse_flag --| Args.$$$ ")") [] >>
-    curry (foldl op |>) (true, false))
+    curry (Library.foldl op |>) (true, false))
     (fn (q,a) => fn _ => meth q a 1)
   end;
 
--- a/src/HOL/IsaMakefile	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/HOL/IsaMakefile	Thu Mar 03 12:43:01 2005 +0100
@@ -77,6 +77,7 @@
   $(SRC)/Provers/make_elim.ML $(SRC)/Provers/order.ML $(SRC)/Provers/quasi.ML\
   $(SRC)/Provers/simplifier.ML $(SRC)/Provers/splitter.ML \
   $(SRC)/Provers/trancl.ML \
+  $(SRC)/TFL/casesplit.ML \
   $(SRC)/TFL/dcterm.ML $(SRC)/TFL/post.ML $(SRC)/TFL/rules.ML \
   $(SRC)/TFL/tfl.ML $(SRC)/TFL/thms.ML $(SRC)/TFL/thry.ML \
   $(SRC)/TFL/usyntax.ML $(SRC)/TFL/utils.ML \
--- a/src/HOL/Lambda/WeakNorm.thy	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/HOL/Lambda/WeakNorm.thy	Thu Mar 03 12:43:01 2005 +0100
@@ -566,7 +566,7 @@
   | term_of_dB' _ _ = error "term_of_dB: term not in normal form";
 
 fun typing_of_term Ts e (Bound i) =
-      rtypingT_Var (e, nat_of_int i, dBtype_of_typ (nth_elem (i, Ts)))
+      rtypingT_Var (e, nat_of_int i, dBtype_of_typ (List.nth (Ts, i)))
   | typing_of_term Ts e (t $ u) = (case fastype_of1 (Ts, t) of
         Type ("fun", [T, U]) => rtypingT_App (e, dB_of_term t,
           dBtype_of_typ T, dBtype_of_typ U, dB_of_term u,
--- a/src/HOL/Library/EfficientNat.thy	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/HOL/Library/EfficientNat.thy	Thu Mar 03 12:43:01 2005 +0100
@@ -100,7 +100,7 @@
     val Suc_if_eq' = Thm.transfer thy Suc_if_eq;
     val ctzero = cterm_of (sign_of Main.thy) HOLogic.zero;
     val vname = variant (map fst
-      (foldl add_term_varnames ([], map prop_of thms))) "x";
+      (Library.foldl add_term_varnames ([], map prop_of thms))) "x";
     val cv = cterm_of (sign_of Main.thy) (Var ((vname, 0), HOLogic.natT));
     fun lhs_of th = snd (Thm.dest_comb
       (fst (Thm.dest_comb (snd (Thm.dest_comb (cprop_of th))))));
@@ -114,13 +114,13 @@
           map (apfst (pairself (Thm.capply ct1))) (find_vars ct2)
         end
       | _ => []);
-    val eqs1 = flat (map
+    val eqs1 = List.concat (map
       (fn th => map (pair th) (find_vars (lhs_of th))) thms);
-    val eqs2 = map (fn x as (_, ((_, ctzero), _)) => (x, mapfilter (fn th =>
+    val eqs2 = map (fn x as (_, ((_, ctzero), _)) => (x, List.mapPartial (fn th =>
       SOME (th, Thm.cterm_match (lhs_of th, ctzero))
         handle Pattern.MATCH => NONE) thms)) eqs1;
     fun distinct_vars vs = forall is_Var vs andalso null (duplicates vs);
-    val eqs2' = map (apsnd (filter (fn (_, (_, s)) =>
+    val eqs2' = map (apsnd (List.filter (fn (_, (_, s)) =>
       distinct_vars (map (term_of o snd) s)))) eqs2;
     fun mk_thms b ((th, ((ct, _), cv')), (th', s) :: _) =
       let
@@ -133,7 +133,7 @@
                  SOME (rhs_of th''), SOME (Thm.cabs cv' (rhs_of th)), SOME cv']
                Suc_if_eq')) th'') (Thm.forall_intr cv' th)
       in
-        mapfilter (fn thm =>
+        List.mapPartial (fn thm =>
           if thm = th then SOME th'''
           else if b andalso thm = th' then NONE
           else SOME thm) thms
@@ -160,13 +160,13 @@
   let
     val Suc_clause' = Thm.transfer thy Suc_clause;
     val vname = variant (map fst
-      (foldl add_term_varnames ([], map prop_of thms))) "x";
+      (Library.foldl add_term_varnames ([], map prop_of thms))) "x";
     fun find_var (t as Const ("Suc", _) $ (v as Var _)) = SOME (t, v)
       | find_var (t $ u) = (case find_var t of NONE => find_var u | x => x)
       | find_var _ = NONE;
     fun find_thm th =
       let val th' = ObjectLogic.atomize_thm th
-      in apsome (pair (th, th')) (find_var (prop_of th')) end
+      in Option.map (pair (th, th')) (find_var (prop_of th')) end
   in
     case get_first find_thm thms of
       NONE => thms
@@ -191,8 +191,8 @@
   let val dest = fst o HOLogic.dest_mem o HOLogic.dest_Trueprop
   in
     if forall (can (dest o concl_of)) ths andalso
-      exists (fn th => "Suc" mem foldr add_term_consts
-        (mapfilter (try dest) (concl_of th :: prems_of th), [])) ths
+      exists (fn th => "Suc" mem Library.foldr add_term_consts
+        (List.mapPartial (try dest) (concl_of th :: prems_of th), [])) ths
     then remove_suc_clause thy ths else ths
   end;
 
--- a/src/HOL/List.thy	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/HOL/List.thy	Thu Mar 03 12:43:01 2005 +0100
@@ -2127,7 +2127,7 @@
     (let val c = chr (dest_nibble c1 * 16 + dest_nibble c2)
      in if Symbol.is_printable c then SOME (gr, Pretty.quote (Pretty.str c))
        else NONE
-     end handle LIST _ => NONE | Match => NONE)
+     end handle Fail _ => NONE | Match => NONE)
   | char_codegen thy gr dep b _ = NONE;
 
 in
--- a/src/HOL/Matrix/Cplex.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/HOL/Matrix/Cplex.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -716,7 +716,7 @@
 
 fun merge a b = Symtab.merge (op =) (a, b)
 
-fun mergemap f ts = foldl
+fun mergemap f ts = Library.foldl
 			(fn (table, x) => merge table (f x))
 			(Symtab.empty, ts)
 
@@ -778,7 +778,7 @@
 			      (fn (l, (k,v)) => (make_pos_constr k) :: l)
 			      ([], positive_vars))
         val bound_constrs = map (fn x => (NONE, x)) 
-				(flat (map bound2constr bounds))
+				(List.concat (map bound2constr bounds))
 	val constraints' = constraints @ pos_constrs @ bound_constrs	   
 	val bounds' = rev(Symtab.foldl (fn (l, (v,_)) => 
 					   (make_free_bound v)::l)
--- a/src/HOL/Matrix/CplexMatrixConverter.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/HOL/Matrix/CplexMatrixConverter.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -73,7 +73,7 @@
 	    set_elem vec (s2i v) (if positive then num else "-"^num)
 	  | setprod _ _ _ = raise (Converter "term is not a normed product")	
 
-	fun sum2vec (cplexSum ts) = foldl (fn (vec, t) => setprod vec true t) (empty_vector, ts)
+	fun sum2vec (cplexSum ts) = Library.foldl (fn (vec, t) => setprod vec true t) (empty_vector, ts)
 	  | sum2vec t = setprod empty_vector true t						
 
 	fun constrs2Ab j A b [] = (A, b)
@@ -100,7 +100,7 @@
     let
 	fun setv (v, (name, value)) = (matrix_builder.set_elem v (name2index name) value) 
     in
-	(opt, foldl setv (matrix_builder.empty_vector, entries))
+	(opt, Library.foldl setv (matrix_builder.empty_vector, entries))
     end
   | convert_results _ _ = raise (Converter "No optimal result")
     
--- a/src/HOL/Matrix/codegen_prep.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/HOL/Matrix/codegen_prep.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -80,7 +80,7 @@
     
 fun prepare_thms ths = 
     let
-	val ths = (filter is_meta_eq ths) @ (map (standard o mk_meta_eq) (filter (not o is_meta_eq) ths))		      
+	val ths = (List.filter is_meta_eq ths) @ (map (standard o mk_meta_eq) (filter_out is_meta_eq ths))		      
 	val _ = if forall Thm.no_prems ths then () else raise (Prepare_thms "premisse found")
 	val thmgroups = group head_name ths
 	val test_clashgroups = group (fn (a,b) => mangle_id a) thmgroups
--- a/src/HOL/Matrix/eq_codegen.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/HOL/Matrix/eq_codegen.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -24,7 +24,7 @@
 fun parens b = if b then Pretty.enclose "(" ")" else Pretty.block;
 
 fun gen_mk_val f xs ps = Pretty.block ([Pretty.str "val ",
-  f (length xs > 1) (flat
+  f (length xs > 1) (List.concat
     (separate [Pretty.str ",", Pretty.brk 1] (map (single o Pretty.str) xs))),
   Pretty.str " =", Pretty.brk 1] @ ps @ [Pretty.str ";"]);
 
@@ -79,7 +79,7 @@
       let
         val vs' = variantlist (map mk_decomp_tname Ts, vs);
         val (vs'', bs', ps') =
-          foldl decomp_type_code ((vs @ vs', bs, ps @
+          Library.foldl decomp_type_code ((vs @ vs', bs, ps @
             [mk_vall vs' [Pretty.str "Thm.dest_ctyp", Pretty.brk 1,
               Pretty.str v]]), vs' ~~ Ts)
       in
@@ -106,7 +106,7 @@
 fun pretty_pattern b (Const (s, _)) = Pretty.block [Pretty.str "Const",
       Pretty.brk 1, Pretty.str ("(\"" ^ s ^ "\", _)")]
   | pretty_pattern b (t as _ $ _) = parens b
-      (flat (separate [Pretty.str " $", Pretty.brk 1]
+      (List.concat (separate [Pretty.str " $", Pretty.brk 1]
         (map (single o pretty_pattern true) (op :: (strip_comb t)))))
   | pretty_pattern b _ = Pretty.str "_";
 
@@ -129,7 +129,7 @@
     [] => Pretty.str s
   | Ts => parens b [Pretty.str "tyinst_cterm", Pretty.brk 1,
       Pretty.list "[" "]" (map (fn (ixn, _) => mk_tyinst
-        (ixn, the (assoc (ty_bs, ixn)))) Ts),
+        (ixn, valOf (assoc (ty_bs, ixn)))) Ts),
       Pretty.brk 1, Pretty.str s]);
 
 fun mk_cterm_code b ty_bs ts xs (vals, t $ u) =
@@ -151,7 +151,7 @@
       in (vals',
         parens b [Pretty.str "Thm.cabs", Pretty.brk 1, p, Pretty.brk 1, p'])
       end
-  | mk_cterm_code b ty_bs ts xs (vals, Bound i) = (vals, nth_elem (i, xs))
+  | mk_cterm_code b ty_bs ts xs (vals, Bound i) = (vals, List.nth (xs, i))
   | mk_cterm_code b ty_bs ts xs (vals, t) = (case assoc (vals, t) of
         NONE =>
           let val SOME s = assoc (ts, t)
@@ -182,7 +182,7 @@
       in if s = s' then (vs, subs)
         else (s' :: vs, ((s, i), Var ((s', i), T)) :: subs)
       end;
-    val (vs', subs) = foldl mk_subst ((vs, []), term_vars t)
+    val (vs', subs) = Library.foldl mk_subst ((vs, []), term_vars t)
   in (vs', subst_Vars subs t) end;
 
 fun is_instance sg t u = t = subst_TVars_Vartab
@@ -190,7 +190,7 @@
     (fastype_of u, fastype_of t))) u handle Type.TYPE_MATCH => false;
 
 (*
-fun lookup sg fs t = apsome snd (Library.find_first
+fun lookup sg fs t = Option.map snd (Library.find_first
   (is_instance sg t o fst) fs);
 *)
 
@@ -269,18 +269,18 @@
                     val cvs' = map Var (map (rpair 0) ys ~~ Ts);
                     val rs = cvs' ~~ cvs;
                     val lhs = list_comb (Const (cname, Ts ---> uT), cvs');
-                    val rhs = foldl betapply (f, cvs');
+                    val rhs = Library.foldl betapply (f, cvs');
                     val (vs', tm_bs, tm_vals) = decomp_term_code false
                       ((vs @ ys, [], []), (ct, lhs));
                     val ((vs'', all_vals), (eq', ct')) = mk_simpl_code sg case_tab
                       false fs (tm_bs @ ts) ty_bs thm_bs ((vs', vals), rhs);
                     val (old_vals, eq_vals) = splitAt (i, all_vals);
-                    val vs''' = vs @ filter (fn v => exists
+                    val vs''' = vs @ List.filter (fn v => exists
                       (fn (_, ((v', _), _)) => v = v') old_vals) (vs'' \\ vs');
                     val insts2 = map (fn (t, s) => Pretty.block [Pretty.str "(",
-                      inst_ty false ty_bs' t (the (assoc (thm_bs, t))), Pretty.str ",",
+                      inst_ty false ty_bs' t (valOf (assoc (thm_bs, t))), Pretty.str ",",
                       Pretty.brk 1, Pretty.str (s ^ ")")]) ((fvs ~~ xs) @
-                        (map (fn (v, s) => (the (assoc (rs, v)), s)) tm_bs));
+                        (map (fn (v, s) => (valOf (assoc (rs, v)), s)) tm_bs));
                     val eq'' = if null insts1 andalso null insts2 then Pretty.str name
                       else parens (eq' <> "") [Pretty.str
                           (if null cvs then "Thm.instantiate" else "Drule.instantiate"),
@@ -293,7 +293,7 @@
                   in
                     ((vs''', old_vals), Pretty.block [pretty_pattern false lhs,
                       Pretty.str " =>",
-                      Pretty.brk 1, mk_let "let" 2 (tm_vals @ flat (map (snd o snd) eq_vals))
+                      Pretty.brk 1, mk_let "let" 2 (tm_vals @ List.concat (map (snd o snd) eq_vals))
                         [Pretty.str ("(" ^ ct' ^ ","), Pretty.brk 1, eq''', Pretty.str ")"]])
                   end;
 
@@ -308,7 +308,7 @@
                   fvals @ ty_vals @
                   [mk_val [ct', eq'] ([Pretty.str "(case", Pretty.brk 1,
                     Pretty.str ("term_of " ^ ct ^ " of"), Pretty.brk 1] @
-                    flat (separate [Pretty.brk 1, Pretty.str "| "]
+                    List.concat (separate [Pretty.brk 1, Pretty.str "| "]
                       (map single case_ps)) @ [Pretty.str ")"])]
               in
                 if b then
@@ -334,7 +334,7 @@
               val b = forall (unint sg fs) us;
               val (q, eqs) = foldl_map
                 (mk_simpl_code sg case_tab (not b) fs ts ty_bs thm_bs) ((vs, vals), us);
-              val ((vs', vals'), (eqf, ctf)) = if is_some (lookup sg fs f) andalso b
+              val ((vs', vals'), (eqf, ctf)) = if isSome (lookup sg fs f) andalso b
                 then (q, ("", ""))
                 else mk_simpl_code sg case_tab (not b) fs ts ty_bs thm_bs (q, f);
               val ct = variant vs' "ct";
@@ -372,38 +372,38 @@
 
 fun mk_funs_code sg case_tab fs fs' =
   let
-    val case_thms = mapfilter (fn s => (case Symtab.lookup (case_tab, s) of
+    val case_thms = List.mapPartial (fn s => (case Symtab.lookup (case_tab, s) of
         NONE => NONE
       | SOME thms => SOME (unsuffix "_case" (Sign.base_name s) ^ ".cases",
           map (fn i => Sign.base_name s ^ "_" ^ string_of_int i)
             (1 upto length thms) ~~ thms)))
-      (foldr add_term_consts (map (prop_of o snd)
-        (flat (map (#3 o snd) fs')), []));
+      (Library.foldr add_term_consts (map (prop_of o snd)
+        (List.concat (map (#3 o snd) fs')), []));
     val case_vals = map (fn (s, cs) => mk_vall (map fst cs)
       [Pretty.str "map my_mk_meta_eq", Pretty.brk 1,
        Pretty.str ("(thms \"" ^ s ^ "\")")]) case_thms;
-    val (vs, thm_bs, thm_vals) = foldl mk_term_bindings (([], [], []),
-      flat (map (map (apsnd prop_of) o #3 o snd) fs') @
-      map (apsnd prop_of) (flat (map snd case_thms)));
+    val (vs, thm_bs, thm_vals) = Library.foldl mk_term_bindings (([], [], []),
+      List.concat (map (map (apsnd prop_of) o #3 o snd) fs') @
+      map (apsnd prop_of) (List.concat (map snd case_thms)));
 
     fun mk_fun_code (prfx, (fname, d, eqns)) =
       let
         val (f, ts) = strip_comb (lhs_of (snd (hd eqns)));
         val args = variantlist (replicate (length ts) "ct", vs);
-        val (vs', ty_bs, ty_vals) = foldl mk_type_bindings
+        val (vs', ty_bs, ty_vals) = Library.foldl mk_type_bindings
           ((vs @ args, [], []), args ~~ map fastype_of ts);
         val insts1 = map mk_tyinst ty_bs;
 
         fun mk_eqn_code (name, eqn) =
           let
             val (_, argts) = strip_comb (lhs_of eqn);
-            val (vs'', tm_bs, tm_vals) = foldl (decomp_term_code false)
+            val (vs'', tm_bs, tm_vals) = Library.foldl (decomp_term_code false)
               ((vs', [], []), args ~~ argts);
             val ((vs''', eq_vals), (eq, ct)) = mk_simpl_code sg case_tab false fs
               (tm_bs @ filter_out (is_Var o fst) thm_bs) ty_bs thm_bs
               ((vs'', []), rhs_of eqn);
             val insts2 = map (fn (t, s) => Pretty.block [Pretty.str "(",
-              inst_ty false ty_bs t (the (assoc (thm_bs, t))), Pretty.str ",", Pretty.brk 1,
+              inst_ty false ty_bs t (valOf (assoc (thm_bs, t))), Pretty.str ",", Pretty.brk 1,
               Pretty.str (s ^ ")")]) tm_bs
             val eq' = if null insts1 andalso null insts2 then Pretty.str name
               else parens (eq <> "") [Pretty.str "Thm.instantiate",
@@ -417,7 +417,7 @@
             Pretty.block [parens (length argts > 1)
                 (Pretty.commas (map (pretty_pattern false) argts)),
               Pretty.str " =>",
-              Pretty.brk 1, mk_let "let" 2 (ty_vals @ tm_vals @ flat (map (snd o snd) eq_vals))
+              Pretty.brk 1, mk_let "let" 2 (ty_vals @ tm_vals @ List.concat (map (snd o snd) eq_vals))
                 [Pretty.str ("(" ^ ct ^ ","), Pretty.brk 1, eq'', Pretty.str ")"]]
           end;
 
@@ -441,7 +441,7 @@
           [Pretty.str " =", Pretty.brk 1, Pretty.str "(case", Pretty.brk 1,
            Pretty.list "(" ")" (map (fn s => Pretty.str ("term_of " ^ s)) args),
            Pretty.str " of", Pretty.brk 1] @
-          flat (separate [Pretty.brk 1, Pretty.str "| "]
+          List.concat (separate [Pretty.brk 1, Pretty.str "| "]
             (map (single o mk_eqn_code) eqns)) @ [Pretty.str ")"] @ default))
       end;
 
@@ -458,19 +458,19 @@
     val eqns' = map attach_term eqns;
     fun mk_node (s, _, (_, th) :: _) = (s, get_head th);
     fun mk_edges (s, _, ths) = map (pair s) (distinct
-      (mapfilter (fn t => apsome #1 (lookup sg eqns' t))
-        (flat (map (term_consts' o prop_of o snd) ths))));
-    val gr = foldr (uncurry Graph.add_edge)
-      (map (pair "" o #1) eqns @ flat (map mk_edges eqns),
-       foldr (uncurry Graph.new_node)
+      (List.mapPartial (fn t => Option.map #1 (lookup sg eqns' t))
+        (List.concat (map (term_consts' o prop_of o snd) ths))));
+    val gr = Library.foldr (uncurry Graph.add_edge)
+      (map (pair "" o #1) eqns @ List.concat (map mk_edges eqns),
+       Library.foldr (uncurry Graph.new_node)
          (("", Bound 0) :: map mk_node eqns, Graph.empty));
     val keys = rev (Graph.all_succs gr [""] \ "");
     fun gr_ord (x :: _, y :: _) =
       int_ord (find_index (equal x) keys, find_index (equal y) keys);
-    val scc = map (fn xs => filter (fn (_, (s, _, _)) => s mem xs) eqns')
+    val scc = map (fn xs => List.filter (fn (_, (s, _, _)) => s mem xs) eqns')
       (sort gr_ord (Graph.strong_conn gr \ [""]));
   in
-    flat (separate [Pretty.str ";", Pretty.fbrk, Pretty.str " ", Pretty.fbrk]
+    List.concat (separate [Pretty.str ";", Pretty.fbrk, Pretty.str " ", Pretty.fbrk]
       (map (fn eqns'' => [mk_funs_code sg case_tab eqns' eqns'']) scc)) @
     [Pretty.str ";", Pretty.fbrk]
   end;
@@ -482,7 +482,7 @@
       let val (i', eqs') = foldl_map attach_name (i, eqs)
       in (i', (s, b, eqs')) end;
     val (_, eqns') = foldl_map attach_names (1, eqns);
-    val (names, thms) = split_list (flat (map #3 eqns'));
+    val (names, thms) = split_list (List.concat (map #3 eqns'));
     val s = setmp print_mode [] Pretty.string_of
       (mk_let "local" 2 [mk_vall names [Pretty.str "!SimprocsCodegen.simp_thms"]]
         (mk_simprocs_code sg eqns'))
--- a/src/HOL/Matrix/fspmlp.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/HOL/Matrix/fspmlp.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -145,7 +145,7 @@
 				     NONE => NONE
 				   | SOME src_sure_bound => SOME (FloatArith.add x (mult_btype src_sure_bound coeff)))
 		    in
-			case foldl add_src_bound (SOME row_bound, sources) of
+			case Library.foldl add_src_bound (SOME row_bound, sources) of
 			    NONE => sure_bound
 			  | new_sure_bound as (SOME new_bound) => 
 			    (case sure_bound of 
@@ -234,7 +234,7 @@
 						add_edge g (src_index, LOWER) dest_key row_index coeff
 					end
 			    in	    
-				foldl fold_src_nodes ((add_row_bound g dest_key row_index row_bound), approx_a)
+				Library.foldl fold_src_nodes ((add_row_bound g dest_key row_index row_bound), approx_a)
 			    end
 		    end
 	    in
@@ -251,7 +251,7 @@
 			else
 			    g
 		    end
-		  | _ => foldl fold_dest_nodes (g, approx_a)
+		  | _ => Library.foldl fold_dest_nodes (g, approx_a)
 	    end
 	
 	val g = FloatSparseMatrixBuilder.m_fold calcr VarGraph.empty A
--- a/src/HOL/MicroJava/BV/BVExample.thy	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/HOL/MicroJava/BV/BVExample.thy	Thu Mar 03 12:43:01 2005 +0100
@@ -454,7 +454,7 @@
   "op :"   ("(_ mem _)")
   "op Un"  ("(_ union _)")
   "image"  ("map")
-  "UNION"  ("(fn A => fn f => flat (map f A))")
+  "UNION"  ("(fn A => fn f => List.concat (map f A))")
   "Bex"    ("(fn A => fn f => exists f A)")
   "Ball"   ("(fn A => fn f => forall f A)")
   "some_elem" ("hd")
--- a/src/HOL/Modelcheck/EindhovenSyn.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/HOL/Modelcheck/EindhovenSyn.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -7,7 +7,7 @@
 fun mc_eindhoven_tac i state =
 let val sign = #sign (rep_thm state)
 in 
-case drop(i-1,prems_of state) of
+case Library.drop(i-1,prems_of state) of
    [] => Seq.empty |
    subgoal::_ => 
 	let val concl = Logic.strip_imp_concl subgoal;
--- a/src/HOL/Modelcheck/MuckeSyn.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/HOL/Modelcheck/MuckeSyn.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -51,14 +51,14 @@
 		     REPEAT (resolve_tac prems 1)]);
 
   val sig_move_thm = #sign (rep_thm move_thm);
-  val bCterm = cterm_of sig_move_thm (the (search_var "b" (concl_of move_thm)));
-  val aCterm = cterm_of sig_move_thm (the (search_var "a" (hd(prems_of move_thm)))); 
+  val bCterm = cterm_of sig_move_thm (valOf (search_var "b" (concl_of move_thm)));
+  val aCterm = cterm_of sig_move_thm (valOf (search_var "a" (hd(prems_of move_thm)))); 
 
 in
 
 fun move_mus i state =
 let val sign = #sign (rep_thm state);
-    val (subgoal::_) = drop(i-1,prems_of state);
+    val (subgoal::_) = Library.drop(i-1,prems_of state);
     val concl = Logic.strip_imp_concl subgoal; (* recursive mu's in prems? *)
     val redex = search_mu concl;
     val idx = let val t = #maxidx (rep_thm state) in 
@@ -84,7 +84,7 @@
 (* Normally t can be user-instantiated by the value thy of the Isabelle context     *)
 fun call_mucke_tac i state =
 let val sign = #sign (rep_thm state);
-    val (subgoal::_) = drop(i-1,prems_of state);
+    val (subgoal::_) = Library.drop(i-1,prems_of state);
     val OraAss = invoke_oracle MuckeSyn.thy "Mucke" (sign,MuckeOracleExn (subgoal));
 in 
 (cut_facts_tac [OraAss] i) state
@@ -166,7 +166,7 @@
 (* the interface *)
 
 fun mc_mucke_tac defs i state =
-  (case drop (i - 1, Thm.prems_of state) of
+  (case Library.drop (i - 1, Thm.prems_of state) of
     [] => PureGeneral.Seq.empty
   | subgoal :: _ =>
       EVERY [
--- a/src/HOL/Modelcheck/mucke_oracle.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/HOL/Modelcheck/mucke_oracle.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -96,7 +96,7 @@
 
 fun if_full_simp_tac sset i state =
 let val sign = #sign (rep_thm state);
-        val (subgoal::_) = drop(i-1,prems_of state);
+        val (subgoal::_) = Library.drop(i-1,prems_of state);
         val prems = Logic.strip_imp_prems subgoal;
 	val concl = Logic.strip_imp_concl subgoal;
 	val prems = prems @ [concl];
@@ -253,10 +253,10 @@
       fun newName (Var(ix,_), (pairs,used)) = 
           let val v = variant used (string_of_indexname ix)
           in  ((ix,v)::pairs, v::used)  end;
-      val (alist, _) = foldr newName (vars, ([], used));
+      val (alist, _) = Library.foldr newName (vars, ([], used));
       fun mk_inst (Var(v,T)) = 
           (Var(v,T),
-           Free(the (assoc(alist,v)), T));
+           Free(valOf (assoc(alist,v)), T));
       val insts = map mk_inst vars;
   in subst_atomic insts t end;
 
--- a/src/HOL/Product_Type.thy	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/HOL/Product_Type.thy	Thu Mar 03 12:43:01 2005 +0100
@@ -816,7 +816,7 @@
             val (gr1, qs) = foldl_map mk_code (gr, ps);
             val (gr2, pu) = Codegen.invoke_codegen thy dep false (gr1, u)
           in
-            SOME (gr2, Pretty.blk (0, [Pretty.str "let ", Pretty.blk (0, flat
+            SOME (gr2, Pretty.blk (0, [Pretty.str "let ", Pretty.blk (0, List.concat
                 (separate [Pretty.str ";", Pretty.brk 1] (map (fn (pl, pr) =>
                   [Pretty.block [Pretty.str "val ", pl, Pretty.str " =",
                      Pretty.brk 1, pr]]) qs))),
--- a/src/HOL/Prolog/HOHH.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/HOL/Prolog/HOHH.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -63,7 +63,7 @@
 	imp_all];	  (* "((!x. D) :- G) = (!x. D :- G)" *)
 
 (*val hyp_resolve_tac = METAHYPS (fn prems => 
-				  resolve_tac (flat (map atomizeD prems)) 1);
+				  resolve_tac (List.concat (map atomizeD prems)) 1);
   -- is nice, but cannot instantiate unknowns in the assumptions *)
 fun hyp_resolve_tac i st = let
 	fun ap (Const("All",_)$Abs(_,_,t))=(case ap t of (k,a,t) => (k+1,a  ,t))
@@ -98,10 +98,10 @@
 		else no_tac);
 	val ptacs = mapn (fn n => fn t => 
 			  pres_tac (ap (HOLogic.dest_Trueprop t)) n i) 0 prems;
-	in foldl (op APPEND) (no_tac, ptacs) st end;
+	in Library.foldl (op APPEND) (no_tac, ptacs) st end;
 
 fun ptac prog = let
-  val proga = flat (map atomizeD prog)			(* atomize the prog *)
+  val proga = List.concat (map atomizeD prog)			(* atomize the prog *)
   in	(REPEAT_DETERM1 o FIRST' [
 		rtac TrueI,			(* "True" *)
 		rtac conjI,			(* "[| P; Q |] ==> P & Q" *)
--- a/src/HOL/Tools/Presburger/cooper_dec.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/HOL/Tools/Presburger/cooper_dec.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -442,7 +442,7 @@
    val ts = coeffs_of t
    in case ts of
      [] => raise DVD_UNKNOWN
-    |_  => foldr (fn(k,r) => r andalso (k mod dn = 0)) (ts,true)
+    |_  => Library.foldr (fn(k,r) => r andalso (k mod dn = 0)) (ts,true)
    end;
 
 
@@ -736,7 +736,7 @@
              in (rw,HOLogic.mk_disj(F',rf)) 
 	     end)
     val f = if b then linear_add else linear_sub
-    val p_elements = foldr (fn (i,l) => l union (map (fn e => f [] e (mk_numeral i)) st)) (1 upto d,[])
+    val p_elements = Library.foldr (fn (i,l) => l union (map (fn e => f [] e (mk_numeral i)) st)) (1 upto d,[])
     in h p_elements
     end;
 
@@ -873,7 +873,7 @@
 fun lift_qelim afn nfn qfn isat = 
  let   fun qelim x vars p = 
   let val cjs = conjuncts p 
-      val (ycjs,ncjs) = partition (has_bound) cjs in 
+      val (ycjs,ncjs) = List.partition (has_bound) cjs in 
       (if ycjs = [] then p else 
                           let val q = (qfn vars ((HOLogic.exists_const HOLogic.intT 
 			  ) $ Abs(x,HOLogic.intT,(list_conj ycjs)))) in 
--- a/src/HOL/Tools/Presburger/presburger.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/HOL/Tools/Presburger/presburger.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -148,21 +148,21 @@
       if body_type T mem [iT, nT] 
          andalso not (ts = []) andalso forall (null o loose_bnos) ts 
       then [fm]
-      else foldl op union ([], map getfuncs ts)
+      else Library.foldl op union ([], map getfuncs ts)
   | (Var (_, T), ts as _ :: _) =>
       if body_type T mem [iT, nT] 
          andalso not (ts = []) andalso forall (null o loose_bnos) ts then [fm]
-      else foldl op union ([], map getfuncs ts)
+      else Library.foldl op union ([], map getfuncs ts)
   | (Const (s, T), ts) =>
       if (s, T) mem allowed_consts orelse not (body_type T mem [iT, nT])
-      then foldl op union ([], map getfuncs ts)
+      then Library.foldl op union ([], map getfuncs ts)
       else [fm]
   | (Abs (s, T, t), _) => getfuncs t
   | _ => [];
 
 
 fun abstract_pres sg fm = 
-  foldr (fn (t, u) =>
+  Library.foldr (fn (t, u) =>
       let val T = fastype_of t
       in all T $ Abs ("x", T, abstract_over (t, u)) end)
          (getfuncs fm, fm);
@@ -198,7 +198,7 @@
  abstracted over.*)
  
 fun relevant ps t = (term_typed_consts t) subset allowed_consts andalso 
-  map (fn i => snd (nth_elem (i, ps))) (loose_bnos t) @
+  map (fn i => snd (List.nth (ps, i))) (loose_bnos t) @
   map (snd o dest_Free) (term_frees t) @ map (snd o dest_Var) (term_vars t)
   subset [iT, nT]
   andalso not (has_free_funcs t);
@@ -217,13 +217,13 @@
         (HOLogic.all_const T $ Abs (s, T, P), n)
       else (incr_boundvars ~1 P, n-1)
     fun mk_all2 (v, t) = HOLogic.all_const (fastype_of v) $ lambda v t;
-    val (rhs,irhs) = partition (relevant (rev ps)) hs
+    val (rhs,irhs) = List.partition (relevant (rev ps)) hs
     val np = length ps
-    val (fm',np) =  foldr (fn ((x, T), (fm,n)) => mk_all ((x, T), (fm,n)))
-      (ps,(foldr HOLogic.mk_imp (rhs, c), np))
-    val (vs, _) = partition (fn t => q orelse (type_of t) = nT)
+    val (fm',np) =  Library.foldr (fn ((x, T), (fm,n)) => mk_all ((x, T), (fm,n)))
+      (ps,(Library.foldr HOLogic.mk_imp (rhs, c), np))
+    val (vs, _) = List.partition (fn t => q orelse (type_of t) = nT)
       (term_frees fm' @ term_vars fm');
-    val fm2 = foldr mk_all2 (vs, fm')
+    val fm2 = Library.foldr mk_all2 (vs, fm')
   in (fm2, np + length vs, length rhs) end;
 
 (*Object quantifier to meta --*)
@@ -300,7 +300,7 @@
  in
    Method.simple_args 
   (Scan.optional (Args.$$$ "(" |-- Scan.repeat1 parse_flag --| Args.$$$ ")") [] >>
-    curry (foldl op |>) (true, false))
+    curry (Library.foldl op |>) (true, false))
     (fn (q,a) => fn _ => meth q a 1)
   end;
 
--- a/src/HOL/Tools/datatype_abs_proofs.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/HOL/Tools/datatype_abs_proofs.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -54,9 +54,9 @@
   let
     val _ = message "Proving case distinction theorems ...";
 
-    val descr' = flat descr;
+    val descr' = List.concat descr;
     val recTs = get_rec_types descr' sorts;
-    val newTs = take (length (hd descr), recTs);
+    val newTs = Library.take (length (hd descr), recTs);
 
     val {maxidx, ...} = rep_thm induct;
     val induct_Ps = map head_of (HOLogic.dest_conj (HOLogic.dest_Trueprop (concl_of induct)));
@@ -67,11 +67,11 @@
           Abs ("z", T', Const ("True", T''))) induct_Ps;
         val P = Abs ("z", T, HOLogic.imp $ HOLogic.mk_eq (Var (("a", maxidx+1), T), Bound 0) $
           Var (("P", 0), HOLogic.boolT))
-        val insts = take (i, dummyPs) @ (P::(drop (i + 1, dummyPs)));
+        val insts = Library.take (i, dummyPs) @ (P::(Library.drop (i + 1, dummyPs)));
         val cert = cterm_of (Theory.sign_of thy);
         val insts' = (map cert induct_Ps) ~~ (map cert insts);
-        val induct' = refl RS ((nth_elem (i,
-          split_conj_thm (cterm_instantiate insts' induct))) RSN (2, rev_mp))
+        val induct' = refl RS ((List.nth
+          (split_conj_thm (cterm_instantiate insts' induct), i)) RSN (2, rev_mp))
 
       in prove_goalw_cterm [] (cert t) (fn prems =>
         [rtac induct' 1,
@@ -95,10 +95,10 @@
     val big_name = space_implode "_" new_type_names;
     val thy0 = add_path flat_names big_name thy;
 
-    val descr' = flat descr;
+    val descr' = List.concat descr;
     val recTs = get_rec_types descr' sorts;
-    val used = foldr add_typ_tfree_names (recTs, []);
-    val newTs = take (length (hd descr), recTs);
+    val used = Library.foldr add_typ_tfree_names (recTs, []);
+    val newTs = Library.take (length (hd descr), recTs);
 
     val induct_Ps = map head_of (HOLogic.dest_conj (HOLogic.dest_Trueprop (concl_of induct)));
 
@@ -127,27 +127,27 @@
           in (case (strip_dtyp dt, strip_type U) of
              ((_, DtRec m), (Us, _)) =>
                let
-                 val free2 = mk_Free "y" (Us ---> nth_elem (m, rec_result_Ts)) k;
+                 val free2 = mk_Free "y" (Us ---> List.nth (rec_result_Ts, m)) k;
                  val i = length Us
                in (j + 1, k + 1, HOLogic.mk_Trueprop (HOLogic.list_all
                      (map (pair "x") Us, HOLogic.mk_mem (HOLogic.mk_prod
                        (app_bnds free1 i, app_bnds free2 i),
-                         nth_elem (m, rec_sets)))) :: prems,
+                         List.nth (rec_sets, m)))) :: prems,
                    free1::t1s, free2::t2s)
                end
            | _ => (j + 1, k, prems, free1::t1s, t2s))
           end;
 
         val Ts = map (typ_of_dtyp descr' sorts) cargs;
-        val (_, _, prems, t1s, t2s) = foldr mk_prem (cargs ~~ Ts, (1, 1, [], [], []))
+        val (_, _, prems, t1s, t2s) = Library.foldr mk_prem (cargs ~~ Ts, (1, 1, [], [], []))
 
       in (rec_intr_ts @ [Logic.list_implies (prems, HOLogic.mk_Trueprop (HOLogic.mk_mem
         (HOLogic.mk_prod (list_comb (Const (cname, Ts ---> T), t1s),
-          list_comb (nth_elem (l, rec_fns), t1s @ t2s)), set_name)))], l + 1)
+          list_comb (List.nth (rec_fns, l), t1s @ t2s)), set_name)))], l + 1)
       end;
 
-    val (rec_intr_ts, _) = foldl (fn (x, ((d, T), set_name)) =>
-      foldl (make_rec_intr T set_name) (x, #3 (snd d)))
+    val (rec_intr_ts, _) = Library.foldl (fn (x, ((d, T), set_name)) =>
+      Library.foldl (make_rec_intr T set_name) (x, #3 (snd d)))
         (([], 0), descr' ~~ recTs ~~ rec_sets);
 
     val (thy1, {intrs = rec_intrs, elims = rec_elims, ...}) =
@@ -163,16 +163,16 @@
       let
         val distinct_tac = (etac Pair_inject 1) THEN
           (if i < length newTs then
-             full_simp_tac (HOL_ss addsimps (nth_elem (i, dist_rewrites))) 1
+             full_simp_tac (HOL_ss addsimps (List.nth (dist_rewrites, i))) 1
            else full_simp_tac dist_ss 1);
 
         val inject = map (fn r => r RS iffD1)
-          (if i < length newTs then nth_elem (i, constr_inject)
-            else #inject (the (Symtab.lookup (dt_info, tname))));
+          (if i < length newTs then List.nth (constr_inject, i)
+            else #inject (valOf (Symtab.lookup (dt_info, tname))));
 
         fun mk_unique_constr_tac n ((tac, intr::intrs, j), (cname, cargs)) =
           let
-            val k = length (filter is_rec_type cargs)
+            val k = length (List.filter is_rec_type cargs)
 
           in (EVERY [DETERM tac,
                 REPEAT (etac ex1E 1), rtac ex1I 1,
@@ -189,7 +189,7 @@
               intrs, j + 1)
           end;
 
-        val (tac', intrs', _) = foldl (mk_unique_constr_tac (length constrs))
+        val (tac', intrs', _) = Library.foldl (mk_unique_constr_tac (length constrs))
           ((tac, intrs, 0), constrs);
 
       in (tac', intrs') end;
@@ -206,7 +206,7 @@
           ((1 upto length recTs) ~~ recTs ~~ rec_unique_ts);
         val induct' = cterm_instantiate ((map cert induct_Ps) ~~
           (map cert insts)) induct;
-        val (tac, _) = foldl mk_unique_tac
+        val (tac, _) = Library.foldl mk_unique_tac
           (((rtac induct' THEN_ALL_NEW ObjectLogic.atomize_tac) 1
               THEN rewtac (mk_meta_eq choice_eq), rec_intrs),
             descr' ~~ rec_elims ~~ recTs ~~ rec_result_Ts);
@@ -255,7 +255,7 @@
   in
     thy2 |> Theory.add_path (space_implode "_" new_type_names) |>
     PureThy.add_thmss [(("recs", rec_thms), [])] |>>
-    Theory.parent_path |> apsnd (pair reccomb_names o flat)
+    Theory.parent_path |> apsnd (pair reccomb_names o List.concat)
   end;
 
 
@@ -267,10 +267,10 @@
 
     val thy1 = add_path flat_names (space_implode "_" new_type_names) thy;
 
-    val descr' = flat descr;
+    val descr' = List.concat descr;
     val recTs = get_rec_types descr' sorts;
-    val used = foldr add_typ_tfree_names (recTs, []);
-    val newTs = take (length (hd descr), recTs);
+    val used = Library.foldr add_typ_tfree_names (recTs, []);
+    val newTs = Library.take (length (hd descr), recTs);
     val T' = TFree (variant used "'t", HOLogic.typeS);
 
     fun mk_dummyT dt = binder_types (typ_of_dtyp descr' sorts dt) ---> T';
@@ -278,7 +278,7 @@
     val case_dummy_fns = map (fn (_, (_, _, constrs)) => map (fn (_, cargs) =>
       let
         val Ts = map (typ_of_dtyp descr' sorts) cargs;
-        val Ts' = map mk_dummyT (filter is_rec_type cargs)
+        val Ts' = map mk_dummyT (List.filter is_rec_type cargs)
       in Const ("arbitrary", Ts @ Ts' ---> T')
       end) constrs) descr';
 
@@ -287,15 +287,15 @@
 
     (* define case combinators via primrec combinators *)
 
-    val (case_defs, thy2) = foldl (fn ((defs, thy),
+    val (case_defs, thy2) = Library.foldl (fn ((defs, thy),
       ((((i, (_, _, constrs)), T), name), recname)) =>
         let
           val (fns1, fns2) = ListPair.unzip (map (fn ((_, cargs), j) =>
             let
               val Ts = map (typ_of_dtyp descr' sorts) cargs;
-              val Ts' = Ts @ map mk_dummyT (filter is_rec_type cargs);
+              val Ts' = Ts @ map mk_dummyT (List.filter is_rec_type cargs);
               val frees' = map (uncurry (mk_Free "x")) (Ts' ~~ (1 upto length Ts'));
-              val frees = take (length cargs, frees');
+              val frees = Library.take (length cargs, frees');
               val free = mk_Free "f" (Ts ---> T') j
             in
              (free, list_abs_free (map dest_Free frees',
@@ -303,20 +303,20 @@
             end) (constrs ~~ (1 upto length constrs)));
 
           val caseT = (map (snd o dest_Free) fns1) @ [T] ---> T';
-          val fns = (flat (take (i, case_dummy_fns))) @
-            fns2 @ (flat (drop (i + 1, case_dummy_fns)));
+          val fns = (List.concat (Library.take (i, case_dummy_fns))) @
+            fns2 @ (List.concat (Library.drop (i + 1, case_dummy_fns)));
           val reccomb = Const (recname, (map fastype_of fns) @ [T] ---> T');
           val decl = (Sign.base_name name, caseT, NoSyn);
           val def = ((Sign.base_name name) ^ "_def",
             Logic.mk_equals (list_comb (Const (name, caseT), fns1),
-              list_comb (reccomb, (flat (take (i, case_dummy_fns))) @
-                fns2 @ (flat (drop (i + 1, case_dummy_fns))) )));
+              list_comb (reccomb, (List.concat (Library.take (i, case_dummy_fns))) @
+                fns2 @ (List.concat (Library.drop (i + 1, case_dummy_fns))) )));
           val (thy', [def_thm]) = thy |>
             Theory.add_consts_i [decl] |> (PureThy.add_defs_i false o map Thm.no_attributes) [def];
 
         in (defs @ [def_thm], thy')
         end) (([], thy1), (hd descr) ~~ newTs ~~ case_names ~~
-          (take (length newTs, reccomb_names)));
+          (Library.take (length newTs, reccomb_names)));
 
     val case_thms = map (map (fn t => prove_goalw_cterm (case_defs @
       (map mk_meta_eq primrec_thms)) (cterm_of (Theory.sign_of thy2) t)
@@ -338,9 +338,9 @@
   let
     val _ = message "Proving equations for case splitting ...";
 
-    val descr' = flat descr;
+    val descr' = List.concat descr;
     val recTs = get_rec_types descr' sorts;
-    val newTs = take (length (hd descr), recTs);
+    val newTs = Library.take (length (hd descr), recTs);
 
     fun prove_split_thms ((((((t1, t2), inject), dist_rewrites'),
         exhaustion), case_thms'), T) =
@@ -372,7 +372,7 @@
 fun prove_size_thms flat_names new_type_names descr sorts reccomb_names primrec_thms thy =
   if exists (fn (_, (_, _, constrs)) => exists (fn (_, cargs) => exists (fn dt =>
     is_rec_type dt andalso not (null (fst (strip_dtyp dt)))) cargs) constrs)
-      (flat descr)
+      (List.concat descr)
   then
     (thy, [])
   else
@@ -382,13 +382,13 @@
     val big_name = space_implode "_" new_type_names;
     val thy1 = add_path flat_names big_name thy;
 
-    val descr' = flat descr;
+    val descr' = List.concat descr;
     val recTs = get_rec_types descr' sorts;
 
     val size_name = "Nat.size";
     val size_names = replicate (length (hd descr)) size_name @
       map (Sign.full_name (Theory.sign_of thy1)) (DatatypeProp.indexify_names
-        (map (fn T => name_of_typ T ^ "_size") (drop (length (hd descr), recTs))));
+        (map (fn T => name_of_typ T ^ "_size") (Library.drop (length (hd descr), recTs))));
     val def_names = map (fn s => s ^ "_def") (DatatypeProp.indexify_names
       (map (fn T => name_of_typ T ^ "_size") recTs));
 
@@ -397,20 +397,20 @@
     fun make_sizefun (_, cargs) =
       let
         val Ts = map (typ_of_dtyp descr' sorts) cargs;
-        val k = length (filter is_rec_type cargs);
+        val k = length (List.filter is_rec_type cargs);
         val t = if k = 0 then HOLogic.zero else
           foldl1 plus (map Bound (k - 1 downto 0) @ [HOLogic.mk_nat 1])
       in
-        foldr (fn (T, t') => Abs ("x", T, t')) (Ts @ replicate k HOLogic.natT, t)
+        Library.foldr (fn (T, t') => Abs ("x", T, t')) (Ts @ replicate k HOLogic.natT, t)
       end;
 
-    val fs = flat (map (fn (_, (_, _, constrs)) => map make_sizefun constrs) descr');
+    val fs = List.concat (map (fn (_, (_, _, constrs)) => map make_sizefun constrs) descr');
     val fTs = map fastype_of fs;
 
     val (thy', size_def_thms) = thy1 |>
       Theory.add_consts_i (map (fn (s, T) =>
         (Sign.base_name s, T --> HOLogic.natT, NoSyn))
-          (drop (length (hd descr), size_names ~~ recTs))) |>
+          (Library.drop (length (hd descr), size_names ~~ recTs))) |>
       (PureThy.add_defs_i true o map Thm.no_attributes) (map (fn (((s, T), def_name), rec_name) =>
         (def_name, Logic.mk_equals (Const (s, T --> HOLogic.natT),
           list_comb (Const (rec_name, fTs @ [T] ---> HOLogic.natT), fs))))
@@ -426,7 +426,7 @@
   in
     thy' |> Theory.add_path big_name |>
     PureThy.add_thmss [(("size", size_thms), [])] |>>
-    Theory.parent_path |> apsnd flat
+    Theory.parent_path |> apsnd List.concat
   end;
 
 fun prove_weak_case_congs new_type_names descr sorts thy =
--- a/src/HOL/Tools/datatype_aux.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/HOL/Tools/datatype_aux.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -71,7 +71,7 @@
 fun message s = if !quiet_mode then () else writeln s;
 
 (* FIXME: move to library ? *)
-fun foldl1 f (x::xs) = foldl f (x, xs);
+fun foldl1 f (x::xs) = Library.foldl f (x, xs);
 
 fun add_path flat_names s = if flat_names then I else Theory.add_path s;
 fun parent_path flat_names = if flat_names then I else Theory.parent_path;
@@ -108,7 +108,7 @@
 
 
 fun cong_tac i st = (case Logic.strip_assums_concl
-  (nth_elem (i - 1, prems_of st)) of
+  (List.nth (prems_of st, i - 1)) of
     _ $ (_ $ (f $ x) $ (g $ y)) =>
       let
         val cong' = lift_rule (st, i) cong;
@@ -128,7 +128,7 @@
   let
     val ts = HOLogic.dest_conj (HOLogic.dest_Trueprop (concl_of indrule));
     val ts' = HOLogic.dest_conj (HOLogic.dest_Trueprop
-      (Logic.strip_imp_concl (nth_elem (i - 1, prems_of st))));
+      (Logic.strip_imp_concl (List.nth (prems_of st, i - 1))));
     val getP = if can HOLogic.dest_imp (hd ts) then
       (apfst SOME) o HOLogic.dest_imp else pair NONE;
     fun abstr (t1, t2) = (case t1 of
@@ -148,14 +148,14 @@
 fun exh_tac exh_thm_of i state =
   let
     val sg = Thm.sign_of_thm state;
-    val prem = nth_elem (i - 1, prems_of state);
+    val prem = List.nth (prems_of state, i - 1);
     val params = Logic.strip_params prem;
     val (_, Type (tname, _)) = hd (rev params);
     val exhaustion = lift_rule (state, i) (exh_thm_of tname);
     val prem' = hd (prems_of exhaustion);
     val _ $ (_ $ lhs $ _) = hd (rev (Logic.strip_assums_hyp prem'));
     val exhaustion' = cterm_instantiate [(cterm_of sg (head_of lhs),
-      cterm_of sg (foldr (fn ((_, T), t) => Abs ("z", T, t))
+      cterm_of sg (Library.foldr (fn ((_, T), t) => Abs ("z", T, t))
         (params, Bound 0)))] exhaustion
   in compose_tac (false, exhaustion', nprems_of exhaustion) i state
   end;
@@ -228,7 +228,7 @@
 
 fun name_of_typ (Type (s, Ts)) =
       let val s' = Sign.base_name s
-      in space_implode "_" (filter (not o equal "") (map name_of_typ Ts) @
+      in space_implode "_" (List.filter (not o equal "") (map name_of_typ Ts) @
         [if Syntax.is_identifier s' then s' else "x"])
       end
   | name_of_typ _ = "";
@@ -242,9 +242,9 @@
              DtRec (find_index (curry op = tname o fst) new_dts)
            else error ("Illegal occurence of recursive type " ^ tname));
 
-fun typ_of_dtyp descr sorts (DtTFree a) = TFree (a, the (assoc (sorts, a)))
+fun typ_of_dtyp descr sorts (DtTFree a) = TFree (a, valOf (assoc (sorts, a)))
   | typ_of_dtyp descr sorts (DtRec i) =
-      let val (s, ds, _) = the (assoc (descr, i))
+      let val (s, ds, _) = valOf (assoc (descr, i))
       in Type (s, map (typ_of_dtyp descr sorts) ds) end
   | typ_of_dtyp descr sorts (DtType (s, ds)) =
       Type (s, map (typ_of_dtyp descr sorts) ds);
@@ -252,8 +252,8 @@
 (* find all non-recursive types in datatype description *)
 
 fun get_nonrec_types descr sorts =
-  map (typ_of_dtyp descr sorts) (foldl (fn (Ts, (_, (_, _, constrs))) =>
-    foldl (fn (Ts', (_, cargs)) =>
+  map (typ_of_dtyp descr sorts) (Library.foldl (fn (Ts, (_, (_, _, constrs))) =>
+    Library.foldl (fn (Ts', (_, cargs)) =>
       filter_out is_rec_type cargs union Ts') (Ts, constrs)) ([], descr));
 
 (* get all recursive types in datatype description *)
@@ -264,22 +264,22 @@
 (* get all branching types *)
 
 fun get_branching_types descr sorts =
-  map (typ_of_dtyp descr sorts) (foldl (fn (Ts, (_, (_, _, constrs))) =>
-    foldl (fn (Ts', (_, cargs)) => foldr op union (map (fst o strip_dtyp)
+  map (typ_of_dtyp descr sorts) (Library.foldl (fn (Ts, (_, (_, _, constrs))) =>
+    Library.foldl (fn (Ts', (_, cargs)) => Library.foldr op union (map (fst o strip_dtyp)
       cargs, Ts')) (Ts, constrs)) ([], descr));
 
-fun get_arities descr = foldl (fn (is, (_, (_, _, constrs))) =>
-  foldl (fn (is', (_, cargs)) => map (length o fst o strip_dtyp)
-    (filter is_rec_type cargs) union is') (is, constrs)) ([], descr);
+fun get_arities descr = Library.foldl (fn (is, (_, (_, _, constrs))) =>
+  Library.foldl (fn (is', (_, cargs)) => map (length o fst o strip_dtyp)
+    (List.filter is_rec_type cargs) union is') (is, constrs)) ([], descr);
 
 (* nonemptiness check for datatypes *)
 
 fun check_nonempty descr =
   let
-    val descr' = flat descr;
+    val descr' = List.concat descr;
     fun is_nonempty_dt is i =
       let
-        val (_, _, constrs) = the (assoc (descr', i));
+        val (_, _, constrs) = valOf (assoc (descr', i));
         fun arg_nonempty (_, DtRec i) = if i mem is then false
               else is_nonempty_dt (i::is) i
           | arg_nonempty _ = true;
@@ -303,8 +303,8 @@
          NONE => typ_error T (tname ^ " is not a datatype - can't use it in\
            \ nested recursion")
        | (SOME {index, descr, ...}) =>
-           let val (_, vars, _) = the (assoc (descr, index));
-               val subst = ((map dest_DtTFree vars) ~~ dts) handle LIST _ =>
+           let val (_, vars, _) = valOf (assoc (descr, index));
+               val subst = ((map dest_DtTFree vars) ~~ dts) handle UnequalLengths =>
                  typ_error T ("Type constructor " ^ tname ^ " used with wrong\
                   \ number of arguments")
            in (i + index, map (fn (j, (tn, args, cs)) => (i + j,
@@ -333,18 +333,18 @@
     (* unfold a constructor *)
 
     fun unfold_constr ((i, constrs, descrs), (cname, cargs)) =
-      let val (i', cargs', descrs') = foldl unfold_arg ((i, [], descrs), cargs)
+      let val (i', cargs', descrs') = Library.foldl unfold_arg ((i, [], descrs), cargs)
       in (i', constrs @ [(cname, cargs')], descrs') end;
 
     (* unfold a single datatype *)
 
     fun unfold_datatype ((i, dtypes, descrs), (j, (tname, tvars, constrs))) =
       let val (i', constrs', descrs') =
-        foldl unfold_constr ((i, [], descrs), constrs)
+        Library.foldl unfold_constr ((i, [], descrs), constrs)
       in (i', dtypes @ [(j, (tname, tvars, constrs'))], descrs')
       end;
 
-    val (i', descr', descrs) = foldl unfold_datatype ((i, [],[]), descr);
+    val (i', descr', descrs) = Library.foldl unfold_datatype ((i, [],[]), descr);
 
   in (descr' :: descrs, i') end;
 
--- a/src/HOL/Tools/datatype_codegen.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/HOL/Tools/datatype_codegen.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -17,7 +17,7 @@
 
 fun mk_tuple [p] = p
   | mk_tuple ps = Pretty.block (Pretty.str "(" ::
-      flat (separate [Pretty.str ",", Pretty.brk 1] (map single ps)) @
+      List.concat (separate [Pretty.str ",", Pretty.brk 1] (map single ps)) @
         [Pretty.str ")"]);
 
 (**** datatype definition ****)
@@ -26,16 +26,16 @@
 
 fun find_nonempty (descr: DatatypeAux.descr) is i =
   let
-    val (_, _, constrs) = the (assoc (descr, i));
+    val (_, _, constrs) = valOf (assoc (descr, i));
     fun arg_nonempty (_, DatatypeAux.DtRec i) = if i mem is then NONE
-          else apsome (curry op + 1 o snd) (find_nonempty descr (i::is) i)
+          else Option.map (curry op + 1 o snd) (find_nonempty descr (i::is) i)
       | arg_nonempty _ = SOME 0;
-    fun max xs = foldl
+    fun max xs = Library.foldl
       (fn (NONE, _) => NONE
         | (SOME i, SOME j) => SOME (Int.max (i, j))
         | (_, NONE) => NONE) (SOME 0, xs);
     val xs = sort (int_ord o pairself snd)
-      (mapfilter (fn (s, dts) => apsome (pair s)
+      (List.mapPartial (fn (s, dts) => Option.map (pair s)
         (max (map (arg_nonempty o DatatypeAux.strip_dtyp) dts))) constrs)
   in case xs of [] => NONE | x :: _ => SOME x end;
 
@@ -44,8 +44,8 @@
     val sg = sign_of thy;
     val tab = DatatypePackage.get_datatypes thy;
 
-    val descr' = filter (can (map DatatypeAux.dest_DtTFree o #2 o snd)) descr;
-    val rtnames = map (#1 o snd) (filter (fn (_, (_, _, cs)) =>
+    val descr' = List.filter (can (map DatatypeAux.dest_DtTFree o #2 o snd)) descr;
+    val rtnames = map (#1 o snd) (List.filter (fn (_, (_, _, cs)) =>
       exists (exists DatatypeAux.is_rec_type o snd) cs) descr');
 
     val (_, (_, _, (cname, _) :: _)) :: _ = descr';
@@ -67,11 +67,11 @@
                (if null tvs then [] else
                   [mk_tuple (map Pretty.str tvs), Pretty.str " "]) @
                [Pretty.str (mk_type_id sg tname ^ " ="), Pretty.brk 1] @
-               flat (separate [Pretty.brk 1, Pretty.str "| "]
+               List.concat (separate [Pretty.brk 1, Pretty.str "| "]
                  (map (fn (cname, ps') => [Pretty.block
                    (Pretty.str (mk_const_id sg cname) ::
                     (if null ps' then [] else
-                     flat ([Pretty.str " of", Pretty.brk 1] ::
+                     List.concat ([Pretty.str " of", Pretty.brk 1] ::
                        separate [Pretty.str " *", Pretty.brk 1]
                          (map single ps'))))]) ps))) :: rest)
           end;
@@ -94,7 +94,7 @@
                  else parens (Pretty.block [Pretty.str (mk_const_id sg cname),
                     Pretty.brk 1, mk_tuple args]),
                  Pretty.str " =", Pretty.brk 1] @
-                 flat (separate [Pretty.str " $", Pretty.brk 1]
+                 List.concat (separate [Pretty.str " $", Pretty.brk 1]
                    ([Pretty.str ("Const (\"" ^ cname ^ "\","), Pretty.brk 1,
                      mk_type false (Ts ---> T), Pretty.str ")"] ::
                     map (fn (x, U) => [Pretty.block [mk_term_of sg false U,
@@ -108,7 +108,7 @@
             val tvs = map DatatypeAux.dest_DtTFree dts;
             val sorts = map (rpair []) tvs;
             val (cs1, cs2) =
-              partition (exists DatatypeAux.is_rec_type o snd) cs;
+              List.partition (exists DatatypeAux.is_rec_type o snd) cs;
             val SOME (cname, _) = find_nonempty descr [i] i;
 
             fun mk_delay p = Pretty.block
@@ -130,7 +130,7 @@
             fun mk_choice [c] = mk_constr "(i-1)" false c
               | mk_choice cs = Pretty.block [Pretty.str "one_of",
                   Pretty.brk 1, Pretty.blk (1, Pretty.str "[" ::
-                  flat (separate [Pretty.str ",", Pretty.fbrk]
+                  List.concat (separate [Pretty.str ",", Pretty.fbrk]
                     (map (single o mk_delay o mk_constr "(i-1)" false) cs)) @
                   [Pretty.str "]"]), Pretty.brk 1, Pretty.str "()"];
 
@@ -155,7 +155,7 @@
                  [Pretty.block [Pretty.str "(case", Pretty.brk 1,
                    Pretty.str "i", Pretty.brk 1, Pretty.str "of",
                    Pretty.brk 1, Pretty.str "0 =>", Pretty.brk 1,
-                   mk_constr "0" true (cname, the (assoc (cs, cname))),
+                   mk_constr "0" true (cname, valOf (assoc (cs, cname))),
                    Pretty.brk 1, Pretty.str "| _ =>", Pretty.brk 1,
                    mk_choice cs1, Pretty.str ")"]]
                else [mk_choice cs2])) ::
@@ -199,18 +199,18 @@
        invoke_codegen thy dep brack (gr, eta_expand c ts (i+1))
     else
       let
-        val ts1 = take (i, ts);
-        val t :: ts2 = drop (i, ts);
-        val names = foldr add_term_names (ts1,
-          map (fst o fst o dest_Var) (foldr add_term_vars (ts1, [])));
-        val (Ts, dT) = split_last (take (i+1, fst (strip_type T)));
+        val ts1 = Library.take (i, ts);
+        val t :: ts2 = Library.drop (i, ts);
+        val names = Library.foldr add_term_names (ts1,
+          map (fst o fst o dest_Var) (Library.foldr add_term_vars (ts1, [])));
+        val (Ts, dT) = split_last (Library.take (i+1, fst (strip_type T)));
 
         fun pcase gr [] [] [] = ([], gr)
           | pcase gr ((cname, cargs)::cs) (t::ts) (U::Us) =
               let
                 val j = length cargs;
                 val xs = variantlist (replicate j "x", names);
-                val Us' = take (j, fst (strip_type U));
+                val Us' = Library.take (j, fst (strip_type U));
                 val frees = map Free (xs ~~ Us');
                 val (gr0, cp) = invoke_codegen thy dep false
                   (gr, list_comb (Const (cname, Us' ---> dT), frees));
@@ -222,7 +222,7 @@
               end;
 
         val (ps1, gr1) = pcase gr constrs ts1 Ts;
-        val ps = flat (separate [Pretty.brk 1, Pretty.str "| "] ps1);
+        val ps = List.concat (separate [Pretty.brk 1, Pretty.str "| "] ps1);
         val (gr2, p) = invoke_codegen thy dep false (gr1, t);
         val (gr3, ps2) = foldl_map (invoke_codegen thy dep true) (gr2, ts2)
       in (gr3, (if not (null ts2) andalso brack then parens else I)
@@ -257,15 +257,15 @@
    (c as Const (s, T), ts) =>
        (case find_first (fn (_, {index, descr, case_name, ...}) =>
          s = case_name orelse
-           is_some (assoc (#3 (the (assoc (descr, index))), s)))
+           isSome (assoc (#3 (valOf (assoc (descr, index))), s)))
              (Symtab.dest (DatatypePackage.get_datatypes thy)) of
           NONE => NONE
         | SOME (tname, {index, descr, ...}) =>
-           if is_some (get_assoc_code thy s T) then NONE else
+           if isSome (get_assoc_code thy s T) then NONE else
            let val SOME (_, _, constrs) = assoc (descr, index)
            in (case (assoc (constrs, s), strip_type T) of
                (NONE, _) => SOME (pretty_case thy gr dep brack
-                 (#3 (the (assoc (descr, index)))) c ts)
+                 (#3 (valOf (assoc (descr, index)))) c ts)
              | (SOME args, (_, Type _)) => SOME (pretty_constr thy
                  (fst (invoke_tycodegen thy dep false (gr, snd (strip_type T))))
                  dep brack args c ts)
@@ -277,7 +277,7 @@
       (case Symtab.lookup (DatatypePackage.get_datatypes thy, s) of
          NONE => NONE
        | SOME {descr, ...} =>
-           if is_some (get_assoc_type thy s) then NONE else
+           if isSome (get_assoc_type thy s) then NONE else
            let val (gr', ps) = foldl_map
              (invoke_tycodegen thy dep false) (gr, Ts)
            in SOME (add_dt_defs thy dep gr' descr,
--- a/src/HOL/Tools/datatype_package.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/HOL/Tools/datatype_package.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -125,15 +125,15 @@
 
 fun constrs_of_sg sg tname = (case datatype_info_sg sg tname of
    SOME {index, descr, ...} =>
-     let val (_, _, constrs) = the (assoc (descr, index))
-     in SOME (map (fn (cname, _) => Const (cname, the (Sign.const_type sg cname))) constrs)
+     let val (_, _, constrs) = valOf (assoc (descr, index))
+     in SOME (map (fn (cname, _) => Const (cname, valOf (Sign.const_type sg cname))) constrs)
      end
  | _ => NONE);
 
 val constrs_of = constrs_of_sg o Theory.sign_of;
 
 fun case_const_of thy tname = (case datatype_info thy tname of
-   SOME {case_name, ...} => SOME (Const (case_name, the (Sign.const_type
+   SOME {case_name, ...} => SOME (Const (case_name, valOf (Sign.const_type
      (Theory.sign_of thy) case_name)))
  | _ => NONE);
 
@@ -169,7 +169,7 @@
 fun occs_in_prems tacf vars =
   SUBGOAL (fn (Bi, i) =>
            (if  exists (fn Free (a, _) => a mem vars)
-                      (foldr add_term_frees (#2 (strip_context Bi), []))
+                      (Library.foldr add_term_frees (#2 (strip_context Bi), []))
              then warning "Induction variable occurs also among premises!"
              else ();
             tacf i));
@@ -182,9 +182,9 @@
 fun prep_var (Var (ixn, _), SOME x) = SOME (ixn, x)
   | prep_var _ = NONE;
 
-fun prep_inst (concl, xs) =	(*exception LIST*)
+fun prep_inst (concl, xs) =	(*exception UnequalLengths *)
   let val vs = InductAttrib.vars_of concl
-  in mapfilter prep_var (Library.drop (length vs - length xs, vs) ~~ xs) end;
+  in List.mapPartial prep_var (Library.drop (length vs - length xs, vs) ~~ xs) end;
 
 in
 
@@ -196,11 +196,11 @@
       (case opt_rule of
         SOME r => (r, "Induction rule")
       | NONE =>
-          let val tn = find_tname (hd (mapfilter I (flat varss))) Bi
+          let val tn = find_tname (hd (List.mapPartial I (List.concat varss))) Bi
           in (#induction (datatype_info_sg_err sign tn), "Induction rule for type " ^ tn) end);
 
     val concls = HOLogic.dest_concls (Thm.concl_of rule);
-    val insts = flat (map prep_inst (concls ~~ varss)) handle LIST _ =>
+    val insts = List.concat (map prep_inst (concls ~~ varss)) handle UnequalLengths =>
       error (rule_name ^ " has different numbers of variables");
   in occs_in_prems (inst_tac insts rule) (map #2 insts) i state end;
 
@@ -272,20 +272,20 @@
 local
 
 fun dt_recs (DtTFree _) = []
-  | dt_recs (DtType (_, dts)) = flat (map dt_recs dts)
+  | dt_recs (DtType (_, dts)) = List.concat (map dt_recs dts)
   | dt_recs (DtRec i) = [i];
 
 fun dt_cases (descr: descr) (_, args, constrs) =
   let
-    fun the_bname i = Sign.base_name (#1 (the (assoc (descr, i))));
-    val bnames = map the_bname (distinct (flat (map dt_recs args)));
+    fun the_bname i = Sign.base_name (#1 (valOf (assoc (descr, i))));
+    val bnames = map the_bname (distinct (List.concat (map dt_recs args)));
   in map (fn (c, _) => space_implode "_" (Sign.base_name c :: bnames)) constrs end;
 
 
 fun induct_cases descr =
-  DatatypeProp.indexify_names (flat (map (dt_cases descr) (map #2 descr)));
+  DatatypeProp.indexify_names (List.concat (map (dt_cases descr) (map #2 descr)));
 
-fun exhaust_cases descr i = dt_cases descr (the (assoc (descr, i)));
+fun exhaust_cases descr i = dt_cases descr (valOf (assoc (descr, i)));
 
 in
 
@@ -293,18 +293,18 @@
 
 fun mk_case_names_exhausts descr new =
   map (RuleCases.case_names o exhaust_cases descr o #1)
-    (filter (fn ((_, (name, _, _))) => name mem_string new) descr);
+    (List.filter (fn ((_, (name, _, _))) => name mem_string new) descr);
 
 end;
 
 fun add_rules simps case_thms size_thms rec_thms inject distinct
                   weak_case_congs cong_att =
   (#1 o PureThy.add_thmss [(("simps", simps), []),
-    (("", flat case_thms @ size_thms @ 
-          flat distinct  @ rec_thms), [Simplifier.simp_add_global]),
+    (("", List.concat case_thms @ size_thms @ 
+          List.concat distinct  @ rec_thms), [Simplifier.simp_add_global]),
     (("", size_thms @ rec_thms), [RecfunCodegen.add]),
-    (("", flat inject),               [iff_add_global]),
-    (("", flat distinct RL [notE]),   [Classical.safe_elim_global]),
+    (("", List.concat inject),               [iff_add_global]),
+    (("", List.concat distinct RL [notE]),   [Classical.safe_elim_global]),
     (("", weak_case_congs),           [cong_att])]);
 
 
@@ -325,7 +325,7 @@
        (("", exhaustion), [InductAttrib.cases_type_global name])];
     fun unnamed_rule i =
       (("", proj i induction), [InductAttrib.induct_type_global ""]);
-    val rules = flat (map named_rules infos) @ map unnamed_rule (length infos upto n - 1);
+    val rules = List.concat (map named_rules infos) @ map unnamed_rule (length infos upto n - 1);
   in #1 o PureThy.add_thms rules end;
 
 
@@ -393,7 +393,7 @@
 fun case_tr sg [t, u] =
     let
       fun case_error s name ts = raise TERM ("Error in case expression" ^
-        if_none (apsome (curry op ^ " for datatype ") name) "" ^ ":\n" ^ s, ts);
+        getOpt (Option.map (curry op ^ " for datatype ") name, "") ^ ":\n" ^ s, ts);
       fun dest_case1 (Const ("_case1", _) $ t $ u) = (case strip_comb t of
             (Const (s, _), ts) => (Sign.intern_const sg s, ts)
           | (Free (s, _), ts) => (Sign.intern_const sg s, ts)
@@ -413,13 +413,13 @@
             Syntax.const "split" $ abstr (x, abstr (y, body))
         | abstr (t, _) = case_error "Illegal pattern" NONE [t];
     in case find_first (fn (_, {descr, index, ...}) =>
-      exists (equal cname o fst) (#3 (snd (nth_elem (index, descr))))) tab of
+      exists (equal cname o fst) (#3 (snd (List.nth (descr, index))))) tab of
         NONE => case_error ("Not a datatype constructor: " ^ cname) NONE [u]
       | SOME (tname, {descr, case_name, index, ...}) =>
         let
           val _ = if exists (equal "dummy_pattern" o fst o fst) cases' then
             case_error "Illegal occurrence of '_' dummy pattern" (SOME tname) [u] else ();
-          val (_, (_, dts, constrs)) = nth_elem (index, descr);
+          val (_, (_, dts, constrs)) = List.nth (descr, index);
           val sorts = map (rpair [] o dest_DtTFree) dts;
           fun find_case (cases, (s, dt)) =
             (case find_first (equal s o fst o fst) cases' of
@@ -431,7 +431,7 @@
                  if length dt <> length vs then
                     case_error ("Wrong number of arguments for constructor " ^ s)
                       (SOME tname) vs
-                 else (cases \ c, foldr abstr (vs, t)))
+                 else (cases \ c, Library.foldr abstr (vs, t)))
           val (cases'', fs) = foldl_map find_case (cases', constrs)
         in case (cases'', length constrs = length cases', default) of
             ([], true, SOME _) =>
@@ -473,7 +473,7 @@
           NONE => (body, [cname]) :: cs
         | SOME cnames => overwrite (cs, (body, cnames @ [cname])));
     val cases' = sort (int_ord o Library.swap o pairself (length o snd))
-      (foldl count_cases ([], cases));
+      (Library.foldl count_cases ([], cases));
     fun mk_case1 (cname, (vs, body), _) = Syntax.const "_case1" $
       list_comb (Syntax.const cname, vs) $ body;
   in
@@ -490,7 +490,7 @@
              [("dummy_pattern", ([], default), false)]))
   end;
 
-fun make_case_tr' case_names descr = flat (map
+fun make_case_tr' case_names descr = List.concat (map
   (fn ((_, (_, _, constrs)), case_name) => map (rpair (case_tr' constrs))
     (NameSpace.accesses' case_name)) (descr ~~ case_names));
 
@@ -542,7 +542,7 @@
 (********************* axiomatic introduction of datatypes ********************)
 
 fun add_and_get_axioms_atts label tnames attss ts thy =
-  foldr (fn (((tname, atts), t), (thy', axs)) =>
+  Library.foldr (fn (((tname, atts), t), (thy', axs)) =>
     let
       val (thy'', [ax]) = thy' |>
         Theory.add_path tname |>
@@ -554,7 +554,7 @@
   add_and_get_axioms_atts label tnames (replicate (length tnames) []);
 
 fun add_and_get_axiomss label tnames tss thy =
-  foldr (fn ((tname, ts), (thy', axss)) =>
+  Library.foldr (fn ((tname, ts), (thy', axss)) =>
     let
       val (thy'', [axs]) = thy' |>
         Theory.add_path tname |>
@@ -565,10 +565,10 @@
 fun add_datatype_axm flat_names new_type_names descr sorts types_syntax constr_syntax dt_info
     case_names_induct case_names_exhausts thy =
   let
-    val descr' = flat descr;
+    val descr' = List.concat descr;
     val recTs = get_rec_types descr' sorts;
-    val used = foldr add_typ_tfree_names (recTs, []);
-    val newTs = take (length (hd descr), recTs);
+    val used = Library.foldr add_typ_tfree_names (recTs, []);
+    val newTs = Library.take (length (hd descr), recTs);
 
     val no_size = exists (fn (_, (_, _, constrs)) => exists (fn (_, cargs) => exists
       (fn dt => is_rec_type dt andalso not (null (fst (strip_dtyp dt))))
@@ -591,7 +591,7 @@
         (1 upto (length descr')));
 
     val size_names = DatatypeProp.indexify_names
-      (map (fn T => name_of_typ T ^ "_size") (drop (length (hd descr), recTs)));
+      (map (fn T => name_of_typ T ^ "_size") (Library.drop (length (hd descr), recTs)));
 
     val freeT = TFree (variant used "'t", HOLogic.typeS);
     val case_fn_Ts = map (fn (i, (_, _, constrs)) =>
@@ -605,7 +605,7 @@
 
       (** new types **)
 
-      curry (foldr (fn (((name, mx), tvs), thy') => thy' |>
+      curry (Library.foldr (fn (((name, mx), tvs), thy') => thy' |>
           TypedefPackage.add_typedecls [(name, tvs, mx)]))
         (types_syntax ~~ tyvars) |>
       add_path flat_names (space_implode "_" new_type_names) |>
@@ -631,12 +631,12 @@
 
       (if no_size then I else Theory.add_consts_i (map (fn (s, T) =>
         (Sign.base_name s, T --> HOLogic.natT, NoSyn))
-          (size_names ~~ drop (length (hd descr), recTs)))) |>
+          (size_names ~~ Library.drop (length (hd descr), recTs)))) |>
 
       (** constructors **)
 
       parent_path flat_names |>
-      curry (foldr (fn (((((_, (_, _, constrs)), T), tname),
+      curry (Library.foldr (fn (((((_, (_, _, constrs)), T), tname),
         constr_syntax'), thy') => thy' |>
           add_path flat_names tname |>
             Theory.add_consts_i (map (fn ((_, cargs), (cname, mx)) =>
@@ -686,7 +686,7 @@
         exhaustion ~~ replicate (length (hd descr)) QuickAndDirty ~~ inject ~~
           nchotomys ~~ case_congs ~~ weak_case_congs);
 
-    val simps = flat (distinct @ inject @ case_thms) @ size_thms @ rec_thms;
+    val simps = List.concat (distinct @ inject @ case_thms) @ size_thms @ rec_thms;
     val split_thms = split ~~ split_asm;
 
     val thy12 = thy11 |>
@@ -694,7 +694,7 @@
       Theory.add_path (space_implode "_" new_type_names) |>
       add_rules simps case_thms size_thms rec_thms inject distinct
                 weak_case_congs Simplifier.cong_add_global |> 
-      put_datatypes (foldr Symtab.update (dt_infos, dt_info)) |>
+      put_datatypes (Library.foldr Symtab.update (dt_infos, dt_info)) |>
       add_cases_induct dt_infos induct |>
       Theory.parent_path |>
       (#1 o store_thmss "splits" new_type_names (map (fn (x, y) => [x, y]) split_thms)) |>
@@ -741,18 +741,18 @@
     val (thy11, size_thms) = DatatypeAbsProofs.prove_size_thms flat_names new_type_names
       descr sorts reccomb_names rec_thms thy10;
 
-    val dt_infos = map (make_dt_info (flat descr) induct reccomb_names rec_thms)
+    val dt_infos = map (make_dt_info (List.concat descr) induct reccomb_names rec_thms)
       ((0 upto length (hd descr) - 1) ~~ (hd descr) ~~ case_names ~~ case_thms ~~
         casedist_thms ~~ simproc_dists ~~ inject ~~ nchotomys ~~ case_congs ~~ weak_case_congs);
 
-    val simps = flat (distinct @ inject @ case_thms) @ size_thms @ rec_thms;
+    val simps = List.concat (distinct @ inject @ case_thms) @ size_thms @ rec_thms;
 
     val thy12 = thy11 |>
       Theory.add_advanced_trfuns ([], [], make_case_tr' case_names (hd descr), []) |>
       Theory.add_path (space_implode "_" new_type_names) |>
       add_rules simps case_thms size_thms rec_thms inject distinct
                 weak_case_congs (Simplifier.change_global_ss (op addcongs)) |> 
-      put_datatypes (foldr Symtab.update (dt_infos, dt_info)) |>
+      put_datatypes (Library.foldr Symtab.update (dt_infos, dt_info)) |>
       add_cases_induct dt_infos induct |>
       Theory.parent_path |>
       (#1 o store_thmss "splits" new_type_names (map (fn (x, y) => [x, y]) split_thms)) |>
@@ -778,7 +778,7 @@
     val _ = Theory.requires thy0 "Inductive" "datatype representations";
 
     fun app_thmss srcs thy = foldl_map (fn (thy, x) => apply_theorems x thy) (thy, srcs);
-    fun app_thm src thy = apsnd Library.hd (apply_theorems [src] thy);
+    fun app_thm src thy = apsnd hd (apply_theorems [src] thy);
 
     val (((thy1, induction), inject), distinct) = thy0
       |> app_thmss raw_distinct
@@ -796,7 +796,7 @@
       | get_typ t = err t;
 
     val dtnames = map get_typ (HOLogic.dest_conj (HOLogic.dest_Trueprop (Thm.concl_of induction')));
-    val new_type_names = if_none alt_names (map fst dtnames);
+    val new_type_names = getOpt (alt_names, map fst dtnames);
 
     fun get_constr t = (case Logic.strip_assums_concl t of
         _ $ (_ $ t') => (case head_of t' of
@@ -854,13 +854,13 @@
       ((0 upto length descr - 1) ~~ descr ~~ case_names ~~ case_thms ~~ casedist_thms ~~
         map FewConstrs distinct ~~ inject ~~ nchotomys ~~ case_congs ~~ weak_case_congs);
 
-    val simps = flat (distinct @ inject @ case_thms) @ size_thms @ rec_thms;
+    val simps = List.concat (distinct @ inject @ case_thms) @ size_thms @ rec_thms;
 
     val thy11 = thy10 |>
       Theory.add_advanced_trfuns ([], [], make_case_tr' case_names descr, []) |>
       add_rules simps case_thms size_thms rec_thms inject distinct
                 weak_case_congs (Simplifier.change_global_ss (op addcongs)) |> 
-      put_datatypes (foldr Symtab.update (dt_infos, dt_info)) |>
+      put_datatypes (Library.foldr Symtab.update (dt_infos, dt_info)) |>
       add_cases_induct dt_infos induction' |>
       Theory.parent_path |>
       (#1 o store_thmss "splits" new_type_names (map (fn (x, y) => [x, y]) split_thms)) |>
@@ -915,8 +915,8 @@
       let
         fun prep_constr ((constrs, constr_syntax', sorts'), (cname, cargs, mx')) =
           let
-            val (cargs', sorts'') = foldl (prep_typ sign) (([], sorts'), cargs);
-            val _ = (case foldr add_typ_tfree_names (cargs', []) \\ tvs of
+            val (cargs', sorts'') = Library.foldl (prep_typ sign) (([], sorts'), cargs);
+            val _ = (case Library.foldr add_typ_tfree_names (cargs', []) \\ tvs of
                 [] => ()
               | vs => error ("Extra type variables on rhs: " ^ commas vs))
           in (constrs @ [((if flat_names then Sign.full_name sign else
@@ -928,7 +928,7 @@
               " of datatype " ^ tname);
 
         val (constrs', constr_syntax', sorts') =
-          foldl prep_constr (([], [], sorts), constrs)
+          Library.foldl prep_constr (([], [], sorts), constrs)
 
       in
         case duplicates (map fst constrs') of
@@ -940,7 +940,7 @@
              " in datatype " ^ tname)
       end;
 
-    val (dts', constr_syntax, sorts', i) = foldl prep_dt_spec (([], [], [], 0), dts);
+    val (dts', constr_syntax, sorts', i) = Library.foldl prep_dt_spec (([], [], [], 0), dts);
     val sorts = sorts' @ (map (rpair (Sign.defaultS sign)) (tyvars \\ map fst sorts'));
     val dt_info = get_datatypes thy;
     val (descr, _) = unfold_datatypes sign dts' sorts dt_info dts' i;
@@ -948,7 +948,7 @@
       if err then error ("NONEmptiness check failed for datatype " ^ s)
       else raise exn;
 
-    val descr' = flat descr;
+    val descr' = List.concat descr;
     val case_names_induct = mk_case_names_induct descr';
     val case_names_exhausts = mk_case_names_exhausts descr' (map #1 new_dts);
   in
--- a/src/HOL/Tools/datatype_prop.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/HOL/Tools/datatype_prop.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -64,7 +64,7 @@
 
 fun make_injs descr sorts =
   let
-    val descr' = flat descr;
+    val descr' = List.concat descr;
 
     fun make_inj T ((cname, cargs), injs) =
       if null cargs then injs else
@@ -80,22 +80,22 @@
              (map HOLogic.mk_eq (frees ~~ frees')))))::injs
         end;
 
-  in map (fn (d, T) => foldr (make_inj T) (#3 (snd d), []))
-    ((hd descr) ~~ take (length (hd descr), get_rec_types descr' sorts))
+  in map (fn (d, T) => Library.foldr (make_inj T) (#3 (snd d), []))
+    ((hd descr) ~~ Library.take (length (hd descr), get_rec_types descr' sorts))
   end;
 
 (********************************* induction **********************************)
 
 fun make_ind descr sorts =
   let
-    val descr' = flat descr;
+    val descr' = List.concat descr;
     val recTs = get_rec_types descr' sorts;
     val pnames = if length descr' = 1 then ["P"]
       else map (fn i => "P" ^ string_of_int i) (1 upto length descr');
 
     fun make_pred i T =
       let val T' = T --> HOLogic.boolT
-      in Free (nth_elem (i, pnames), T') end;
+      in Free (List.nth (pnames, i), T') end;
 
     fun make_ind_prem k T (cname, cargs) =
       let
@@ -105,11 +105,11 @@
             (make_pred (body_index dt) U $ app_bnds (Free (s, T)) (length Us)))
           end;
 
-        val recs = filter is_rec_type cargs;
+        val recs = List.filter is_rec_type cargs;
         val Ts = map (typ_of_dtyp descr' sorts) cargs;
         val recTs' = map (typ_of_dtyp descr' sorts) recs;
         val tnames = variantlist (make_tnames Ts, pnames);
-        val rec_tnames = map fst (filter (is_rec_type o snd) (tnames ~~ cargs));
+        val rec_tnames = map fst (List.filter (is_rec_type o snd) (tnames ~~ cargs));
         val frees = tnames ~~ Ts;
         val prems = map mk_prem (recs ~~ rec_tnames ~~ recTs');
 
@@ -118,7 +118,7 @@
           list_comb (Const (cname, Ts ---> T), map Free frees))))
       end;
 
-    val prems = flat (map (fn ((i, (_, _, constrs)), T) =>
+    val prems = List.concat (map (fn ((i, (_, _, constrs)), T) =>
       map (make_ind_prem i T) constrs) (descr' ~~ recTs));
     val tnames = make_tnames recTs;
     val concl = HOLogic.mk_Trueprop (foldr1 (HOLogic.mk_binop "op &")
@@ -131,7 +131,7 @@
 
 fun make_casedists descr sorts =
   let
-    val descr' = flat descr;
+    val descr' = List.concat descr;
 
     fun make_casedist_prem T (cname, cargs) =
       let
@@ -149,29 +149,29 @@
       end
 
   in map make_casedist
-    ((hd descr) ~~ take (length (hd descr), get_rec_types descr' sorts))
+    ((hd descr) ~~ Library.take (length (hd descr), get_rec_types descr' sorts))
   end;
 
 (*************** characteristic equations for primrec combinator **************)
 
 fun make_primrec_Ts descr sorts used =
   let
-    val descr' = flat descr;
+    val descr' = List.concat descr;
 
     val rec_result_Ts = map TFree (variantlist (replicate (length descr') "'t", used) ~~
       replicate (length descr') HOLogic.typeS);
 
-    val reccomb_fn_Ts = flat (map (fn (i, (_, _, constrs)) =>
+    val reccomb_fn_Ts = List.concat (map (fn (i, (_, _, constrs)) =>
       map (fn (_, cargs) =>
         let
           val Ts = map (typ_of_dtyp descr' sorts) cargs;
-          val recs = filter (is_rec_type o fst) (cargs ~~ Ts);
+          val recs = List.filter (is_rec_type o fst) (cargs ~~ Ts);
 
           fun mk_argT (dt, T) =
-            binder_types T ---> nth_elem (body_index dt, rec_result_Ts);
+            binder_types T ---> List.nth (rec_result_Ts, body_index dt);
 
           val argTs = Ts @ map mk_argT recs
-        in argTs ---> nth_elem (i, rec_result_Ts)
+        in argTs ---> List.nth (rec_result_Ts, i)
         end) constrs) descr');
 
   in (rec_result_Ts, reccomb_fn_Ts) end;
@@ -180,9 +180,9 @@
   let
     val sign = Theory.sign_of thy;
 
-    val descr' = flat descr;
+    val descr' = List.concat descr;
     val recTs = get_rec_types descr' sorts;
-    val used = foldr add_typ_tfree_names (recTs, []);
+    val used = Library.foldr add_typ_tfree_names (recTs, []);
 
     val (rec_result_Ts, reccomb_fn_Ts) = make_primrec_Ts descr sorts used;
 
@@ -200,18 +200,18 @@
 
     fun make_primrec T comb_t ((ts, f::fs), (cname, cargs)) =
       let
-        val recs = filter is_rec_type cargs;
+        val recs = List.filter is_rec_type cargs;
         val Ts = map (typ_of_dtyp descr' sorts) cargs;
         val recTs' = map (typ_of_dtyp descr' sorts) recs;
         val tnames = make_tnames Ts;
-        val rec_tnames = map fst (filter (is_rec_type o snd) (tnames ~~ cargs));
+        val rec_tnames = map fst (List.filter (is_rec_type o snd) (tnames ~~ cargs));
         val frees = map Free (tnames ~~ Ts);
         val frees' = map Free (rec_tnames ~~ recTs');
 
         fun mk_reccomb ((dt, T), t) =
           let val (Us, U) = strip_type T
           in list_abs (map (pair "x") Us,
-            nth_elem (body_index dt, reccombs) $ app_bnds t (length Us))
+            List.nth (reccombs, body_index dt) $ app_bnds t (length Us))
           end;
 
         val reccombs' = map mk_reccomb (recs ~~ recTs' ~~ frees')
@@ -221,8 +221,8 @@
          list_comb (f, frees @ reccombs')))], fs)
       end
 
-  in fst (foldl (fn (x, ((dt, T), comb_t)) =>
-    foldl (make_primrec T comb_t) (x, #3 (snd dt)))
+  in fst (Library.foldl (fn (x, ((dt, T), comb_t)) =>
+    Library.foldl (make_primrec T comb_t) (x, #3 (snd dt)))
       (([], rec_fns), descr' ~~ recTs ~~ reccombs))
   end;
 
@@ -230,10 +230,10 @@
 
 fun make_case_combs new_type_names descr sorts thy fname =
   let
-    val descr' = flat descr;
+    val descr' = List.concat descr;
     val recTs = get_rec_types descr' sorts;
-    val used = foldr add_typ_tfree_names (recTs, []);
-    val newTs = take (length (hd descr), recTs);
+    val used = Library.foldr add_typ_tfree_names (recTs, []);
+    val newTs = Library.take (length (hd descr), recTs);
     val T' = TFree (variant used "'t", HOLogic.typeS);
 
     val case_fn_Ts = map (fn (i, (_, _, constrs)) =>
@@ -254,9 +254,9 @@
 
 fun make_cases new_type_names descr sorts thy =
   let
-    val descr' = flat descr;
+    val descr' = List.concat descr;
     val recTs = get_rec_types descr' sorts;
-    val newTs = take (length (hd descr), recTs);
+    val newTs = Library.take (length (hd descr), recTs);
 
     fun make_case T comb_t ((cname, cargs), f) =
       let
@@ -276,9 +276,9 @@
 
 fun make_distincts new_type_names descr sorts thy =
   let
-    val descr' = flat descr;
+    val descr' = List.concat descr;
     val recTs = get_rec_types descr' sorts;
-    val newTs = take (length (hd descr), recTs);
+    val newTs = Library.take (length (hd descr), recTs);
 
     (**** number of constructors < dtK : C_i ... ~= C_j ... ****)
 
@@ -315,10 +315,10 @@
 
 fun make_splits new_type_names descr sorts thy =
   let
-    val descr' = flat descr;
+    val descr' = List.concat descr;
     val recTs = get_rec_types descr' sorts;
-    val used' = foldr add_typ_tfree_names (recTs, []);
-    val newTs = take (length (hd descr), recTs);
+    val used' = Library.foldr add_typ_tfree_names (recTs, []);
+    val newTs = Library.take (length (hd descr), recTs);
     val T' = TFree (variant used' "'t", HOLogic.typeS);
     val P = Free ("P", T' --> HOLogic.boolT);
 
@@ -334,13 +334,13 @@
             val eqn = HOLogic.mk_eq (Free ("x", T),
               list_comb (Const (cname, Ts ---> T), frees));
             val P' = P $ list_comb (f, frees)
-          in ((foldr (fn (Free (s, T), t) => HOLogic.mk_all (s, T, t))
+          in ((Library.foldr (fn (Free (s, T), t) => HOLogic.mk_all (s, T, t))
                 (frees, HOLogic.imp $ eqn $ P'))::t1s,
-              (foldr (fn (Free (s, T), t) => HOLogic.mk_exists (s, T, t))
+              (Library.foldr (fn (Free (s, T), t) => HOLogic.mk_exists (s, T, t))
                 (frees, HOLogic.conj $ eqn $ (HOLogic.Not $ P')))::t2s)
           end;
 
-        val (t1s, t2s) = foldr process_constr (constrs ~~ fs, ([], []));
+        val (t1s, t2s) = Library.foldr process_constr (constrs ~~ fs, ([], []));
         val lhs = P $ (comb_t $ Free ("x", T))
       in
         (HOLogic.mk_Trueprop (HOLogic.mk_eq (lhs, mk_conj t1s)),
@@ -356,13 +356,13 @@
 
 fun make_size descr sorts thy =
   let
-    val descr' = flat descr;
+    val descr' = List.concat descr;
     val recTs = get_rec_types descr' sorts;
 
     val size_name = "Nat.size";
     val size_names = replicate (length (hd descr)) size_name @
       map (Sign.intern_const (Theory.sign_of thy)) (indexify_names
-        (map (fn T => name_of_typ T ^ "_size") (drop (length (hd descr), recTs))));
+        (map (fn T => name_of_typ T ^ "_size") (Library.drop (length (hd descr), recTs))));
     val size_consts = map (fn (s, T) =>
       Const (s, T --> HOLogic.natT)) (size_names ~~ recTs);
 
@@ -370,12 +370,12 @@
 
     fun make_size_eqn size_const T (cname, cargs) =
       let
-        val recs = filter is_rec_type cargs;
+        val recs = List.filter is_rec_type cargs;
         val Ts = map (typ_of_dtyp descr' sorts) cargs;
         val recTs = map (typ_of_dtyp descr' sorts) recs;
         val tnames = make_tnames Ts;
-        val rec_tnames = map fst (filter (is_rec_type o snd) (tnames ~~ cargs));
-        val ts = map (fn ((r, s), T) => nth_elem (dest_DtRec r, size_consts) $
+        val rec_tnames = map fst (List.filter (is_rec_type o snd) (tnames ~~ cargs));
+        val ts = map (fn ((r, s), T) => List.nth (size_consts, dest_DtRec r) $
           Free (s, T)) (recs ~~ rec_tnames ~~ recTs);
         val t = if ts = [] then HOLogic.zero else
           foldl1 plus (ts @ [HOLogic.mk_nat 1])
@@ -385,7 +385,7 @@
       end
 
   in
-    flat (map (fn (((_, (_, _, constrs)), size_const), T) =>
+    List.concat (map (fn (((_, (_, _, constrs)), size_const), T) =>
       map (make_size_eqn size_const T) constrs) (descr' ~~ size_consts ~~ recTs))
   end;
 
@@ -465,9 +465,9 @@
 
 fun make_nchotomys descr sorts =
   let
-    val descr' = flat descr;
+    val descr' = List.concat descr;
     val recTs = get_rec_types descr' sorts;
-    val newTs = take (length (hd descr), recTs);
+    val newTs = Library.take (length (hd descr), recTs);
 
     fun mk_eqn T (cname, cargs) =
       let
@@ -475,7 +475,7 @@
         val tnames = variantlist (make_tnames Ts, ["v"]);
         val frees = tnames ~~ Ts
       in
-        foldr (fn ((s, T'), t) => HOLogic.mk_exists (s, T', t))
+        Library.foldr (fn ((s, T'), t) => HOLogic.mk_exists (s, T', t))
           (frees, HOLogic.mk_eq (Free ("v", T),
             list_comb (Const (cname, Ts ---> T), map Free frees)))
       end
--- a/src/HOL/Tools/datatype_realizer.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/HOL/Tools/datatype_realizer.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -53,23 +53,23 @@
 
     fun make_pred i T U r x =
       if i mem is then
-        Free (nth_elem (i, pnames), T --> U --> HOLogic.boolT) $ r $ x
-      else Free (nth_elem (i, pnames), U --> HOLogic.boolT) $ x;
+        Free (List.nth (pnames, i), T --> U --> HOLogic.boolT) $ r $ x
+      else Free (List.nth (pnames, i), U --> HOLogic.boolT) $ x;
 
     fun mk_all i s T t =
       if i mem is then list_all_free ([(s, T)], t) else t;
 
-    val (prems, rec_fns) = split_list (flat (snd (foldl_map
+    val (prems, rec_fns) = split_list (List.concat (snd (foldl_map
       (fn (j, ((i, (_, _, constrs)), T)) => foldl_map (fn (j, (cname, cargs)) =>
         let
           val Ts = map (typ_of_dtyp descr sorts) cargs;
           val tnames = variantlist (DatatypeProp.make_tnames Ts, pnames);
-          val recs = filter (is_rec_type o fst o fst) (cargs ~~ tnames ~~ Ts);
+          val recs = List.filter (is_rec_type o fst o fst) (cargs ~~ tnames ~~ Ts);
           val frees = tnames ~~ Ts;
 
           fun mk_prems vs [] = 
                 let
-                  val rT = nth_elem (i, rec_result_Ts);
+                  val rT = List.nth (rec_result_Ts, i);
                   val vs' = filter_out is_unit vs;
                   val f = mk_Free "f" (map fastype_of vs' ---> rT) j;
                   val f' = Pattern.eta_contract (list_abs_free
@@ -83,7 +83,7 @@
                   val k = body_index dt;
                   val (Us, U) = strip_type T;
                   val i = length Us;
-                  val rT = nth_elem (k, rec_result_Ts);
+                  val rT = List.nth (rec_result_Ts, k);
                   val r = Free ("r" ^ s, Us ---> rT);
                   val (p, f) = mk_prems (vs @ [r]) ds
                 in (mk_all k ("r" ^ s) (Us ---> rT) (Logic.mk_implies
@@ -107,7 +107,7 @@
       (list_comb (Const (s, fTs ---> T --> U), rec_fns) $ Bound 0) (Bound 0)))
         (descr ~~ recTs ~~ rec_result_Ts ~~ rec_names);
     val r = if null is then Extraction.nullt else
-      foldr1 HOLogic.mk_prod (mapfilter (fn (((((i, _), T), U), s), tname) =>
+      foldr1 HOLogic.mk_prod (List.mapPartial (fn (((((i, _), T), U), s), tname) =>
         if i mem is then SOME
           (list_comb (Const (s, fTs ---> T --> U), rec_fns) $ Free (tname, T))
         else NONE) (descr ~~ recTs ~~ rec_result_Ts ~~ rec_names ~~ tnames));
@@ -130,22 +130,22 @@
 
     val {path, ...} = Sign.rep_sg sg;
     val ind_name = Thm.name_of_thm induction;
-    val vs = map (fn i => nth_elem (i, pnames)) is;
+    val vs = map (fn i => List.nth (pnames, i)) is;
     val (thy', thm') = thy
       |> Theory.absolute_path
       |> PureThy.store_thm
         ((space_implode "_" (ind_name :: vs @ ["correctness"]), thm), [])
-      |>> Theory.add_path (NameSpace.pack (if_none path []));
+      |>> Theory.add_path (NameSpace.pack (getOpt (path,[])));
 
     val ivs = Drule.vars_of_terms
       [Logic.varify (DatatypeProp.make_ind [descr] sorts)];
     val rvs = Drule.vars_of_terms [prop_of thm'];
     val ivs1 = map Var (filter_out (fn (_, T) =>
       tname_of (body_type T) mem ["set", "bool"]) ivs);
-    val ivs2 = map (fn (ixn, _) => Var (ixn, the (assoc (rvs, ixn)))) ivs;
+    val ivs2 = map (fn (ixn, _) => Var (ixn, valOf (assoc (rvs, ixn)))) ivs;
 
-    val prf = foldr forall_intr_prf (ivs2,
-      foldr (fn ((f, p), prf) =>
+    val prf = Library.foldr forall_intr_prf (ivs2,
+      Library.foldr (fn ((f, p), prf) =>
         (case head_of (strip_abs_body f) of
            Free (s, T) =>
              let val T' = Type.varifyT T
@@ -156,7 +156,7 @@
            (rec_fns ~~ prems_of thm, Proofterm.proof_combP
              (prf_of thm', map PBound (length prems - 1 downto 0))));
 
-    val r' = if null is then r else Logic.varify (foldr (uncurry lambda)
+    val r' = if null is then r else Logic.varify (Library.foldr (uncurry lambda)
       (map Logic.unvarify ivs1 @ filter_out is_unit
         (map (head_of o strip_abs_body) rec_fns), r));
 
@@ -184,7 +184,7 @@
       end;
 
     val SOME (_, _, constrs) = assoc (descr, index);
-    val T = nth_elem (index, get_rec_types descr sorts);
+    val T = List.nth (get_rec_types descr sorts, index);
     val (rs, prems) = split_list (map (make_casedist_prem T) constrs);
     val r = Const (case_name, map fastype_of rs ---> T --> rT);
 
@@ -205,11 +205,11 @@
     val (thy', thm') = thy
       |> Theory.absolute_path
       |> PureThy.store_thm ((exh_name ^ "_P_correctness", thm), [])
-      |>> Theory.add_path (NameSpace.pack (if_none path []));
+      |>> Theory.add_path (NameSpace.pack (getOpt (path,[])));
 
     val P = Var (("P", 0), rT' --> HOLogic.boolT);
     val prf = forall_intr_prf (y, forall_intr_prf (P,
-      foldr (fn ((p, r), prf) =>
+      Library.foldr (fn ((p, r), prf) =>
         forall_intr_prf (Logic.varify r, AbsP ("H", SOME (Logic.varify p),
           prf))) (prems ~~ rs, Proofterm.proof_combP (prf_of thm',
             map PBound (length prems - 1 downto 0)))));
@@ -225,8 +225,8 @@
 
 fun add_dt_realizers sorts infos thy = if !proofs < 2 then thy else
   (message "Adding realizers for induction and case analysis ..."; thy
-   |> curry (foldr (make_ind sorts (hd infos)))
+   |> curry (Library.foldr (make_ind sorts (hd infos)))
      (subsets 0 (length (#descr (hd infos)) - 1))
-   |> curry (foldr (make_casedists sorts)) infos);
+   |> curry (Library.foldr (make_casedists sorts)) infos);
 
 end;
--- a/src/HOL/Tools/datatype_rep_proofs.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/HOL/Tools/datatype_rep_proofs.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -35,7 +35,7 @@
 
 
 fun exh_thm_of (dt_info : datatype_info Symtab.table) tname =
-  #exhaustion (the (Symtab.lookup (dt_info, tname)));
+  #exhaustion (valOf (Symtab.lookup (dt_info, tname)));
 
 (******************************************************************************)
 
@@ -62,7 +62,7 @@
          "In0_eq", "In1_eq", "In0_not_In1", "In1_not_In0",
          "Lim_inject", "Suml_inject", "Sumr_inject"];
 
-    val descr' = flat descr;
+    val descr' = List.concat descr;
 
     val big_name = space_implode "_" new_type_names;
     val thy1 = add_path flat_names big_name thy;
@@ -78,11 +78,11 @@
     val branchT = if null branchTs then HOLogic.unitT
       else fold_bal (fn (T, U) => Type ("+", [T, U])) branchTs;
     val arities = get_arities descr' \ 0;
-    val unneeded_vars = hd tyvars \\ foldr add_typ_tfree_names (leafTs' @ branchTs, []);
-    val leafTs = leafTs' @ (map (fn n => TFree (n, the (assoc (sorts, n)))) unneeded_vars);
+    val unneeded_vars = hd tyvars \\ Library.foldr add_typ_tfree_names (leafTs' @ branchTs, []);
+    val leafTs = leafTs' @ (map (fn n => TFree (n, valOf (assoc (sorts, n)))) unneeded_vars);
     val recTs = get_rec_types descr' sorts;
-    val newTs = take (length (hd descr), recTs);
-    val oldTs = drop (length (hd descr), recTs);
+    val newTs = Library.take (length (hd descr), recTs);
+    val oldTs = Library.drop (length (hd descr), recTs);
     val sumT = if null leafTs then HOLogic.unitT
       else fold_bal (fn (T, U) => Type ("+", [T, U])) leafTs;
     val Univ_elT = HOLogic.mk_setT (Type (node_name, [sumT, branchT]));
@@ -134,7 +134,7 @@
       in mk_inj branchT (length branchTs) (1 + find_index_eq T' branchTs)
       end;
 
-    val mk_lim = foldr (fn (T, t) => Lim $ mk_fun_inj T (Abs ("x", T, t)));
+    val mk_lim = Library.foldr (fn (T, t) => Lim $ mk_fun_inj T (Abs ("x", T, t)));
 
     (************** generate introduction rules for representing set **********)
 
@@ -152,7 +152,7 @@
                   app_bnds (mk_Free "x" (Ts ---> Univ_elT) j) (length Ts)
               in (j + 1, list_all (map (pair "x") Ts,
                   HOLogic.mk_Trueprop (HOLogic.mk_mem (free_t,
-                    Const (nth_elem (k, rep_set_names), UnivT)))) :: prems,
+                    Const (List.nth (rep_set_names, k), UnivT)))) :: prems,
                 mk_lim (Ts, free_t) :: ts)
               end
           | _ =>
@@ -160,7 +160,7 @@
               in (j + 1, prems, (Leaf $ mk_inj T (mk_Free "x" T j))::ts)
               end);
 
-        val (_, prems, ts) = foldr mk_prem (cargs, (1, [], []));
+        val (_, prems, ts) = Library.foldr mk_prem (cargs, (1, [], []));
         val concl = HOLogic.mk_Trueprop (HOLogic.mk_mem
           (mk_univ_inj ts n i, Const (s, UnivT)))
       in Logic.list_implies (prems, concl)
@@ -168,7 +168,7 @@
 
     val consts = map (fn s => Const (s, UnivT)) rep_set_names;
 
-    val intr_ts = flat (map (fn ((_, (_, _, constrs)), rep_set_name) =>
+    val intr_ts = List.concat (map (fn ((_, (_, _, constrs)), rep_set_name) =>
       map (make_intr rep_set_name (length constrs))
         ((1 upto (length constrs)) ~~ constrs)) (descr' ~~ rep_set_names));
 
@@ -179,21 +179,21 @@
 
     (********************************* typedef ********************************)
 
-    val thy3 = add_path flat_names big_name (foldl (fn (thy, ((((name, mx), tvs), c), name')) =>
+    val thy3 = add_path flat_names big_name (Library.foldl (fn (thy, ((((name, mx), tvs), c), name')) =>
       setmp TypedefPackage.quiet_mode true
         (TypedefPackage.add_typedef_i false (SOME name') (name, tvs, mx) c NONE
           (rtac exI 1 THEN
             QUIET_BREADTH_FIRST (has_fewer_prems 1)
             (resolve_tac rep_intrs 1))) thy |> #1)
               (parent_path flat_names thy2, types_syntax ~~ tyvars ~~
-                (take (length newTs, consts)) ~~ new_type_names));
+                (Library.take (length newTs, consts)) ~~ new_type_names));
 
     (*********************** definition of constructors ***********************)
 
     val big_rep_name = (space_implode "_" new_type_names) ^ "_Rep_";
     val rep_names = map (curry op ^ "Rep_") new_type_names;
     val rep_names' = map (fn i => big_rep_name ^ (string_of_int i))
-      (1 upto (length (flat (tl descr))));
+      (1 upto (length (List.concat (tl descr))));
     val all_rep_names = map (Sign.intern_const (Theory.sign_of thy3)) rep_names @
       map (Sign.full_name (Theory.sign_of thy3)) rep_names';
 
@@ -211,12 +211,12 @@
               val free_t = mk_Free "x" T j
           in (case (strip_dtyp dt, strip_type T) of
               ((_, DtRec m), (Us, U)) => (j + 1, free_t :: l_args, mk_lim (Us,
-                Const (nth_elem (m, all_rep_names), U --> Univ_elT) $
+                Const (List.nth (all_rep_names, m), U --> Univ_elT) $
                   app_bnds free_t (length Us)) :: r_args)
             | _ => (j + 1, free_t::l_args, (Leaf $ mk_inj T free_t)::r_args))
           end;
 
-        val (_, l_args, r_args) = foldr constr_arg (cargs, (1, [], []));
+        val (_, l_args, r_args) = Library.foldr constr_arg (cargs, (1, [], []));
         val constrT = (map (typ_of_dtyp descr' sorts) cargs) ---> T;
         val abs_name = Sign.intern_const (Theory.sign_of thy) ("Abs_" ^ tname);
         val rep_name = Sign.intern_const (Theory.sign_of thy) ("Rep_" ^ tname);
@@ -243,14 +243,14 @@
           (Const (Sign.intern_const sg ("Rep_" ^ tname), T --> Univ_elT));
         val cong' = standard (cterm_instantiate [(cterm_of sg cong_f, rep_const)] arg_cong);
         val dist = standard (cterm_instantiate [(cterm_of sg distinct_f, rep_const)] distinct_lemma);
-        val (thy', defs', eqns', _) = foldl ((make_constr_def tname T) (length constrs))
+        val (thy', defs', eqns', _) = Library.foldl ((make_constr_def tname T) (length constrs))
           ((add_path flat_names tname thy, defs, [], 1), constrs ~~ constr_syntax)
       in
         (parent_path flat_names thy', defs', eqns @ [eqns'],
           rep_congs @ [cong'], dist_lemmas @ [dist])
       end;
 
-    val (thy4, constr_defs, constr_rep_eqns, rep_congs, dist_lemmas) = foldl dt_constr_defs
+    val (thy4, constr_defs, constr_rep_eqns, rep_congs, dist_lemmas) = Library.foldl dt_constr_defs
       ((thy3 |> Theory.add_consts_i iso_decls |> parent_path flat_names, [], [], [], []),
         hd descr ~~ new_type_names ~~ newTs ~~ constr_syntax);
 
@@ -300,7 +300,7 @@
 
     val newT_iso_inj_thms = map prove_newT_iso_inj_thm
       (new_type_names ~~ newT_iso_axms ~~ newTs ~~
-        take (length newTs, rep_set_names));
+        Library.take (length newTs, rep_set_names));
 
     (********* isomorphisms between existing types and "unfolded" types *******)
 
@@ -318,8 +318,8 @@
     fun make_iso_def k ks n ((fs, eqns, i), (cname, cargs)) =
       let
         val argTs = map (typ_of_dtyp descr' sorts) cargs;
-        val T = nth_elem (k, recTs);
-        val rep_name = nth_elem (k, all_rep_names);
+        val T = List.nth (recTs, k);
+        val rep_name = List.nth (all_rep_names, k);
         val rep_const = Const (rep_name, T --> Univ_elT);
         val constr = Const (cname, argTs ---> T);
 
@@ -334,17 +334,17 @@
                    Ts @ [Us ---> Univ_elT])
                 else
                   (i2 + 1, i2', ts @ [mk_lim (Us,
-                     Const (nth_elem (j, all_rep_names), U --> Univ_elT) $
+                     Const (List.nth (all_rep_names, j), U --> Univ_elT) $
                        app_bnds (mk_Free "x" T' i2) (length Us))], Ts)
             | _ => (i2 + 1, i2', ts @ [Leaf $ mk_inj T' (mk_Free "x" T' i2)], Ts))
           end;
 
-        val (i2, i2', ts, Ts) = foldl (process_arg ks) ((1, 1, [], []), cargs);
+        val (i2, i2', ts, Ts) = Library.foldl (process_arg ks) ((1, 1, [], []), cargs);
         val xs = map (uncurry (mk_Free "x")) (argTs ~~ (1 upto (i2 - 1)));
         val ys = map (uncurry (mk_Free "y")) (Ts ~~ (1 upto (i2' - 1)));
         val f = list_abs_free (map dest_Free (xs @ ys), mk_univ_inj ts n i);
 
-        val (_, _, ts', _) = foldl (process_arg []) ((1, 1, [], []), cargs);
+        val (_, _, ts', _) = Library.foldl (process_arg []) ((1, 1, [], []), cargs);
         val eqn = HOLogic.mk_Trueprop (HOLogic.mk_eq
           (rep_const $ list_comb (constr, xs), mk_univ_inj ts' n i))
 
@@ -356,16 +356,16 @@
       let
         val ks = map fst ds;
         val (_, (tname, _, _)) = hd ds;
-        val {rec_rewrites, rec_names, ...} = the (Symtab.lookup (dt_info, tname));
+        val {rec_rewrites, rec_names, ...} = valOf (Symtab.lookup (dt_info, tname));
 
         fun process_dt ((fs, eqns, isos), (k, (tname, _, constrs))) =
           let
-            val (fs', eqns', _) = foldl (make_iso_def k ks (length constrs))
+            val (fs', eqns', _) = Library.foldl (make_iso_def k ks (length constrs))
               ((fs, eqns, 1), constrs);
-            val iso = (nth_elem (k, recTs), nth_elem (k, all_rep_names))
+            val iso = (List.nth (recTs, k), List.nth (all_rep_names, k))
           in (fs', eqns', isos @ [iso]) end;
         
-        val (fs, eqns, isos) = foldl process_dt (([], [], []), ds);
+        val (fs, eqns, isos) = Library.foldl process_dt (([], [], []), ds);
         val fTs = map fastype_of fs;
         val defs = map (fn (rec_name, (T, iso_name)) => ((Sign.base_name iso_name) ^ "_def",
           equals (T --> Univ_elT) $ Const (iso_name, T --> Univ_elT) $
@@ -380,7 +380,7 @@
 
       in (thy', char_thms' @ char_thms) end;
 
-    val (thy5, iso_char_thms) = foldr make_iso_defs
+    val (thy5, iso_char_thms) = Library.foldr make_iso_defs
       (tl descr, (add_path flat_names big_name thy4, []));
 
     (* prove isomorphism properties *)
@@ -412,13 +412,13 @@
     fun prove_iso_thms (ds, (inj_thms, elem_thms)) =
       let
         val (_, (tname, _, _)) = hd ds;
-        val {induction, ...} = the (Symtab.lookup (dt_info, tname));
+        val {induction, ...} = valOf (Symtab.lookup (dt_info, tname));
 
         fun mk_ind_concl (i, _) =
           let
-            val T = nth_elem (i, recTs);
-            val Rep_t = Const (nth_elem (i, all_rep_names), T --> Univ_elT);
-            val rep_set_name = nth_elem (i, rep_set_names)
+            val T = List.nth (recTs, i);
+            val Rep_t = Const (List.nth (all_rep_names, i), T --> Univ_elT);
+            val rep_set_name = List.nth (rep_set_names, i)
           in (HOLogic.all_const T $ Abs ("y", T, HOLogic.imp $
                 HOLogic.mk_eq (Rep_t $ mk_Free "x" T i, Rep_t $ Bound 0) $
                   HOLogic.mk_eq (mk_Free "x" T i, Bound 0)),
@@ -469,7 +469,7 @@
       in (inj_thms'' @ inj_thms, elem_thms @ (split_conj_thm elem_thm))
       end;
 
-    val (iso_inj_thms_unfolded, iso_elem_thms) = foldr prove_iso_thms
+    val (iso_inj_thms_unfolded, iso_elem_thms) = Library.foldr prove_iso_thms
       (tl descr, ([], map #3 newT_iso_axms));
     val iso_inj_thms = map snd newT_iso_inj_thms @ iso_inj_thms_unfolded;
 
@@ -494,7 +494,7 @@
       iso_inj_thms_unfolded;
 
     val iso_thms = if length descr = 1 then [] else
-      drop (length newTs, split_conj_thm
+      Library.drop (length newTs, split_conj_thm
         (prove_goalw_cterm [] (cterm_of (Theory.sign_of thy5) iso_t) (fn _ =>
            [(indtac rep_induct THEN_ALL_NEW ObjectLogic.atomize_tac) 1,
             REPEAT (rtac TrueI 1),
@@ -503,7 +503,7 @@
             rewrite_goals_tac (map symmetric range_eqs),
             REPEAT (EVERY
               [REPEAT (eresolve_tac ([rangeE, ex1_implies_ex RS exE] @
-                 flat (map (mk_funs_inv o #1) newT_iso_axms)) 1),
+                 List.concat (map (mk_funs_inv o #1) newT_iso_axms)) 1),
                TRY (hyp_subst_tac 1),
                rtac (sym RS range_eqI) 1,
                resolve_tac iso_char_thms 1])])));
@@ -513,7 +513,7 @@
       map2 (fn (r_inj, r) => f_myinv_f OF [r_inj, r RS mp])
         (iso_inj_thms_unfolded, iso_thms);
 
-    val Abs_inverse_thms = flat (map mk_funs_inv Abs_inverse_thms');
+    val Abs_inverse_thms = List.concat (map mk_funs_inv Abs_inverse_thms');
 
     (******************* freeness theorems for constructors *******************)
 
@@ -596,23 +596,23 @@
 
     fun mk_indrule_lemma ((prems, concls), ((i, _), T)) =
       let
-        val Rep_t = Const (nth_elem (i, all_rep_names), T --> Univ_elT) $
+        val Rep_t = Const (List.nth (all_rep_names, i), T --> Univ_elT) $
           mk_Free "x" T i;
 
         val Abs_t = if i < length newTs then
             Const (Sign.intern_const (Theory.sign_of thy6)
-              ("Abs_" ^ (nth_elem (i, new_type_names))), Univ_elT --> T)
+              ("Abs_" ^ (List.nth (new_type_names, i))), Univ_elT --> T)
           else Const ("Inductive.myinv", [T --> Univ_elT, Univ_elT] ---> T) $
-            Const (nth_elem (i, all_rep_names), T --> Univ_elT)
+            Const (List.nth (all_rep_names, i), T --> Univ_elT)
 
       in (prems @ [HOLogic.imp $ HOLogic.mk_mem (Rep_t,
-            Const (nth_elem (i, rep_set_names), UnivT)) $
+            Const (List.nth (rep_set_names, i), UnivT)) $
               (mk_Free "P" (T --> HOLogic.boolT) (i + 1) $ (Abs_t $ Rep_t))],
           concls @ [mk_Free "P" (T --> HOLogic.boolT) (i + 1) $ mk_Free "x" T i])
       end;
 
     val (indrule_lemma_prems, indrule_lemma_concls) =
-      foldl mk_indrule_lemma (([], []), (descr' ~~ recTs));
+      Library.foldl mk_indrule_lemma (([], []), (descr' ~~ recTs));
 
     val cert = cterm_of (Theory.sign_of thy6);
 
--- a/src/HOL/Tools/inductive_codegen.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/HOL/Tools/inductive_codegen.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -49,12 +49,12 @@
   in (case concl_of thm of
       _ $ (Const ("op :", _) $ _ $ t) => (case head_of t of
         Const (s, _) =>
-          let val cs = foldr add_term_consts (prems_of thm, [])
+          let val cs = Library.foldr add_term_consts (prems_of thm, [])
           in (CodegenData.put
             {intros = Symtab.update ((s,
-               if_none (Symtab.lookup (intros, s)) [] @ [thm]), intros),
-             graph = foldr (uncurry (Graph.add_edge o pair s))
-               (cs, foldl add_node (graph, s :: cs)),
+               getOpt (Symtab.lookup (intros, s), []) @ [thm]), intros),
+             graph = Library.foldr (uncurry (Graph.add_edge o pair s))
+               (cs, Library.foldl add_node (graph, s :: cs)),
              eqns = eqns} thy, thm)
           end
       | _ => (warn thm; p))
@@ -62,7 +62,7 @@
         Const (s, _) =>
           (CodegenData.put {intros = intros, graph = graph,
              eqns = Symtab.update ((s,
-               if_none (Symtab.lookup (eqns, s)) [] @ [thm]), eqns)} thy, thm)
+               getOpt (Symtab.lookup (eqns, s), []) @ [thm]), eqns)} thy, thm)
       | _ => (warn thm; p))
     | _ => (warn thm; p))
   end;
@@ -77,7 +77,7 @@
         let val SOME names = find_first
           (fn xs => s mem xs) (Graph.strong_conn graph)
         in SOME (names, preprocess thy
-          (flat (map (fn s => the (Symtab.lookup (intros, s))) names)))
+          (List.concat (map (fn s => valOf (Symtab.lookup (intros, s))) names)))
         end
   end;
 
@@ -117,14 +117,14 @@
   in (case (optf, strip_comb t) of
       (SOME f, (Const (name, _), args)) =>
         (case assoc (extra_fs, name) of
-           NONE => overwrite (fs, (name, if_none
-             (apsome (mg_factor f) (assoc (fs, name))) f))
+           NONE => overwrite (fs, (name, getOpt
+             (Option.map (mg_factor f) (assoc (fs, name)), f)))
          | SOME (fs', f') => (mg_factor f (FFix f');
-             foldl (infer_factors sg extra_fs)
-               (fs, map (apsome FFix) fs' ~~ args)))
+             Library.foldl (infer_factors sg extra_fs)
+               (fs, map (Option.map FFix) fs' ~~ args)))
     | (SOME f, (Var ((name, _), _), [])) =>
-        overwrite (fs, (name, if_none
-          (apsome (mg_factor f) (assoc (fs, name))) f))
+        overwrite (fs, (name, getOpt
+          (Option.map (mg_factor f) (assoc (fs, name)), f)))
     | (NONE, _) => fs
     | _ => err "Illegal term")
       handle Factors => err "Product factor mismatch in"
@@ -139,7 +139,7 @@
 
 fun is_constrt thy =
   let
-    val cnstrs = flat (flat (map
+    val cnstrs = List.concat (List.concat (map
       (map (fn (_, (_, _, cs)) => map (apsnd length) cs) o #descr o snd)
       (Symtab.dest (DatatypePackage.get_datatypes thy))));
     fun check t = (case strip_comb t of
@@ -167,11 +167,11 @@
     string_of_mode ms)) modes));
 
 val term_vs = map (fst o fst o dest_Var) o term_vars;
-val terms_vs = distinct o flat o (map term_vs);
+val terms_vs = distinct o List.concat o (map term_vs);
 
 (** collect all Vars in a term (with duplicates!) **)
 fun term_vTs t = map (apfst fst o dest_Var)
-  (filter is_Var (foldl_aterms (op :: o Library.swap) ([], t)));
+  (List.filter is_Var (foldl_aterms (op :: o Library.swap) ([], t)));
 
 fun get_args _ _ [] = ([], [])
   | get_args is i (x::xs) = (if i mem is then apfst else apsnd) (cons x)
@@ -190,18 +190,18 @@
 fun cprod ([], ys) = []
   | cprod (x :: xs, ys) = map (pair x) ys @ cprod (xs, ys);
 
-fun cprods xss = foldr (map op :: o cprod) (xss, [[]]);
+fun cprods xss = Library.foldr (map op :: o cprod) (xss, [[]]);
 
 datatype mode = Mode of (int list option list * int list) * mode option list;
 
 fun modes_of modes t =
   let
-    fun mk_modes name args = flat
+    fun mk_modes name args = List.concat
       (map (fn (m as (iss, is)) => map (Mode o pair m) (cprods (map
         (fn (NONE, _) => [NONE]
           | (SOME js, arg) => map SOME
-              (filter (fn Mode ((_, js'), _) => js=js') (modes_of modes arg)))
-                (iss ~~ args)))) (the (assoc (modes, name))))
+              (List.filter (fn Mode ((_, js'), _) => js=js') (modes_of modes arg)))
+                (iss ~~ args)))) (valOf (assoc (modes, name))))
 
   in (case strip_comb t of
       (Const ("op =", Type (_, [T, _])), _) =>
@@ -215,14 +215,14 @@
 datatype indprem = Prem of term list * term | Sidecond of term;
 
 fun select_mode_prem thy modes vs ps =
-  find_first (is_some o snd) (ps ~~ map
+  find_first (isSome o snd) (ps ~~ map
     (fn Prem (us, t) => find_first (fn Mode ((_, is), _) =>
           let
             val (in_ts, out_ts) = get_args is 1 us;
-            val (out_ts', in_ts') = partition (is_constrt thy) out_ts;
-            val vTs = flat (map term_vTs out_ts');
+            val (out_ts', in_ts') = List.partition (is_constrt thy) out_ts;
+            val vTs = List.concat (map term_vTs out_ts');
             val dupTs = map snd (duplicates vTs) @
-              mapfilter (curry assoc vTs) vs;
+              List.mapPartial (curry assoc vTs) vs;
           in
             terms_vs (in_ts @ in_ts') subset vs andalso
             forall (is_eqT o fastype_of) in_ts' andalso
@@ -235,7 +235,7 @@
 
 fun check_mode_clause thy arg_vs modes (iss, is) (ts, ps) =
   let
-    val modes' = modes @ mapfilter
+    val modes' = modes @ List.mapPartial
       (fn (_, NONE) => NONE | (v, SOME js) => SOME (v, [([], js)]))
         (arg_vs ~~ iss);
     fun check_mode_prems vs [] = SOME vs
@@ -244,11 +244,11 @@
         | SOME (x, _) => check_mode_prems
             (case x of Prem (us, _) => vs union terms_vs us | _ => vs)
             (filter_out (equal x) ps));
-    val (in_ts, in_ts') = partition (is_constrt thy) (fst (get_args is 1 ts));
+    val (in_ts, in_ts') = List.partition (is_constrt thy) (fst (get_args is 1 ts));
     val in_vs = terms_vs in_ts;
     val concl_vs = terms_vs ts
   in
-    forall is_eqT (map snd (duplicates (flat (map term_vTs in_ts)))) andalso
+    forall is_eqT (map snd (duplicates (List.concat (map term_vTs in_ts)))) andalso
     forall (is_eqT o fastype_of) in_ts' andalso
     (case check_mode_prems (arg_vs union in_vs) ps of
        NONE => false
@@ -257,7 +257,7 @@
 
 fun check_modes_pred thy arg_vs preds modes (p, ms) =
   let val SOME rs = assoc (preds, p)
-  in (p, filter (fn m => case find_index
+  in (p, List.filter (fn m => case find_index
     (not o check_mode_clause thy arg_vs modes m) rs of
       ~1 => true
     | i => (message ("Clause " ^ string_of_int (i+1) ^ " of " ^
@@ -283,7 +283,7 @@
   in mk_eqs x xs end;
 
 fun mk_tuple xs = Pretty.block (Pretty.str "(" ::
-  flat (separate [Pretty.str ",", Pretty.brk 1] (map single xs)) @
+  List.concat (separate [Pretty.str ",", Pretty.brk 1] (map single xs)) @
   [Pretty.str ")"]);
 
 (* convert nested pairs to n-tuple *)
@@ -351,8 +351,8 @@
   | is_exhaustive _ = false;
 
 fun compile_match nvs eq_ps out_ps success_p can_fail =
-  let val eqs = flat (separate [Pretty.str " andalso", Pretty.brk 1]
-    (map single (flat (map (mk_eq o snd) nvs) @ eq_ps)));
+  let val eqs = List.concat (separate [Pretty.str " andalso", Pretty.brk 1]
+    (map single (List.concat (map (mk_eq o snd) nvs) @ eq_ps)));
   in
     Pretty.block
      ([Pretty.str "(fn ", mk_tuple out_ps, Pretty.str " =>", Pretty.brk 1] @
@@ -367,7 +367,7 @@
 
 fun modename thy s (iss, is) = space_implode "__"
   (mk_const_id (sign_of thy) s ::
-    map (space_implode "_" o map string_of_int) (mapfilter I iss @ [is]));
+    map (space_implode "_" o map string_of_int) (List.mapPartial I iss @ [is]));
 
 fun compile_expr thy dep brack (gr, (NONE, t)) =
       apsnd single (invoke_codegen thy dep brack (gr, t))
@@ -380,13 +380,13 @@
           (compile_expr thy dep true) (gr, ms ~~ args);
       in (gr', (if brack andalso not (null ps) then
         single o parens o Pretty.block else I)
-          (flat (separate [Pretty.brk 1]
+          (List.concat (separate [Pretty.brk 1]
             ([Pretty.str (modename thy name mode)] :: ps))))
       end;
 
 fun compile_clause thy gr dep all_vs arg_vs modes (iss, is) (ts, ps) =
   let
-    val modes' = modes @ mapfilter
+    val modes' = modes @ List.mapPartial
       (fn (_, NONE) => NONE | (v, SOME js) => SOME (v, [([], js)]))
         (arg_vs ~~ iss);
 
@@ -404,7 +404,7 @@
       foldl_map check_constrt ((all_vs, []), in_ts);
 
     fun is_ind t = (case head_of t of
-          Const (s, _) => s = "op =" orelse is_some (assoc (modes, s))
+          Const (s, _) => s = "op =" orelse isSome (assoc (modes, s))
         | Var ((s, _), _) => s mem arg_vs);
 
     fun compile_prems out_ts' vs names gr [] =
@@ -426,7 +426,7 @@
           end
       | compile_prems out_ts vs names gr ps =
           let
-            val vs' = distinct (flat (vs :: map term_vs out_ts));
+            val vs' = distinct (List.concat (vs :: map term_vs out_ts));
             val SOME (p, mode as SOME (Mode ((_, js), _))) =
               select_mode_prem thy modes' vs' ps;
             val ps' = filter_out (equal p) ps;
@@ -484,16 +484,16 @@
          (Pretty.str (prfx ^ modename thy s mode) :: map Pretty.str arg_vs) @
          [Pretty.str " inp ="]),
         Pretty.brk 1] @
-       flat (separate [Pretty.str " ++", Pretty.brk 1] (map single cl_ps))))
+       List.concat (separate [Pretty.str " ++", Pretty.brk 1] (map single cl_ps))))
   end;
 
 fun compile_preds thy gr dep all_vs arg_vs modes preds =
   let val ((gr', _), prs) = foldl_map (fn ((gr, prfx), (s, cls)) =>
     foldl_map (fn ((gr', prfx'), mode) =>
       compile_pred thy gr' dep prfx' all_vs arg_vs modes s cls mode)
-        ((gr, prfx), the (assoc (modes, s)))) ((gr, "fun "), preds)
+        ((gr, prfx), valOf (assoc (modes, s)))) ((gr, "fun "), preds)
   in
-    (gr', space_implode "\n\n" (map Pretty.string_of (flat prs)) ^ ";\n\n")
+    (gr', space_implode "\n\n" (map Pretty.string_of (List.concat prs)) ^ ";\n\n")
   end;
 
 (**** processing of introduction rules ****)
@@ -502,7 +502,7 @@
   (string * (int list option list * int list) list) list *
   (string * (int list list option list * int list list)) list;
 
-fun lookup_modes gr dep = apfst flat (apsnd flat (ListPair.unzip
+fun lookup_modes gr dep = apfst List.concat (apsnd List.concat (ListPair.unzip
   (map ((fn (SOME (Modes x), _) => x | _ => ([], [])) o Graph.get_node gr)
     (Graph.all_preds gr [dep]))));
 
@@ -520,13 +520,13 @@
     | SOME xs' => xs inter xs') :: constrain cs ys;
 
 fun mk_extra_defs thy gr dep names ts =
-  foldl (fn (gr, name) =>
+  Library.foldl (fn (gr, name) =>
     if name mem names then gr
     else (case get_clauses thy name of
         NONE => gr
       | SOME (names, intrs) =>
           mk_ind_def thy gr dep names [] [] (prep_intrs intrs)))
-            (gr, foldr add_term_consts (ts, []))
+            (gr, Library.foldr add_term_consts (ts, []))
 
 and mk_ind_def thy gr dep names modecs factorcs intrs =
   let val ids = map (mk_const_id (sign_of thy)) names
@@ -534,7 +534,7 @@
     let
       val _ $ (_ $ _ $ u) = Logic.strip_imp_concl (hd intrs);
       val (_, args) = strip_comb u;
-      val arg_vs = flat (map term_vs args);
+      val arg_vs = List.concat (map term_vs args);
 
       fun dest_prem factors (_ $ (p as (Const ("op :", _) $ t $ u))) =
             (case assoc (factors, case head_of u of
@@ -551,11 +551,11 @@
           val Const (name, _) = head_of u;
           val prems = map (dest_prem factors) (Logic.strip_imp_prems intr);
         in
-          (overwrite (clauses, (name, if_none (assoc (clauses, name)) [] @
-             [(split_prod [] (the (assoc (factors, name))) t, prems)])))
+          (overwrite (clauses, (name, getOpt (assoc (clauses, name), []) @
+             [(split_prod [] (valOf (assoc (factors, name))) t, prems)])))
         end;
 
-      fun check_set (Const (s, _)) = s mem names orelse is_some (get_clauses thy s)
+      fun check_set (Const (s, _)) = s mem names orelse isSome (get_clauses thy s)
         | check_set (Var ((s, _), _)) = s mem arg_vs
         | check_set _ = false;
 
@@ -571,13 +571,13 @@
           (Graph.new_node (hd ids, (NONE, "")) gr)) (hd ids) names intrs;
       val (extra_modes, extra_factors) = lookup_modes gr' (hd ids);
       val fs = constrain factorcs (map (apsnd dest_factors)
-        (foldl (add_prod_factors extra_factors) ([], flat (map (fn t =>
+        (Library.foldl (add_prod_factors extra_factors) ([], List.concat (map (fn t =>
           Logic.strip_imp_concl t :: Logic.strip_imp_prems t) intrs))));
-      val factors = mapfilter (fn (name, f) =>
+      val factors = List.mapPartial (fn (name, f) =>
         if name mem arg_vs then NONE
         else SOME (name, (map (curry assoc fs) arg_vs, f))) fs;
       val clauses =
-        foldl (add_clause (fs @ map (apsnd snd) extra_factors)) ([], intrs);
+        Library.foldl (add_clause (fs @ map (apsnd snd) extra_factors)) ([], intrs);
       val modes = constrain modecs
         (infer_modes thy extra_modes factors arg_vs clauses);
       val _ = print_factors factors;
@@ -606,9 +606,9 @@
            val gr1 = mk_extra_defs thy
              (mk_ind_def thy gr dep names [] [] (prep_intrs intrs)) dep names [u];
            val (modes, factors) = lookup_modes gr1 dep;
-           val ts = split_prod [] (snd (the (assoc (factors, s)))) t;
+           val ts = split_prod [] (snd (valOf (assoc (factors, s)))) t;
            val (ts', is) = if is_query then
-               fst (foldl mk_mode ((([], []), 1), ts))
+               fst (Library.foldl mk_mode ((([], []), 1), ts))
              else (ts, 1 upto length ts);
            val mode = find_mode s u modes is;
            val (gr2, in_ps) = foldl_map
@@ -635,7 +635,7 @@
            SOME (gr2, (if brack then parens else I)
              (Pretty.block ([Pretty.str "Seq.list_of", Pretty.brk 1,
                Pretty.str "("] @
-               conv_ntuple' (snd (the (assoc (factors, s))))
+               conv_ntuple' (snd (valOf (assoc (factors, s))))
                  (HOLogic.dest_setT (fastype_of u))
                  (ps @ [Pretty.brk 1, Pretty.str "()"]) @
                [Pretty.str ")"])))
@@ -718,7 +718,7 @@
 
 fun ?? b = if b then Seq.single () else Seq.empty;
 
-fun ?! s = is_some (Seq.pull s);    
+fun ?! s = isSome (Seq.pull s);    
 
 fun op_61__1 x = Seq.single x;
 
--- a/src/HOL/Tools/inductive_package.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/HOL/Tools/inductive_package.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -124,7 +124,7 @@
 fun put_inductives names info thy =
   let
     fun upd ((tab, monos), name) = (Symtab.update_new ((name, info), tab), monos);
-    val tab_monos = foldl upd (InductiveData.get thy, names)
+    val tab_monos = Library.foldl upd (InductiveData.get thy, names)
       handle Symtab.DUP name => error ("Duplicate definition of (co)inductive set " ^ quote name);
   in InductiveData.put tab_monos thy end;
 
@@ -183,16 +183,16 @@
     fun varify (t, (i, ts)) =
       let val t' = map_term_types (incr_tvar (i + 1)) (#1 (Type.varify (t, [])))
       in (maxidx_of_term t', t'::ts) end;
-    val (i, cs') = foldr varify (cs, (~1, []));
-    val (i', intr_ts') = foldr varify (intr_ts, (i, []));
-    val rec_consts = foldl add_term_consts_2 ([], cs');
-    val intr_consts = foldl add_term_consts_2 ([], intr_ts');
+    val (i, cs') = Library.foldr varify (cs, (~1, []));
+    val (i', intr_ts') = Library.foldr varify (intr_ts, (i, []));
+    val rec_consts = Library.foldl add_term_consts_2 ([], cs');
+    val intr_consts = Library.foldl add_term_consts_2 ([], intr_ts');
     fun unify (env, (cname, cT)) =
-      let val consts = map snd (filter (fn c => fst c = cname) intr_consts)
-      in foldl (fn ((env', j'), Tp) => (Type.unify tsig (env', j') Tp))
+      let val consts = map snd (List.filter (fn c => fst c = cname) intr_consts)
+      in Library.foldl (fn ((env', j'), Tp) => (Type.unify tsig (env', j') Tp))
           (env, (replicate (length consts) cT) ~~ consts)
       end;
-    val (env, _) = foldl unify ((Vartab.empty, i'), rec_consts);
+    val (env, _) = Library.foldl unify ((Vartab.empty, i'), rec_consts);
     fun typ_subst_TVars_2 env T = let val T' = typ_subst_TVars_Vartab env T
       in if T = T' then T else typ_subst_TVars_2 env T' end;
     val subst = fst o Type.freeze_thaw o
@@ -237,7 +237,7 @@
 
 fun mg_prod_factors ts (fs, t $ u) = if t mem ts then
         let val f = prod_factors [] u
-        in overwrite (fs, (t, f inter if_none (assoc (fs, t)) f)) end
+        in overwrite (fs, (t, f inter (curry getOpt) (assoc (fs, t)) f)) end
       else mg_prod_factors ts (mg_prod_factors ts (fs, t), u)
   | mg_prod_factors ts (fs, Abs (_, _, t)) = mg_prod_factors ts (fs, t)
   | mg_prod_factors ts (fs, _) = fs;
@@ -256,7 +256,7 @@
 
 fun mk_tuple p ps (Type ("*", [T1, T2])) (tms as t::_) =
       if p mem ps then HOLogic.mk_prod (mk_tuple (1::p) ps T1 tms, 
-        mk_tuple (2::p) ps T2 (drop (length (prodT_factors (1::p) ps T1), tms)))
+        mk_tuple (2::p) ps T2 (Library.drop (length (prodT_factors (1::p) ps T1), tms)))
       else t
   | mk_tuple _ _ _ (t::_) = t;
 
@@ -271,12 +271,12 @@
 
 val remove_split = rewrite_rule [split_conv RS eq_reflection];
 
-fun split_rule_vars vs rl = standard (remove_split (foldr split_rule_var'
+fun split_rule_vars vs rl = standard (remove_split (Library.foldr split_rule_var'
   (mg_prod_factors vs ([], Thm.prop_of rl), rl)));
 
-fun split_rule vs rl = standard (remove_split (foldr split_rule_var'
-  (mapfilter (fn (t as Var ((a, _), _)) =>
-    apsome (pair t) (assoc (vs, a))) (term_vars (Thm.prop_of rl)), rl)));
+fun split_rule vs rl = standard (remove_split (Library.foldr split_rule_var'
+  (List.mapPartial (fn (t as Var ((a, _), _)) =>
+    Option.map (pair t) (assoc (vs, a))) (term_vars (Thm.prop_of rl)), rl)));
 
 
 (** process rules **)
@@ -315,7 +315,7 @@
         if u mem cs then
           if exists (Logic.occs o rpair t) cs then
             err_in_rule sg name rule "Recursion term on left of member symbol"
-          else seq check_prem (prems ~~ aprems)
+          else List.app check_prem (prems ~~ aprems)
         else err_in_rule sg name rule bad_concl
       | Const ("all", _) $ _ => err_in_rule sg name rule all_not_allowed
       | _ => err_in_rule sg name rule bad_concl);
@@ -337,7 +337,7 @@
 
 fun mk_elims cs cTs params intr_ts intr_names =
   let
-    val used = foldr add_term_names (intr_ts, []);
+    val used = Library.foldr add_term_names (intr_ts, []);
     val [aname, pname] = variantlist (["a", "P"], used);
     val P = HOLogic.mk_Trueprop (Free (pname, HOLogic.boolT));
 
@@ -353,9 +353,9 @@
         val a = Free (aname, T);
 
         fun mk_elim_prem (_, t, ts) =
-          list_all_free (map dest_Free ((foldr add_term_frees (t::ts, [])) \\ params),
+          list_all_free (map dest_Free ((Library.foldr add_term_frees (t::ts, [])) \\ params),
             Logic.list_implies (HOLogic.mk_Trueprop (HOLogic.mk_eq (a, t)) :: ts, P));
-        val c_intrs = (filter (equal c o #1 o #1) intrs);
+        val c_intrs = (List.filter (equal c o #1 o #1) intrs);
       in
         (Logic.list_implies (HOLogic.mk_Trueprop (HOLogic.mk_mem (a, c)) ::
           map mk_elim_prem (map #1 c_intrs), P), map #2 c_intrs)
@@ -369,7 +369,7 @@
 
 fun mk_indrule cs cTs params intr_ts =
   let
-    val used = foldr add_term_names (intr_ts, []);
+    val used = Library.foldr add_term_names (intr_ts, []);
 
     (* predicates for induction rule *)
 
@@ -407,22 +407,22 @@
           HOLogic.dest_Trueprop (Logic.strip_imp_concl r)
 
       in list_all_free (frees,
-           Logic.list_implies (map HOLogic.mk_Trueprop (foldr mk_prem
+           Logic.list_implies (map HOLogic.mk_Trueprop (Library.foldr mk_prem
              (map HOLogic.dest_Trueprop (Logic.strip_imp_prems r), [])),
-               HOLogic.mk_Trueprop (the (pred_of u) $ t)))
+               HOLogic.mk_Trueprop (valOf (pred_of u) $ t)))
       end;
 
     val ind_prems = map mk_ind_prem intr_ts;
 
-    val factors = foldl (mg_prod_factors preds) ([], ind_prems);
+    val factors = Library.foldl (mg_prod_factors preds) ([], ind_prems);
 
     (* make conclusions for induction rules *)
 
     fun mk_ind_concl ((c, P), (ts, x)) =
       let val T = HOLogic.dest_setT (fastype_of c);
-          val ps = if_none (assoc (factors, P)) [];
+          val ps = getOpt (assoc (factors, P), []);
           val Ts = prodT_factors [] ps T;
-          val (frees, x') = foldr (fn (T', (fs, s)) =>
+          val (frees, x') = Library.foldr (fn (T', (fs, s)) =>
             ((Free (s, T'))::fs, Symbol.bump_string s)) (Ts, ([], x));
           val tuple = mk_tuple [] ps T frees;
       in ((HOLogic.mk_binop "op -->"
@@ -430,7 +430,7 @@
       end;
 
     val mutual_ind_concl = HOLogic.mk_Trueprop (foldr1 HOLogic.mk_conj
-        (fst (foldr mk_ind_concl (cs ~~ preds, ([], "xa")))))
+        (fst (Library.foldr mk_ind_concl (cs ~~ preds, ([], "xa")))))
 
   in (preds, ind_prems, mutual_ind_concl,
     map (apfst (fst o dest_Free)) factors)
@@ -481,7 +481,7 @@
   Goals.prove_goalw_cterm []      (*NO quick_and_dirty_prove_goalw_cterm here!*)
     (Thm.cterm_of (Theory.sign_of thy) (HOLogic.mk_Trueprop
       (Const (mono_name, (setT --> setT) --> HOLogic.boolT) $ fp_fun)))
-    (fn _ => [rtac monoI 1, REPEAT (ares_tac (flat (map mk_mono monos) @ get_monos thy) 1)]));
+    (fn _ => [rtac monoI 1, REPEAT (ares_tac (List.concat (map mk_mono monos) @ get_monos thy) 1)]));
 
 
 (* prove introduction rules *)
@@ -628,7 +628,7 @@
 
     val dummy = if !trace then
 		(writeln "ind_prems = ";
-		 seq (writeln o Sign.string_of_term sign) ind_prems)
+		 List.app (writeln o Sign.string_of_term sign) ind_prems)
 	    else ();
 
     (* make predicate for instantiation of abstract induction rule *)
@@ -639,7 +639,7 @@
              val Type (_, [T1, T2]) = T
          in Const ("Datatype.sum.sum_case",
            [T1 --> HOLogic.boolT, T2 --> HOLogic.boolT, T] ---> HOLogic.boolT) $
-             mk_ind_pred T1 (take (n, Ps)) $ mk_ind_pred T2 (drop (n, Ps))
+             mk_ind_pred T1 (Library.take (n, Ps)) $ mk_ind_pred T2 (Library.drop (n, Ps))
          end;
 
     val ind_pred = mk_ind_pred sumT preds;
@@ -655,7 +655,7 @@
         (HOLogic.mk_Trueprop (HOLogic.mk_eq
           (mk_vimage cs sumT (HOLogic.Collect_const sumT $ ind_pred) c,
            HOLogic.Collect_const (HOLogic.dest_setT (fastype_of c)) $
-             nth_elem (find_index_eq c cs, preds)))))
+             List.nth (preds, find_index_eq c cs)))))
         (fn _ => [rtac vimage_Collect 1, rewrite_goals_tac sum_case_rewrites, rtac refl 1])) cs;
 
     val raw_fp_induct = (mono RS (fp_def RS def_lfp_induct));
@@ -707,7 +707,7 @@
 
     val fp_name = if coind then gfp_name else lfp_name;
 
-    val used = foldr add_term_names (intr_ts, []);
+    val used = Library.foldr add_term_names (intr_ts, []);
     val [sname, xname] = variantlist (["S", "x"], used);
 
     (* transform an introduction rule into a conjunction  *)
@@ -723,7 +723,7 @@
         val Const ("op :", _) $ t $ u =
           HOLogic.dest_Trueprop (Logic.strip_imp_concl r)
 
-      in foldr (fn ((x, T), P) => HOLogic.mk_exists (x, T, P))
+      in Library.foldr (fn ((x, T), P) => HOLogic.mk_exists (x, T, P))
         (frees, foldr1 HOLogic.mk_conj
           (((HOLogic.eq_const sumT) $ Free (xname, sumT) $ (mk_inj cs sumT u t))::
             (map (subst o HOLogic.dest_Trueprop)
--- a/src/HOL/Tools/inductive_realizer.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/HOL/Tools/inductive_realizer.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -41,7 +41,7 @@
       | strip _ t = t;
   in strip (add_term_free_names (t, [])) t end;
 
-fun relevant_vars prop = foldr (fn
+fun relevant_vars prop = Library.foldr (fn
       (Var ((a, i), T), vs) => (case strip_type T of
         (_, Type (s, _)) => if s mem ["bool", "set"] then (a, T) :: vs else vs
       | _ => vs)
@@ -198,13 +198,13 @@
 fun indrule_realizer thy induct raw_induct rsets params vs rec_names rss intrs dummies =
   let
     val concls = HOLogic.dest_conj (HOLogic.dest_Trueprop (concl_of raw_induct));
-    val premss = mapfilter (fn (s, rs) => if s mem rsets then
-      SOME (map (fn r => nth_elem (find_index_eq (prop_of r) (map prop_of intrs),
-        prems_of raw_induct)) rs) else NONE) rss;
-    val concls' = mapfilter (fn (s, _) => if s mem rsets then
+    val premss = List.mapPartial (fn (s, rs) => if s mem rsets then
+      SOME (map (fn r => List.nth (prems_of raw_induct,
+        find_index_eq (prop_of r) (map prop_of intrs))) rs) else NONE) rss;
+    val concls' = List.mapPartial (fn (s, _) => if s mem rsets then
         find_first (fn concl => s mem term_consts concl) concls
       else NONE) rss;
-    val fs = flat (snd (foldl_map (fn (intrs, (prems, dummy)) =>
+    val fs = List.concat (snd (foldl_map (fn (intrs, (prems, dummy)) =>
       let
         val (intrs1, intrs2) = splitAt (length prems, intrs);
         val fs = map (fn (rule, intr) =>
@@ -213,9 +213,9 @@
           HOLogic.unitT --> body_type (fastype_of (hd fs))) :: fs
         else fs)
       end) (intrs, (premss ~~ dummies))));
-    val frees = foldl Term.add_frees ([], fs);
+    val frees = Library.foldl Term.add_frees ([], fs);
     val Ts = map fastype_of fs;
-    val rlzs = mapfilter (fn (a, concl) =>
+    val rlzs = List.mapPartial (fn (a, concl) =>
       let val T = Extraction.etype_of thy vs [] concl
       in if T = Extraction.nullT then NONE
         else SOME (list_comb (Const (a, Ts ---> T), fs))
@@ -225,8 +225,8 @@
       val r = foldr1 HOLogic.mk_prod rlzs;
       val x = Free ("x", Extraction.etype_of thy vs [] (hd (prems_of induct)));
       fun name_of_fn intr = "r" ^ Sign.base_name (Thm.name_of_thm intr);
-      val r' = list_abs_free (mapfilter (fn intr =>
-        apsome (pair (name_of_fn intr)) (assoc (frees, name_of_fn intr))) intrs,
+      val r' = list_abs_free (List.mapPartial (fn intr =>
+        Option.map (pair (name_of_fn intr)) (assoc (frees, name_of_fn intr))) intrs,
           if length concls = 1 then r $ x else r)
     in
       if length concls = 1 then lambda x r' else r'
@@ -253,7 +253,7 @@
     val xs = rev (Term.add_vars ([], prop_of rule));
     val vs1 = map Var (filter_out (fn ((a, _), _) => a mem rvs) xs);
     val rlzvs = rev (Term.add_vars ([], prop_of rrule));
-    val vs2 = map (fn (ixn, _) => Var (ixn, the (assoc (rlzvs, ixn)))) xs;
+    val vs2 = map (fn (ixn, _) => Var (ixn, valOf (assoc (rlzvs, ixn)))) xs;
     val rs = gen_rems (op = o pairself fst) (rlzvs, xs);
 
     fun mk_prf _ [] prf = prf
@@ -265,8 +265,8 @@
 
   in (Thm.name_of_thm rule, (vs,
     if rt = Extraction.nullt then rt else
-      foldr (uncurry lambda) (vs1, rt),
-    foldr forall_intr_prf (vs2, mk_prf rs prems (Proofterm.proof_combP
+      Library.foldr (uncurry lambda) (vs1, rt),
+    Library.foldr forall_intr_prf (vs2, mk_prf rs prems (Proofterm.proof_combP
       (prf_of rrule, map PBound (length prems - 1 downto 0))))))
   end;
 
@@ -274,7 +274,7 @@
   let
     val _ $ (_ $ _ $ S) = concl_of r;
     val (Const (s, _), _) = strip_comb S;
-    val rs = if_none (assoc (rss, s)) [];
+    val rs = getOpt (assoc (rss, s), []);
   in overwrite (rss, (s, rs @ [r])) end;
 
 fun add_ind_realizer rsets intrs induct raw_induct elims (thy, vs) =
@@ -284,7 +284,7 @@
     val (_ $ (_ $ _ $ S)) = Logic.strip_imp_concl (prop_of (hd intrs));
     val (_, params) = strip_comb S;
     val params' = map dest_Var params;
-    val rss = foldl add_rule ([], intrs);
+    val rss = Library.foldl add_rule ([], intrs);
     val (prfx, _) = split_last (NameSpace.unpack (fst (hd rss)));
     val tnames = map (fn s => space_implode "_" (s ^ "T" :: vs)) rsets;
     val {path, ...} = Sign.rep_sg (sign_of thy);
@@ -300,7 +300,7 @@
       Theory.add_arities_i (map (fn s =>
         (s, replicate ar HOLogic.typeS, HOLogic.typeS)) tnames) |>
         Extraction.add_typeof_eqns_i ty_eqs;
-    val dts = mapfilter (fn (s, rs) => if s mem rsets then
+    val dts = List.mapPartial (fn (s, rs) => if s mem rsets then
       SOME (dt_of_intrs thy1' vs rs) else NONE) rss;
 
     (** datatype representing computational content of inductive set **)
@@ -311,7 +311,7 @@
           (map #2 dts)) (map (pair false) dts) []) |>>
       Extraction.add_typeof_eqns_i ty_eqs |>>
       Extraction.add_realizes_eqns_i rlz_eqs;
-    fun get f x = if_none (apsome f x) [];
+    fun get f x = getOpt (Option.map f x, []);
     val rec_names = distinct (map (fst o dest_Const o head_of o fst o
       HOLogic.dest_eq o HOLogic.dest_Trueprop o prop_of) (get #rec_thms dt_info));
     val (_, constrss) = foldl_map (fn ((recs, dummies), (s, rs)) =>
@@ -328,7 +328,7 @@
       (Extraction.realizes_of thy2 vs
         c (prop_of (forall_intr_list (map (cterm_of (sign_of thy2) o Var)
           (rev (Term.add_vars ([], prop_of intr)) \\ params')) intr))))
-            (intrs ~~ flat constrss);
+            (intrs ~~ List.concat constrss);
     val rlzsets = distinct (map (fn rintr => snd (HOLogic.dest_mem
       (HOLogic.dest_Trueprop (Logic.strip_assums_concl rintr)))) rintrs);
 
@@ -345,7 +345,7 @@
 
     (** realizer for induction rule **)
 
-    val Ps = mapfilter (fn _ $ M $ P => if set_of M mem rsets then
+    val Ps = List.mapPartial (fn _ $ M $ P => if set_of M mem rsets then
       SOME (fst (fst (dest_Var (head_of P)))) else NONE)
         (HOLogic.dest_conj (HOLogic.dest_Trueprop (concl_of raw_induct)));
 
@@ -383,13 +383,13 @@
       let
         val (prem :: prems) = prems_of elim;
         fun reorder1 (p, intr) =
-          foldl (fn (t, ((s, _), T)) => all T $ lambda (Free (s, T)) t)
+          Library.foldl (fn (t, ((s, _), T)) => all T $ lambda (Free (s, T)) t)
             (strip_all p, Term.add_vars ([], prop_of intr) \\ params');
         fun reorder2 (intr, i) =
           let
             val fs1 = term_vars (prop_of intr) \\ params;
             val fs2 = Term.add_vars ([], prop_of intr) \\ params'
-          in foldl (fn (t, x) => lambda (Var x) t)
+          in Library.foldl (fn (t, x) => lambda (Var x) t)
             (list_comb (Bound (i + length fs1), fs1), fs2)
           end;
         val p = Logic.list_implies
@@ -423,24 +423,24 @@
 
     (** add realizers to theory **)
 
-    val rintr_thms = flat (map (fn (_, rs) => map (fn r => nth_elem
-      (find_index_eq r intrs, #intrs ind_info)) rs) rss);
-    val thy4 = foldl add_ind_realizer (thy3, subsets Ps);
+    val rintr_thms = List.concat (map (fn (_, rs) => map (fn r => List.nth
+      (#intrs ind_info, find_index_eq r intrs)) rs) rss);
+    val thy4 = Library.foldl add_ind_realizer (thy3, subsets Ps);
     val thy5 = Extraction.add_realizers_i
       (map (mk_realizer thy4 vs params')
          (map (fn ((rule, rrule), c) => ((rule, rrule), list_comb (c,
             map Var (rev (Term.add_vars ([], prop_of rule)) \\ params')))) 
-              (flat (map snd rss) ~~ rintr_thms ~~ flat constrss))) thy4;
-    val elimps = mapfilter (fn (s, intrs) => if s mem rsets then
-        apsome (rpair intrs) (find_first (fn (thm, _) =>
+              (List.concat (map snd rss) ~~ rintr_thms ~~ List.concat constrss))) thy4;
+    val elimps = List.mapPartial (fn (s, intrs) => if s mem rsets then
+        Option.map (rpair intrs) (find_first (fn (thm, _) =>
           s mem term_consts (hd (prems_of thm))) (elims ~~ #elims ind_info))
       else NONE) rss;
-    val thy6 = foldl (fn (thy, p as (((((elim, _), _), _), _), _)) => thy |>
+    val thy6 = Library.foldl (fn (thy, p as (((((elim, _), _), _), _), _)) => thy |>
       add_elim_realizer [] p |> add_elim_realizer [fst (fst (dest_Var
         (HOLogic.dest_Trueprop (concl_of elim))))] p) (thy5,
            elimps ~~ get #case_thms dt_info ~~ case_names ~~ dummies)
 
-  in Theory.add_path (NameSpace.pack (if_none path [])) thy6 end;
+  in Theory.add_path (NameSpace.pack (getOpt (path, []))) thy6 end;
 
 fun add_ind_realizers name rsets thy =
   let
@@ -452,7 +452,7 @@
     val vss = sort (int_ord o pairself length)
       (subsets (map fst (relevant_vars S)))
   in
-    foldl (add_ind_realizer rsets intrs induct raw_induct elims) (thy, vss)
+    Library.foldl (add_ind_realizer rsets intrs induct raw_induct elims) (thy, vss)
   end
 
 fun rlz_attrib arg (thy, thm) =
@@ -462,7 +462,7 @@
       (case HOLogic.dest_conj (HOLogic.dest_Trueprop (concl_of thm)) of
            [_] => [set_of (HOLogic.dest_Trueprop (hd (prems_of thm)))]
          | xs => map (set_of o fst o HOLogic.dest_imp) xs)
-         handle TERM _ => err () | LIST _ => err ();
+         handle TERM _ => err () | Empty => err ();
   in 
     (add_ind_realizers (hd sets) (case arg of
         NONE => sets | SOME NONE => []
--- a/src/HOL/Tools/meson.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/HOL/Tools/meson.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -164,7 +164,7 @@
  fun fewerlits(th1,th2) = nliterals(prop_of th1) < nliterals(prop_of th2);
 
  (*TAUTOLOGY CHECK SHOULD NOT BE NECESSARY!*)
- fun sort_clauses ths = sort (make_ord fewerlits) (filter (not o is_taut) ths);
+ fun sort_clauses ths = sort (make_ord fewerlits) (List.filter (not o is_taut) ths);
 
  (*Convert all suitable free variables to schematic variables*)
  fun generalize th = forall_elim_vars 0 (forall_intr_frees th);
@@ -188,12 +188,12 @@
      let fun name1 (th, (k,ths)) =
            (k-1, Thm.name_thm (label ^ string_of_int k, th) :: ths)
 
-     in  fn ths => #2 (foldr name1 (ths, (length ths, [])))  end;
+     in  fn ths => #2 (Library.foldr name1 (ths, (length ths, [])))  end;
 
  (*Find an all-negative support clause*)
  fun is_negative th = forall (not o #1) (literals (prop_of th));
 
- val neg_clauses = filter is_negative;
+ val neg_clauses = List.filter is_negative;
 
 
  (***** MESON PROOF PROCEDURE *****)
@@ -211,7 +211,7 @@
  fun has_reps [] = false
    | has_reps [_] = false
    | has_reps [t,u] = (t aconv u)
-   | has_reps ts = (foldl ins_term (Net.empty, ts);  false)
+   | has_reps ts = (Library.foldl ins_term (Net.empty, ts);  false)
                    handle INSERT => true;
 
  (*Like TRYALL eq_assume_tac, but avoids expensive THEN calls*)
@@ -239,7 +239,7 @@
 (*Sums the sizes of the subgoals, ignoring hypotheses (ancestors)*)
 local fun addconcl(prem,sz) = size_of_term(Logic.strip_assums_concl prem) + sz
 in
-fun size_of_subgoals st = foldr addconcl (prems_of st, 0)
+fun size_of_subgoals st = Library.foldr addconcl (prems_of st, 0)
 end;
 
 (*Negation Normal Form*)
@@ -265,12 +265,12 @@
 (*Make clauses from a list of theorems, previously Skolemized and put into nnf.
   The resulting clauses are HOL disjunctions.*)
 fun make_clauses ths =
-    sort_clauses (map (generalize o nodups) (foldr cnf (ths,[])));
+    sort_clauses (map (generalize o nodups) (Library.foldr cnf (ths,[])));
 
 (*Convert a list of clauses to (contrapositive) Horn clauses*)
 fun make_horns ths =
     name_thms "Horn#"
-      (gen_distinct Drule.eq_thm_prop (foldr (add_contras clause_rules) (ths,[])));
+      (gen_distinct Drule.eq_thm_prop (Library.foldr (add_contras clause_rules) (ths,[])));
 
 (*Could simply use nprems_of, which would count remaining subgoals -- no
   discrimination as to their size!  With BEST_FIRST, fails for problem 41.*)
--- a/src/HOL/Tools/primrec_package.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/HOL/Tools/primrec_package.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -76,7 +76,7 @@
         NONE =>
           (fname, (tname, rpos, [(cname, (ls, cargs, rs, rhs, eq))]))::rec_fns
       | SOME (_, rpos', eqns) =>
-          if is_some (assoc (eqns, cname)) then
+          if isSome (assoc (eqns, cname)) then
             raise RecError "constructor already occurred as pattern"
           else if rpos <> rpos' then
             raise RecError "position of recursive argument inconsistent"
@@ -90,7 +90,7 @@
 
 fun process_fun sign descr rec_eqns ((i, fname), (fnames, fnss)) =
   let
-    val (_, (tname, _, constrs)) = nth_elem (i, descr);
+    val (_, (tname, _, constrs)) = List.nth (descr, i);
 
     (* substitute "fname ls x rs" by "y ls rs" for (x, (_, y)) in subs *)
 
@@ -104,11 +104,11 @@
             if is_Const f andalso (fst (dest_Const f)) mem (map fst rec_eqns) then
               let
                 val (fname', _) = dest_Const f;
-                val (_, rpos, _) = the (assoc (rec_eqns, fname'));
-                val ls = take (rpos, ts);
-                val rest = drop (rpos, ts);
+                val (_, rpos, _) = valOf (assoc (rec_eqns, fname'));
+                val ls = Library.take (rpos, ts);
+                val rest = Library.drop (rpos, ts);
                 val (x', rs) = (hd rest, tl rest)
-                  handle LIST _ => raise RecError ("not enough arguments\
+                  handle Empty => raise RecError ("not enough arguments\
                    \ in recursive application\nof function " ^ quote fname' ^ " on rhs");
                 val (x, xs) = strip_comb x'
               in 
@@ -140,7 +140,7 @@
               (fnames', fnss', (Const ("arbitrary", dummyT))::fns))
         | SOME (ls, cargs', rs, rhs, eq) =>
             let
-              val recs = filter (is_rec_type o snd) (cargs' ~~ cargs);
+              val recs = List.filter (is_rec_type o snd) (cargs' ~~ cargs);
               val rargs = map fst recs;
               val subs = map (rpair dummyT o fst) 
 		             (rev (rename_wrt_term rhs rargs));
@@ -160,8 +160,8 @@
           raise RecError ("inconsistent functions for datatype " ^ quote tname)
         else
           let
-            val (_, _, eqns) = the (assoc (rec_eqns, fname));
-            val (fnames', fnss', fns) = foldr (trans eqns)
+            val (_, _, eqns) = valOf (assoc (rec_eqns, fname));
+            val (fnames', fnss', fns) = Library.foldr (trans eqns)
               (constrs, ((i, fname)::fnames, fnss, []))
           in
             (fnames', (i, (fname, #1 (snd (hd eqns)), fns))::fnss')
@@ -179,7 +179,7 @@
      NONE =>
        let
          val dummy_fns = map (fn (_, cargs) => Const ("arbitrary",
-           replicate ((length cargs) + (length (filter is_rec_type cargs)))
+           replicate ((length cargs) + (length (List.filter is_rec_type cargs)))
              dummyT ---> HOLogic.unitT)) constrs;
          val _ = warning ("No function definition for datatype " ^ quote tname)
        in
@@ -192,7 +192,7 @@
 
 fun make_def sign fs (fname, ls, rec_name, tname) =
   let
-    val rhs = foldr (fn (T, t) => Abs ("", T, t)) 
+    val rhs = Library.foldr (fn (T, t) => Abs ("", T, t)) 
 	            ((map snd ls) @ [dummyT],
 		     list_comb (Const (rec_name, dummyT),
 				fs @ map Bound (0 ::(length ls downto 1))));
@@ -216,10 +216,10 @@
   let
     fun constrs_of (_, (_, _, cs)) =
       map (fn (cname:string, (_, cargs, _, _, _)) => (cname, map fst cargs)) cs;
-    val params_of = Library.assocs (flat (map constrs_of rec_eqns));
+    val params_of = Library.assocs (List.concat (map constrs_of rec_eqns));
   in
     induction
-    |> RuleCases.rename_params (map params_of (flat (map (map #1 o #3 o #2) descr)))
+    |> RuleCases.rename_params (map params_of (List.concat (map (map #1 o #3 o #2) descr)))
     |> RuleCases.save induction
   end;
 
@@ -228,22 +228,22 @@
     val (eqns, atts) = split_list eqns_atts;
     val sg = Theory.sign_of thy;
     val dt_info = DatatypePackage.get_datatypes thy;
-    val rec_eqns = foldr (process_eqn sg) (map snd eqns, []);
+    val rec_eqns = Library.foldr (process_eqn sg) (map snd eqns, []);
     val tnames = distinct (map (#1 o snd) rec_eqns);
     val dts = find_dts dt_info tnames tnames;
     val main_fns = 
 	map (fn (tname, {index, ...}) =>
 	     (index, 
-	      fst (the (find_first (fn f => #1 (snd f) = tname) rec_eqns))))
+	      fst (valOf (find_first (fn f => #1 (snd f) = tname) rec_eqns))))
 	dts;
     val {descr, rec_names, rec_rewrites, ...} = 
 	if null dts then
 	    primrec_err ("datatypes " ^ commas_quote tnames ^ 
 			 "\nare not mutually recursive")
 	else snd (hd dts);
-    val (fnames, fnss) = foldr (process_fun sg descr rec_eqns)
+    val (fnames, fnss) = Library.foldr (process_fun sg descr rec_eqns)
 	                       (main_fns, ([], []));
-    val (fs, defs) = foldr (get_fns fnss) (descr ~~ rec_names, ([], []));
+    val (fs, defs) = Library.foldr (get_fns fnss) (descr ~~ rec_names, ([], []));
     val defs' = map (make_def sg fs) defs;
     val names1 = map snd fnames;
     val names2 = map fst rec_eqns;
--- a/src/HOL/Tools/prop_logic.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/HOL/Tools/prop_logic.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -275,7 +275,7 @@
 
 	(* prop_formula list -> prop_formula *)
 
-	fun exists xs = foldl SOr (False, xs);
+	fun exists xs = Library.foldl SOr (False, xs);
 
 (* ------------------------------------------------------------------------- *)
 (* all: computes the conjunction over a list 'xs' of propositional formulas  *)
@@ -283,7 +283,7 @@
 
 	(* prop_formula list -> prop_formula *)
 
-	fun all xs = foldl SAnd (True, xs);
+	fun all xs = Library.foldl SAnd (True, xs);
 
 (* ------------------------------------------------------------------------- *)
 (* dot_product: ([x1,...,xn], [y1,...,yn]) -> x1*y1+...+xn*yn                *)
--- a/src/HOL/Tools/recdef_package.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/HOL/Tools/recdef_package.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -91,7 +91,7 @@
     val (del, rest) = Library.partition (Library.equal c o fst) congs;
   in if null del then (warning ("No recdef congruence rule for " ^ quote c); congs) else rest end;
 
-val add_congs = curry (foldr (uncurry add_cong));
+val add_congs = curry (Library.foldr (uncurry add_cong));
 
 end;
 
@@ -255,7 +255,7 @@
     val (thy, (simps' :: rules', [induct'])) =
       thy
       |> Theory.add_path bname
-      |> PureThy.add_thmss ((("simps", flat rules), simp_att) :: ((eq_names ~~ rules) ~~ eq_atts))
+      |> PureThy.add_thmss ((("simps", List.concat rules), simp_att) :: ((eq_names ~~ rules) ~~ eq_atts))
       |>>> PureThy.add_thms [(("induct", induct), [])];
     val result = {simps = simps', rules = rules', induct = induct', tcs = tcs};
     val thy =
@@ -312,8 +312,8 @@
       (case get_recdef thy name of
         NONE => error ("No recdef definition of constant: " ^ quote name)
       | SOME {tcs, ...} => tcs);
-    val i = if_none opt_i 1;
-    val tc = Library.nth_elem (i - 1, tcs) handle Library.LIST _ =>
+    val i = getOpt (opt_i, 1);
+    val tc = List.nth (tcs, i - 1) handle Subscript =>
       error ("No termination condition #" ^ string_of_int i ^
         " in recdef definition of " ^ quote name);
   in
--- a/src/HOL/Tools/recfun_codegen.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/HOL/Tools/recfun_codegen.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -44,7 +44,7 @@
   in
     if Pattern.pattern (lhs_of thm) then
       (CodegenData.put (Symtab.update ((s,
-        thm :: if_none (Symtab.lookup (tab, s)) []), tab)) thy, thm)
+        thm :: getOpt (Symtab.lookup (tab, s), [])), tab)) thy, thm)
     else (warn thm; p)
   end handle TERM _ => (warn thm; p);
 
@@ -70,7 +70,7 @@
   (case Symtab.lookup (CodegenData.get thy, s) of
      NONE => []
    | SOME thms => preprocess thy (del_redundant thy []
-       (filter (fn thm => is_instance thy T
+       (List.filter (fn thm => is_instance thy T
          (snd (const_of (prop_of thm)))) thms)));
 
 fun mk_poly_id thy (s, T) = mk_const_id (sign_of thy) s ^
@@ -82,7 +82,7 @@
 
 fun cycle g (xs, x) =
   if x mem xs then xs
-  else foldl (cycle g) (x :: xs, flat (Graph.find_paths g (x, x)));
+  else Library.foldl (cycle g) (x :: xs, List.concat (Graph.find_paths g (x, x)));
 
 fun add_rec_funs thy gr dep eqs =
   let
@@ -125,10 +125,10 @@
              if not (dep mem xs) then
                let
                  val eqs'' = map (dest_eq o prop_of)
-                   (flat (map (get_equations thy) cs));
+                   (List.concat (map (get_equations thy) cs));
                  val (gr3, fundef') = mk_fundef "" "fun "
                    (Graph.add_edge (dname, dep)
-                     (foldr (uncurry Graph.new_node) (map (fn k =>
+                     (Library.foldr (uncurry Graph.new_node) (map (fn k =>
                        (k, (SOME (EQN ("", dummyT, dname)), ""))) xs,
                          Graph.del_nodes xs gr2))) eqs''
                in put_code fundef' gr3 end
--- a/src/HOL/Tools/record_package.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/HOL/Tools/record_package.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -160,7 +160,7 @@
 fun dest_recT (typ as Type (c_ext_type, Ts as (T::_))) =
       (case try (unsuffix ext_typeN) c_ext_type of
         NONE => raise TYPE ("RecordPackage.dest_recT", [typ], [])
-      | SOME c => ((c, Ts), last_elem Ts))
+      | SOME c => ((c, Ts), List.last Ts))
   | dest_recT typ = raise TYPE ("RecordPackage.dest_recT", [typ], []);
 
 fun is_recT T =
@@ -180,8 +180,8 @@
 
 fun rec_id i T = 
   let val rTs = dest_recTs T
-      val rTs' = if i < 0 then rTs else take (i,rTs)
-  in foldl (fn (s,(c,T)) => s ^ c) ("",rTs') end;
+      val rTs' = if i < 0 then rTs else Library.take (i,rTs)
+  in Library.foldl (fn (s,(c,T)) => s ^ c) ("",rTs') end;
 
 (*** extend theory by record definition ***)
 
@@ -426,11 +426,11 @@
     val varifyT = map_type_tfree varify;
     val {records,extfields,...} = RecordsData.get_sg sg;
     val (flds,(more,_)) = split_last (Symtab.lookup_multi (extfields,name));
-    val args = map varifyT (snd (#extension (the (Symtab.lookup (records,recname)))));
+    val args = map varifyT (snd (#extension (valOf (Symtab.lookup (records,recname)))));
 
     val tsig = Sign.tsig_of sg;
     fun unify (t,env) = Type.unify tsig env t;
-    val (subst,_) = foldr unify (but_last args ~~ but_last Ts,(Vartab.empty,0));
+    val (subst,_) = Library.foldr unify (but_last args ~~ but_last Ts,(Vartab.empty,0));
     val flds' = map (apsnd ((Envir.norm_type subst) o varifyT)) flds;
   in (flds',(more,moreT)) end;
 
@@ -449,7 +449,7 @@
   let
     val {records, sel_upd, equalities, extinjects, extsplit, splits, extfields, fieldext} = 
            RecordsData.get thy;
-    val fieldext' = foldl (fn (table,field) => Symtab.update_new ((field,extname_types),table))  
+    val fieldext' = Library.foldl (fn (table,field) => Symtab.update_new ((field,extname_types),table))  
                           (fieldext,fields);
     val data=make_record_data records sel_upd equalities extinjects extsplit 
               splits extfields fieldext';
@@ -473,11 +473,11 @@
 
         fun bad_inst ((x, S), T) =
           if Sign.of_sort sign (T, S) then NONE else SOME x
-        val bads = mapfilter bad_inst (args ~~ types);
+        val bads = List.mapPartial bad_inst (args ~~ types);
 
         val inst = map fst args ~~ types;
-        val subst = Term.map_type_tfree (fn (x, _) => the (assoc (inst, x)));
-        val parent' = apsome (apfst (map subst)) parent;
+        val subst = Term.map_type_tfree (fn (x, _) => valOf (assoc (inst, x)));
+        val parent' = Option.map (apfst (map subst)) parent;
         val fields' = map (apsnd subst) fields;
         val extension' = apsnd (map subst) extension;
       in
@@ -504,7 +504,7 @@
 
 
 fun record_update_tr [t, u] =
-      foldr (op $) (rev (gen_fields_tr "_updates" "_update" updateN u), t)
+      Library.foldr (op $) (rev (gen_fields_tr "_updates" "_update" updateN u), t)
   | record_update_tr ts = raise TERM ("record_update_tr", ts);
 
 fun update_name_tr (Free (x, T) :: ts) = Free (suffix updateN x, T) $$ ts
@@ -584,7 +584,7 @@
                        val (args,rest) = splitargs (map fst flds') fargs;
                        val vartypes = map Type.varifyT types;
                        val argtypes = map to_type args;
-                       val (subst,_) = foldr unify (vartypes ~~ argtypes,(Vartab.empty,0));
+                       val (subst,_) = Library.foldr unify (vartypes ~~ argtypes,(Vartab.empty,0));
                        val alphas' = map ((Syntax.term_of_typ (! Syntax.show_sorts)) o 
                                           (Envir.norm_type subst) o Type.varifyT) 
                                          (but_last alphas);
@@ -671,7 +671,7 @@
                           val flds' = Sign.extern sg Sign.constK f::map NameSpace.base fs; 
                           val (args',more) = split_last args; 
                          in (flds'~~args')@field_lst more end
-                         handle LIST _ => [("",t)]) 
+                         handle UnequalLengths => [("",t)])
                    | NONE => [("",t)])
              | NONE => [("",t)])
        | _ => [("",t)])
@@ -777,12 +777,12 @@
                                             ::map (apfst NameSpace.base) fs; 
                                 val (args',more) = split_last args; 
                                 val alphavars = map Type.varifyT (but_last alphas); 
-                                val (subst,_)= foldr unify (alphavars~~args',(Vartab.empty,0));
+                                val (subst,_)= Library.foldr unify (alphavars~~args',(Vartab.empty,0));
                                 val flds'' =map (apsnd ((Envir.norm_type subst)o(Type.varifyT)))
                                                 flds';
                               in flds''@field_lst more end
-                              handle TUNIFY => [("",T)] 
-                                   | LIST _=> [("",T)])
+                              handle TUNIFY         => [("",T)] 
+                                   | UnequalLengths => [("",T)])
                          | NONE => [("",T)])
                    | NONE => [("",T)])
              | NONE => [("",T)]) 
@@ -840,7 +840,7 @@
   let 
     val {sel_upd={simpset,...},extsplit,...} = RecordsData.get_sg sg;
     val extsplits = 
-            foldl (fn (thms,(n,_)) => (list (Symtab.lookup (extsplit,n)))@thms) 
+            Library.foldl (fn (thms,(n,_)) => (list (Symtab.lookup (extsplit,n)))@thms) 
                     ([],dest_recTs T);
     val thms = (case get_splits sg (rec_id (~1) T) of
                    SOME (all_thm,_,_,_) => 
@@ -854,7 +854,7 @@
 local
 
 fun get_fields extfields T = 
-     foldl (fn (xs,(eN,_))=>xs@(Symtab.lookup_multi (extfields,eN)))
+     Library.foldl (fn (xs,(eN,_))=>xs@(Symtab.lookup_multi (extfields,eN)))
              ([],(dest_recTs T));
 in
 (* record_simproc *)
@@ -974,10 +974,10 @@
               * updates again, the optimised term is constructed.
               *)
              fun mk_updterm upds already (t as ((upd as Const (u,uT)) $ k $ r)) =
-		 if is_some (Symtab.lookup (upds,u))
+		 if isSome (Symtab.lookup (upds,u))
 		 then let 
 			 fun rest already = mk_updterm upds already
-		      in if is_some (Symtab.lookup (already,u)) 
+		      in if isSome (Symtab.lookup (already,u)) 
 			 then (case (rest already r) of
 				 Init ((sprout,skel),vars) => 
                                  let
@@ -1146,8 +1146,8 @@
           (s = "all" orelse s = "All" orelse s = "Ex") andalso is_recT T 
         | _ => false);
 
-    val goal = Library.nth_elem (i - 1, Thm.prems_of st);
-    val frees = filter (is_recT o type_of) (term_frees goal);
+    val goal = List.nth (Thm.prems_of st, i - 1);
+    val frees = List.filter (is_recT o type_of) (term_frees goal);
 
     fun mk_split_free_tac free induct_thm i = 
 	let val cfree = cterm_of sg free;
@@ -1172,13 +1172,13 @@
                    end)
      | split_free_tac _ _ _ = NONE;
 
-    val split_frees_tacs = mapfilter (split_free_tac P i) frees;
+    val split_frees_tacs = List.mapPartial (split_free_tac P i) frees;
    
     val simprocs = if has_rec goal then [record_split_simproc P] else [];
    
   in st |> (EVERY split_frees_tacs) 
            THEN (Simplifier.full_simp_tac (simpset addsimps thms addsimprocs simprocs) i)
-  end handle Library.LIST _ => Seq.empty;
+  end handle Empty => Seq.empty;
 end;
 
 
@@ -1193,7 +1193,7 @@
           (s = "all" orelse s = "All") andalso is_recT T 
         | _ => false);
  
-    val goal = Library.nth_elem (i - 1, Thm.prems_of st);   
+    val goal = List.nth (Thm.prems_of st, i - 1);   
 
     fun is_all t =
       (case t of (Const (quantifier, _)$_) =>
@@ -1204,7 +1204,7 @@
      then Simplifier.full_simp_tac 
            (HOL_basic_ss addsimprocs [record_split_simproc is_all]) i st 
      else Seq.empty
-  end handle Library.LIST _ => Seq.empty;
+  end handle Subscript => Seq.empty;
 
 (* wrapper *)
 
@@ -1251,14 +1251,14 @@
 fun try_param_tac s rule i st =
   let
     val cert = cterm_of (Thm.sign_of_thm st);
-    val g = nth_elem (i - 1, prems_of st);
+    val g = List.nth (prems_of st, i - 1);
     val params = Logic.strip_params g;
     val concl = HOLogic.dest_Trueprop (Logic.strip_assums_concl g);
     val rule' = Thm.lift_rule (st, i) rule;
     val (P, ys) = strip_comb (HOLogic.dest_Trueprop
       (Logic.strip_assums_concl (prop_of rule')));
     (* ca indicates if rule is a case analysis or induction rule *)
-    val (x, ca) = (case rev (drop (length params, ys)) of
+    val (x, ca) = (case rev (Library.drop (length params, ys)) of
         [] => (head_of (fst (HOLogic.dest_eq (HOLogic.dest_Trueprop
           (hd (rev (Logic.strip_assums_hyp (hd (prems_of rule')))))))), true)
       | [x] => (head_of x, false));
@@ -1278,13 +1278,13 @@
 fun ex_inst_tac i st =
   let
     val sg = sign_of_thm st;
-    val g = nth_elem (i - 1, prems_of st);
+    val g = List.nth (prems_of st, i - 1);
     val params = Logic.strip_params g;
     val exI' = Thm.lift_rule (st, i) exI;
     val (_$(_$x)) = Logic.strip_assums_concl (hd (prems_of exI'));
     val cx = cterm_of sg (fst (strip_comb x));
 
-  in Seq.single (foldl (fn (st,v) => 
+  in Seq.single (Library.foldl (fn (st,v) => 
         Seq.hd 
         (compose_tac (false, cterm_instantiate 
                                 [(cx,cterm_of sg (list_abs (params,Bound v)))] exI',1) 
@@ -1307,7 +1307,7 @@
 
 fun mixit convs refls = 
   let fun f ((res,lhs,rhs),refl) = ((refl,List.revAppend (lhs,refl::tl rhs))::res,hd rhs::lhs,tl rhs);
-  in #1 (foldl f (([],[],convs),refls)) end;
+  in #1 (Library.foldl f (([],[],convs),refls)) end;
 
 fun extension_definition full name fields names alphas zeta moreT more vars thy = 
   let  
@@ -1332,7 +1332,7 @@
     val ext_decl = (mk_extC (name,extT) fields_moreTs);
     (*     
     val ext_spec = Const ext_decl :== 
-         (foldr (uncurry lambda) 
+         (Library.foldr (uncurry lambda) 
             (vars@[more],(mk_Abs name repT extT $ (foldr1 HOLogic.mk_prod (vars@[more]))))) 
     *) 
     val ext_spec = list_comb (Const ext_decl,vars@[more]) :== 
@@ -1484,7 +1484,7 @@
          (* freezeT just for performance, to adjust the maxidx, so that nodup_vars will not 
                 be called during combination *)
         fun mkthm (udef,(fld_refl,thms)) =
-          let val bdyeq = foldl (uncurry Thm.combination) (constr_refl,thms);
+          let val bdyeq = Library.foldl (uncurry Thm.combination) (constr_refl,thms);
                (* (|N=N (|N=N,M=M,K=K,more=more|)
                     M=M (|N=N,M=M,K=K,more=more|)
                     K=K'
@@ -1537,7 +1537,7 @@
    
 fun chunks []      []   = []
   | chunks []      xs   = [xs]
-  | chunks (l::ls) xs  = take (l,xs)::chunks ls (drop (l,xs));
+  | chunks (l::ls) xs  = Library.take (l,xs)::chunks ls (Library.drop (l,xs));
  
 fun chop_last [] = error "last: list should not be empty"
   | chop_last [x] = ([],x)
@@ -1551,7 +1551,7 @@
  * of parent extensions, starting with the root of the record hierarchy 
 *) 
 fun mk_recordT extT parent_exts = 
-    foldr (fn ((parent,Ts),T) => Type (parent, subst_last T Ts)) (parent_exts,extT);
+    Library.foldr (fn ((parent,Ts),T) => Type (parent, subst_last T Ts)) (parent_exts,extT);
 
 
 
@@ -1591,7 +1591,7 @@
 
     val (bfields, field_syntax) = split_list (map (fn (x, T, mx) => ((x, T), mx)) raw_fields);
 
-    val parent_fields = flat (map #fields parents);
+    val parent_fields = List.concat (map #fields parents);
     val parent_chunks = map (length o #fields) parents;
     val parent_names = map fst parent_fields;
     val parent_types = map snd parent_fields;
@@ -1605,7 +1605,7 @@
     val names = map fst fields;
     val extN = full bname;
     val types = map snd fields;
-    val alphas_fields = foldr add_typ_tfree_names (types,[]);
+    val alphas_fields = Library.foldr add_typ_tfree_names (types,[]);
     val alphas_ext = alphas inter alphas_fields; 
     val len = length fields;
     val variants = variantlist (map fst bfields, moreN::rN::rN ^ "'"::wN::parent_variants);
@@ -1647,7 +1647,7 @@
     val extension = let val (n,Ts) = extension_scheme in (n,subst_last HOLogic.unitT Ts) end; 
     val extension_names = 
          (map ((unsuffix ext_typeN) o fst o #extension) parents) @ [extN];
-    val extension_id = foldl (op ^) ("",extension_names);
+    val extension_id = Library.foldl (op ^) ("",extension_names);
 
  
     fun rec_schemeT n = mk_recordT extT (map #extension (prune n parents));
@@ -1663,7 +1663,7 @@
       let val (args',more) = chop_last args;
 	  fun mk_ext' (((name,T),args),more) = mk_ext (name,T) (args@[more]);
           fun build Ts = 
-           foldr mk_ext' (prune n (extension_names ~~ Ts ~~ (chunks parent_chunks args')),more) 
+           Library.foldr mk_ext' (prune n (extension_names ~~ Ts ~~ (chunks parent_chunks args')),more) 
       in 
         if more = HOLogic.unit 
         then build (map recT (0 upto parent_len)) 
@@ -1681,7 +1681,7 @@
 
     (* prepare print translation functions *)
     val field_tr's =
-      print_translation (distinct (flat (map NameSpace.accesses' (full_moreN :: names))));
+      print_translation (distinct (List.concat (map NameSpace.accesses' (full_moreN :: names))));
 
     val adv_ext_tr's =
     let
@@ -1822,13 +1822,13 @@
       end; 
 
     val split_object_prop =
-      let fun ALL vs t = foldr (fn ((v,T),t) => HOLogic.mk_all (v,T,t)) (vs,t)
+      let fun ALL vs t = Library.foldr (fn ((v,T),t) => HOLogic.mk_all (v,T,t)) (vs,t)
       in (ALL [dest_Free r0] (P $ r0)) === (ALL (map dest_Free all_vars_more) (P $ r_rec0))
       end;
 
 
     val split_ex_prop =
-      let fun EX vs t = foldr (fn ((v,T),t) => HOLogic.mk_exists (v,T,t)) (vs,t)
+      let fun EX vs t = Library.foldr (fn ((v,T),t) => HOLogic.mk_exists (v,T,t)) (vs,t)
       in (EX [dest_Free r0] (P $ r0)) === (EX (map dest_Free all_vars_more) (P $ r_rec0))
       end;
 
@@ -2041,14 +2041,14 @@
 
     fun prep_inst T = snd (cert_typ sign ([], T));
 
-    val parent = apsome (apfst (map prep_inst) o prep_raw_parent sign) raw_parent
+    val parent = Option.map (apfst (map prep_inst) o prep_raw_parent sign) raw_parent
       handle ERROR => error ("The error(s) above in parent record specification");
     val parents = add_parents thy parent [];
 
     val init_env =
       (case parent of
         NONE => []
-      | SOME (types, _) => foldr Term.add_typ_tfrees (types, []));
+      | SOME (types, _) => Library.foldr Term.add_typ_tfrees (types, []));
 
 
     (* fields *)
@@ -2065,7 +2065,7 @@
     (* args *)
 
     val defaultS = Sign.defaultS sign;
-    val args = map (fn x => (x, if_none (assoc (envir, x)) defaultS)) params;
+    val args = map (fn x => (x, getOpt (assoc (envir, x), defaultS))) params;
 
 
     (* errors *)
--- a/src/HOL/Tools/refute.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/HOL/Tools/refute.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -93,7 +93,7 @@
 	fun tree_foldl f =
 	let
 		fun itl (e, Leaf x)  = f(e,x)
-		  | itl (e, Node xs) = foldl (tree_foldl f) (e,xs)
+		  | itl (e, Node xs) = Library.foldl (tree_foldl f) (e,xs)
 	in
 		itl
 	end;
@@ -192,7 +192,7 @@
 			 parameters = Symtab.merge (op=) (pa1, pa2)};
 		fun print sg {interpreters, printers, parameters} =
 			Pretty.writeln (Pretty.chunks
-				[Pretty.strs ("default parameters:" :: flat (map (fn (name,value) => [name, "=", value]) (Symtab.dest parameters))),
+				[Pretty.strs ("default parameters:" :: List.concat (map (fn (name,value) => [name, "=", value]) (Symtab.dest parameters))),
 				 Pretty.strs ("interpreters:" :: map fst interpreters),
 				 Pretty.strs ("printers:" :: map fst printers)]);
 	end;
@@ -250,7 +250,7 @@
 			if null terms then
 				"empty interpretation (no free variables in term)\n"
 			else
-				space_implode "\n" (mapfilter (fn (t,intr) =>
+				space_implode "\n" (List.mapPartial (fn (t,intr) =>
 					(* print constants only if 'show_consts' is true *)
 					if (!show_consts) orelse not (is_Const t) then
 						SOME (Sign.string_of_term (sign_of thy) t ^ ": " ^ Sign.string_of_term (sign_of thy) (print thy model t intr assignment))
@@ -359,9 +359,9 @@
 		(* TODO: it is currently not possible to specify a size for a type     *)
 		(*       whose name is one of the other parameters (e.g. 'maxvars')    *)
 		(* (string * int) list *)
-		val sizes     = mapfilter
+		val sizes     = List.mapPartial
 			(fn (name,value) => (case Int.fromString value of SOME i => SOME (name, i) | NONE => NONE))
-			(filter (fn (name,_) => name<>"minsize" andalso name<>"maxsize" andalso name<>"maxvars" andalso name<>"maxtime" andalso name<>"satsolver")
+			(List.filter (fn (name,_) => name<>"minsize" andalso name<>"maxsize" andalso name<>"maxvars" andalso name<>"maxtime" andalso name<>"satsolver")
 				allparams)
 	in
 		{sizes=sizes, minsize=minsize, maxsize=maxsize, maxvars=maxvars, maxtime=maxtime, satsolver=satsolver}
@@ -382,12 +382,12 @@
 
 	fun typ_of_dtyp descr typ_assoc (DatatypeAux.DtTFree a) =
 		(* replace a 'DtTFree' variable by the associated type *)
-		(the o assoc) (typ_assoc, DatatypeAux.DtTFree a)
+		(valOf o assoc) (typ_assoc, DatatypeAux.DtTFree a)
 	  | typ_of_dtyp descr typ_assoc (DatatypeAux.DtType (s, ds)) =
 		Type (s, map (typ_of_dtyp descr typ_assoc) ds)
 	  | typ_of_dtyp descr typ_assoc (DatatypeAux.DtRec i) =
 		let
-			val (s, ds, _) = (the o assoc) (descr, i)
+			val (s, ds, _) = (valOf o assoc) (descr, i)
 		in
 			Type (s, map (typ_of_dtyp descr typ_assoc) ds)
 		end;
@@ -419,7 +419,7 @@
 	let
 		val _ = immediate_output "Adding axioms..."
 		(* (string * Term.term) list *)
-		val axioms = flat (map (Symtab.dest o #axioms o Theory.rep_theory) (thy :: Theory.ancestors_of thy))
+		val axioms = List.concat (map (Symtab.dest o #axioms o Theory.rep_theory) (thy :: Theory.ancestors_of thy))
 		(* string list *)
 		val rec_names = Symtab.foldl (fn (acc, (_, info)) =>
 			#rec_names info @ acc) ([], DatatypePackage.get_datatypes thy)
@@ -478,7 +478,7 @@
 					let
 						(* obtain the axioms generated by the "axclass" command *)
 						(* (string * Term.term) list *)
-						val class_axioms             = filter (fn (s, _) => String.isPrefix (class ^ ".axioms_") s) axioms
+						val class_axioms             = List.filter (fn (s, _) => String.isPrefix (class ^ ".axioms_") s) axioms
 						(* replace the one schematic type variable in each axiom by the actual type 'T' *)
 						(* (string * Term.term) list *)
 						val monomorphic_class_axioms = map (fn (axname, ax) =>
@@ -498,7 +498,7 @@
 								collect_term_axioms (ax :: axs, ax)
 							)
 					in
-						foldl collect_axiom (axs, monomorphic_class_axioms)
+						Library.foldl collect_axiom (axs, monomorphic_class_axioms)
 					end
 				(* string list *)
 				val sort = (case T of
@@ -509,7 +509,7 @@
 				(* string list *)
 				val superclasses = Graph.all_succs ((#classes o Type.rep_tsig o Sign.tsig_of o sign_of) thy) sort
 			in
-				foldl collect_class_axioms (axs, superclasses)
+				Library.foldl collect_class_axioms (axs, superclasses)
 			end
 		(* Term.term list * Term.typ -> Term.term list *)
 		and collect_type_axioms (axs, T) =
@@ -557,20 +557,20 @@
 					case DatatypePackage.datatype_info thy s of
 					  SOME info =>  (* inductive datatype *)
 							(* only collect relevant type axioms for the argument types *)
-							foldl collect_type_axioms (axs, Ts)
+							Library.foldl collect_type_axioms (axs, Ts)
 					| NONE =>
 						(case get_typedefn axioms of
 						  SOME (axname, ax) => 
 							if mem_term (ax, axs) then
 								(* only collect relevant type axioms for the argument types *)
-								foldl collect_type_axioms (axs, Ts)
+								Library.foldl collect_type_axioms (axs, Ts)
 							else
 								(immediate_output (" " ^ axname);
 								collect_term_axioms (ax :: axs, ax))
 						| NONE =>
 							(* unspecified type, perhaps introduced with 'typedecl' *)
 							(* at least collect relevant type axioms for the argument types *)
-							foldl collect_type_axioms (axs, Ts))
+							Library.foldl collect_type_axioms (axs, Ts))
 				end
 			| TFree _                => collect_sort_axioms (axs, T)  (* axiomatic type classes *)
 			| TVar _                 => collect_sort_axioms (axs, T)  (* axiomatic type classes *)
@@ -590,7 +590,7 @@
 			| Const ("arbitrary", T)          => collect_type_axioms (axs, T)
 			| Const ("The", T)                =>
 				let
-					val ax = specialize_type (("The", T), (the o assoc) (axioms, "HOL.the_eq_trivial"))
+					val ax = specialize_type (("The", T), (valOf o assoc) (axioms, "HOL.the_eq_trivial"))
 				in
 					if mem_term (ax, axs) then
 						collect_type_axioms (axs, T)
@@ -600,7 +600,7 @@
 				end
 			| Const ("Hilbert_Choice.Eps", T) =>
 				let
-					val ax = specialize_type (("Hilbert_Choice.Eps", T), (the o assoc) (axioms, "Hilbert_Choice.someI"))
+					val ax = specialize_type (("Hilbert_Choice.Eps", T), (valOf o assoc) (axioms, "Hilbert_Choice.someI"))
 				in
 					if mem_term (ax, axs) then
 						collect_type_axioms (axs, T)
@@ -686,7 +686,7 @@
 							val inclass = Logic.mk_inclass (TVar (("'a", 0), [class]), class)
 							(* Term.term option *)
 							val ofclass_ax = (SOME (specialize_type ((s, T), inclass)) handle Type.TYPE_MATCH => NONE)
-							val intro_ax   = (apsome (fn t => specialize_type ((s, T), t)) (assoc (axioms, class ^ ".intro")) handle Type.TYPE_MATCH => NONE)
+							val intro_ax   = (Option.map (fn t => specialize_type ((s, T), t)) (assoc (axioms, class ^ ".intro")) handle Type.TYPE_MATCH => NONE)
 							val axs'       = (case ofclass_ax of NONE => axs | SOME ax => if mem_term (ax, axs) then
 									(* collect relevant type axioms *)
 									collect_type_axioms (axs, T)
@@ -734,7 +734,7 @@
 			(* (Term.indexname * Term.typ) list *)
 			val vars = sort_wrt (fst o fst) (map dest_Var (term_vars t))
 		in
-			foldl
+			Library.foldl
 				(fn (t', ((x, i), T)) => (Term.all T) $ Abs (x, T, abstract_over (Var((x, i), T), t')))
 				(t, vars)
 		end
@@ -772,7 +772,7 @@
 						let
 							val index               = #index info
 							val descr               = #descr info
-							val (_, dtyps, constrs) = (the o assoc) (descr, index)
+							val (_, dtyps, constrs) = (valOf o assoc) (descr, index)
 							val typ_assoc           = dtyps ~~ Ts
 							(* sanity check: every element in 'dtyps' must be a 'DtTFree' *)
 							val _ = (if Library.exists (fn d =>
@@ -787,14 +787,14 @@
 								else
 									acc)
 							(* collect argument types *)
-							val acc_args = foldr collect_types (Ts, acc')
+							val acc_args = Library.foldr collect_types (Ts, acc')
 							(* collect constructor types *)
-							val acc_constrs = foldr collect_types (flat (map (fn (_, ds) => map (typ_of_dtyp descr typ_assoc) ds) constrs), acc_args)
+							val acc_constrs = Library.foldr collect_types (List.concat (map (fn (_, ds) => map (typ_of_dtyp descr typ_assoc) ds) constrs), acc_args)
 						in
 							acc_constrs
 						end
 					| NONE =>  (* not an inductive datatype, e.g. defined via "typedef" or "typedecl" *)
-						T ins (foldr collect_types (Ts, acc)))
+						T ins (Library.foldr collect_types (Ts, acc)))
 				| TFree _                => T ins acc
 				| TVar _                 => T ins acc)
 	in
@@ -853,9 +853,9 @@
 				NONE
 		  | make_first max len sum =
 			if sum<=max orelse max<0 then
-				apsome (fn xs' => sum :: xs') (make_first max (len-1) 0)
+				Option.map (fn xs' => sum :: xs') (make_first max (len-1) 0)
 			else
-				apsome (fn xs' => max :: xs') (make_first max (len-1) (sum-max))
+				Option.map (fn xs' => max :: xs') (make_first max (len-1) (sum-max))
 		(* enumerates all int lists with a fixed length, where 0<=x<='max' for *)
 		(* all list elements x (unless 'max'<0)                                *)
 		(* int -> int -> int -> int list -> int list option *)
@@ -867,12 +867,12 @@
 		  | next max len sum (x1::x2::xs) =
 			if x1>0 andalso (x2<max orelse max<0) then
 				(* we can shift *)
-				SOME (the (make_first max (len+1) (sum+x1-1)) @ (x2+1) :: xs)
+				SOME (valOf (make_first max (len+1) (sum+x1-1)) @ (x2+1) :: xs)
 			else
 				(* continue search *)
 				next max (len+1) (sum+x1) (x2::xs)
 		(* only consider those types for which the size is not fixed *)
-		val mutables = filter (fn (T, _) => assoc (sizes, string_of_typ T) = NONE) xs
+		val mutables = List.filter (fn (T, _) => assoc (sizes, string_of_typ T) = NONE) xs
 		(* subtract 'minsize' from every size (will be added again at the end) *)
 		val diffs = map (fn (_, n) => n-minsize) mutables
 	in
@@ -931,7 +931,7 @@
 			(* Term.term list *)
 			val axioms = collect_axioms thy t
 			(* Term.typ list *)
-			val types  = foldl (fn (acc, t') => acc union (ground_types thy t')) ([], t :: axioms)
+			val types  = Library.foldl (fn (acc, t') => acc union (ground_types thy t')) ([], t :: axioms)
 			val _      = writeln ("Ground types: "
 				^ (if null types then "none."
 				   else commas (map (Sign.string_of_typ (sign_of thy)) types)))
@@ -945,7 +945,7 @@
 						let
 							val index           = #index info
 							val descr           = #descr info
-							val (_, _, constrs) = (the o assoc) (descr, index)
+							val (_, _, constrs) = (valOf o assoc) (descr, index)
 						in
 							(* recursive datatype? *)
 							Library.exists (fn (_, ds) => Library.exists DatatypeAux.is_rec_type ds) constrs
@@ -1053,7 +1053,7 @@
 		(* (Term.indexname * Term.typ) list *)
 		val vars = sort_wrt (fst o fst) (map dest_Var (term_vars t))
 		(* Term.term *)
-		val ex_closure = foldl
+		val ex_closure = Library.foldl
 			(fn (t', ((x,i),T)) => (HOLogic.exists_const T) $ Abs (x, T, abstract_over (Var((x,i),T), t')))
 			(t, vars)
 		(* If 't' is of type 'propT' (rather than 'boolT'), applying  *)
@@ -1075,7 +1075,7 @@
 	(* theory -> (string * string) list -> Thm.thm -> int -> unit *)
 
 	fun refute_subgoal thy params thm subgoal =
-		refute_term thy params (nth_elem (subgoal, prems_of thm));
+		refute_term thy params (List.nth (prems_of thm, subgoal));
 
 
 (* ------------------------------------------------------------------------- *)
@@ -1116,7 +1116,7 @@
 			map (fn x => [x]) xs
 		  | pick_all n xs =
 			let val rec_pick = pick_all (n-1) xs in
-				foldl (fn (acc,x) => (cons_list x rec_pick) @ acc) ([],xs)
+				Library.foldl (fn (acc,x) => (cons_list x rec_pick) @ acc) ([],xs)
 			end
 	in
 		case intr of
@@ -1269,7 +1269,7 @@
 			map (fn x => [x]) xs
 		  | pick_all (xs::xss) =
 			let val rec_pick = pick_all xss in
-				foldl (fn (acc,x) => (cons_list x rec_pick) @ acc) ([],xs)
+				Library.foldl (fn (acc,x) => (cons_list x rec_pick) @ acc) ([],xs)
 			end
 		  | pick_all _ =
 			raise REFUTE ("interpretation_apply", "empty list (in pick_all)")
@@ -1296,8 +1296,8 @@
 	let
 		val Ts = binder_types (fastype_of t)
 	in
-		foldr (fn (T, t) => Abs ("<eta_expand>", T, t))
-			(take (i, Ts), list_comb (t, map Bound (i-1 downto 0)))
+		Library.foldr (fn (T, t) => Abs ("<eta_expand>", T, t))
+			(Library.take (i, Ts), list_comb (t, map Bound (i-1 downto 0)))
 	end;
 
 (* ------------------------------------------------------------------------- *)
@@ -1306,7 +1306,7 @@
 
 	(* int list -> int *)
 
-	fun sum xs = foldl op+ (0, xs);
+	fun sum xs = Library.foldl op+ (0, xs);
 
 (* ------------------------------------------------------------------------- *)
 (* product: returns the product of a list 'xs' of integers                   *)
@@ -1314,7 +1314,7 @@
 
 	(* int list -> int *)
 
-	fun product xs = foldl op* (1, xs);
+	fun product xs = Library.foldl op* (1, xs);
 
 (* ------------------------------------------------------------------------- *)
 (* size_of_dtyp: the size of (an initial fragment of) an inductive data type *)
@@ -1354,7 +1354,7 @@
 			(* unit -> (interpretation * model * arguments) option *)
 			fun interpret_groundtype () =
 			let
-				val size = (if T = Term.propT then 2 else (the o assoc) (typs, T))                    (* the model MUST specify a size for ground types *)
+				val size = (if T = Term.propT then 2 else (valOf o assoc) (typs, T))                    (* the model MUST specify a size for ground types *)
 				val next = next_idx+size
 				val _    = (if next-1>maxvars andalso maxvars>0 then raise MAXVARS_EXCEEDED else ())  (* check if 'maxvars' is large enough *)
 				(* prop_formula list *)
@@ -1416,7 +1416,7 @@
 			| Var (_, T)       =>
 				interpret_groundterm T
 			| Bound i          =>
-				SOME (nth_elem (i, #bounds args), model, args)
+				SOME (List.nth (#bounds args, i), model, args)
 			| Abs (x, T, body) =>
 				let
 					(* create all constants of type 'T' *)
@@ -1656,7 +1656,7 @@
 						let
 							val index               = #index info
 							val descr               = #descr info
-							val (_, dtyps, constrs) = (the o assoc) (descr, index)
+							val (_, dtyps, constrs) = (valOf o assoc) (descr, index)
 							val typ_assoc           = dtyps ~~ Ts
 							(* sanity check: every element in 'dtyps' must be a 'DtTFree' *)
 							val _ = (if Library.exists (fn d =>
@@ -1723,7 +1723,7 @@
 						let
 							val index               = #index info
 							val descr               = #descr info
-							val (_, dtyps, constrs) = (the o assoc) (descr, index)
+							val (_, dtyps, constrs) = (valOf o assoc) (descr, index)
 							val typ_assoc           = dtyps ~~ Ts'
 							(* sanity check: every element in 'dtyps' must be a 'DtTFree' *)
 							val _ = (if Library.exists (fn d =>
@@ -1846,7 +1846,7 @@
 									(* after it generate further elements                                    *)
 									val offset = size_of_dtyp thy typs' descr typ_assoc constrs1 +
 										(if is_rec_constr ctypes then
-											size_of_dtyp thy typs' descr typ_assoc (filter (not o is_rec_constr o snd) cs)
+											size_of_dtyp thy typs' descr typ_assoc (List.filter (not o is_rec_constr o snd) cs)
 										else
 											0)
 								in
@@ -1904,7 +1904,7 @@
 						let
 							val index               = #index info
 							val descr               = #descr info
-							val (_, dtyps, constrs) = (the o assoc) (descr, index)
+							val (_, dtyps, constrs) = (valOf o assoc) (descr, index)
 							(* the total number of constructors, including those of different    *)
 							(* (mutually recursive) datatypes within the same descriptor 'descr' *)
 							val constrs_count = sum (map (fn (_, (_, _, cs)) => length cs) descr)
@@ -1931,7 +1931,7 @@
 										end) ((model, args), params)
 									val (typs, terms) = model'
 									(* the type of a recursion operator: [T1, ..., Tn, IDT] ---> Tresult *)
-									val IDT       = nth_elem (constrs_count, binder_types T)
+									val IDT       = List.nth (binder_types T, constrs_count)
 									val typ_assoc = dtyps ~~ (snd o dest_Type) IDT
 									(* interpret each constructor of the datatype *)
 									(* TODO: we probably need to interpret every constructor in the descriptor, *)
@@ -1993,13 +1993,13 @@
 												  | select_subtree (Leaf _, _) =
 													raise REFUTE ("IDT_recursion_interpreter", "interpretation for parameter is a leaf; cannot select a subtree")
 												  | select_subtree (Node tr, x::xs) =
-													select_subtree (nth_elem (x, tr), xs)
+													select_subtree (List.nth (tr, x), xs)
 												(* select the correct subtree of the parameter corresponding to constructor 'c' *)
-												val p_intr = select_subtree (nth_elem (c, p_intrs), args)
+												val p_intr = select_subtree (List.nth (p_intrs, c), args)
 												(* find the indices of recursive arguments *)
-												val rec_args = map snd (filter (DatatypeAux.is_rec_type o fst) ((snd (nth_elem (c, constrs))) ~~ args))
+												val rec_args = map snd (List.filter (DatatypeAux.is_rec_type o fst) ((snd (List.nth (constrs, c))) ~~ args))
 												(* apply 'p_intr' to recursively computed results *)
-												val rec_p_intr = foldl (fn (i, n) => interpretation_apply (i, Array.sub (INTRS, n))) (p_intr, rec_args)
+												val rec_p_intr = Library.foldl (fn (i, n) => interpretation_apply (i, Array.sub (INTRS, n))) (p_intr, rec_args)
 												(* update 'INTRS' *)
 												val _ = Array.update (INTRS, elem, rec_p_intr)
 											in
@@ -2036,7 +2036,7 @@
 				val constants     = make_constants i_set
 				(* interpretation -> int *)
 				fun number_of_elements (Node xs) =
-					foldl (fn (n, x) =>
+					Library.foldl (fn (n, x) =>
 						if x=TT then
 							n+1
 						else if x=FF then
@@ -2214,7 +2214,7 @@
 					val HOLogic_empty_set = Const ("{}", HOLogic_setT)
 					val HOLogic_insert    = Const ("insert", HOLogic_prodT --> HOLogic_setT --> HOLogic_setT)
 				in
-					SOME (foldr (fn (pair, acc) => HOLogic_insert $ pair $ acc) (pairs, HOLogic_empty_set))
+					SOME (Library.foldr (fn (pair, acc) => HOLogic_insert $ pair $ acc) (pairs, HOLogic_empty_set))
 				end
 			| Type ("prop", [])      =>
 				(case index_from_interpretation intr of
@@ -2259,7 +2259,7 @@
 					  Node xs => xs
 					| _       => raise REFUTE ("set_printer", "interpretation for set type is a leaf"))
 				(* Term.term list *)
-				val elements = mapfilter (fn (arg, result) =>
+				val elements = List.mapPartial (fn (arg, result) =>
 					case result of
 					  Leaf [fmTrue, fmFalse] =>
 						if PropLogic.eval assignment fmTrue then
@@ -2275,7 +2275,7 @@
 				val HOLogic_empty_set = Const ("{}", HOLogic_setT)
 				val HOLogic_insert    = Const ("insert", T --> HOLogic_setT --> HOLogic_setT)
 			in
-				SOME (foldl (fn (acc, elem) => HOLogic_insert $ elem $ acc) (HOLogic_empty_set, elements))
+				SOME (Library.foldl (fn (acc, elem) => HOLogic_insert $ elem $ acc) (HOLogic_empty_set, elements))
 			end
 		| _ =>
 			NONE
@@ -2299,7 +2299,7 @@
 					val (typs, _)           = model
 					val index               = #index info
 					val descr               = #descr info
-					val (_, dtyps, constrs) = (the o assoc) (descr, index)
+					val (_, dtyps, constrs) = (valOf o assoc) (descr, index)
 					val typ_assoc           = dtyps ~~ Ts
 					(* sanity check: every element in 'dtyps' must be a 'DtTFree' *)
 					val _ = (if Library.exists (fn d =>
@@ -2345,7 +2345,7 @@
 										search (xs, 0)
 									end
 							in
-								apsome (fn args => (cTerm, cargs, args)) (get_args iC)
+								Option.map (fn args => (cTerm, cargs, args)) (get_args iC)
 							end
 						(* Term.term * DatatypeAux.dtyp list * int list *)
 						val (cTerm, cargs, args) = (case get_first get_constr_args constrs of
@@ -2359,10 +2359,10 @@
 									(* list, so there might be a more efficient implementation that does    *)
 									(* not generate all constants                                           *)
 							in
-								print thy (typs, []) (Free ("dummy", dT)) (nth_elem (n, consts)) assignment
+								print thy (typs, []) (Free ("dummy", dT)) (List.nth (consts, n)) assignment
 							end) (cargs ~~ args)
 					in
-						SOME (foldl op$ (cTerm, argsTerms))
+						SOME (Library.foldl op$ (cTerm, argsTerms))
 					end
 				end
 			| NONE =>  (* not an inductive datatype *)
--- a/src/HOL/Tools/refute_isar.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/HOL/Tools/refute_isar.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -48,7 +48,7 @@
 					val thy              = (Toplevel.theory_of state)
 					val thm              = ((snd o snd) (Proof.get_goal (Toplevel.proof_of state)))
 				in
-					Refute.refute_subgoal thy (if_none parms []) thm ((if_none subgoal 1)-1)
+					Refute.refute_subgoal thy (getOpt (parms, [])) thm ((getOpt (subgoal, 1))-1)
 				end)
 			);
 
@@ -79,7 +79,7 @@
 		in
 			Toplevel.theory (fn thy =>
 				let
-					val thy'               = add_params (thy, (if_none args []))
+					val thy'               = add_params (thy, (getOpt (args, [])))
 					val new_default_params = Refute.get_default_params thy'
 					val output             = if new_default_params=[] then "none" else (space_implode "\n" (map (fn (name,value) => name ^ "=" ^ value) new_default_params))
 				in
--- a/src/HOL/Tools/rewrite_hol_proof.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/HOL/Tools/rewrite_hol_proof.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -311,15 +311,15 @@
 fun mk_AbsP P t = AbsP ("H", P, t);
 
 fun elim_cong Ts (PThm (("HOL.iffD1", _), _, _, _) % _ % _ %% prf1 %% prf2) =
-      apsome (make_subst Ts prf2 []) (strip_cong [] prf1)
+      Option.map (make_subst Ts prf2 []) (strip_cong [] prf1)
   | elim_cong Ts (PThm (("HOL.iffD1", _), _, _, _) % P % _ %% prf) =
-      apsome (mk_AbsP P o make_subst Ts (PBound 0) [])
+      Option.map (mk_AbsP P o make_subst Ts (PBound 0) [])
         (strip_cong [] (incr_pboundvars 1 0 prf))
   | elim_cong Ts (PThm (("HOL.iffD2", _), _, _, _) % _ % _ %% prf1 %% prf2) =
-      apsome (make_subst Ts prf2 [] o
+      Option.map (make_subst Ts prf2 [] o
         apsnd (map (make_sym Ts))) (strip_cong [] prf1)
   | elim_cong Ts (PThm (("HOL.iffD2", _), _, _, _) % _ % P %% prf) =
-      apsome (mk_AbsP P o make_subst Ts (PBound 0) [] o
+      Option.map (mk_AbsP P o make_subst Ts (PBound 0) [] o
         apsnd (map (make_sym Ts))) (strip_cong [] (incr_pboundvars 1 0 prf))
   | elim_cong _ _ = NONE;
 
--- a/src/HOL/Tools/sat_solver.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/HOL/Tools/sat_solver.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -193,7 +193,7 @@
 			NONE
 		(* string -> int list *)
 		fun int_list_from_string s =
-			mapfilter (option o Int.fromString) (space_explode " " s)
+			List.mapPartial (option o Int.fromString) (space_explode " " s)
 		(* int list -> assignment *)
 		fun assignment_from_list [] i =
 			NONE  (* the SAT solver didn't provide a value for this variable *)
@@ -232,7 +232,7 @@
 			else
 				parse_lines lines
 	in
-		(parse_lines o (filter (fn l => l <> "")) o split_lines o File.read) path
+		(parse_lines o (List.filter (fn l => l <> "")) o split_lines o File.read) path
 	end;
 
 (* ------------------------------------------------------------------------- *)
@@ -310,10 +310,10 @@
 		o (map (map literal_from_int))
 		o clauses
 		o (map int_from_string)
-		o flat
+		o List.concat
 		o (map (String.fields (fn c => c mem [#" ", #"\t", #"\n"])))
 		o filter_preamble
-		o (filter (fn l => l <> ""))
+		o (List.filter (fn l => l <> ""))
 		o split_lines
 		o File.read)
 			path
@@ -343,7 +343,7 @@
 	(* string -> solver *)
 
 	fun invoke_solver name =
-		(the o assoc) (!solvers, name);
+		(valOf o assoc) (!solvers, name);
 
 end;  (* SatSolver *)
 
@@ -458,7 +458,7 @@
 				| False => NONE
 				| _     =>
 					let
-						val x = the (fresh_var xs')  (* a fresh variable must exist since 'fm' did not evaluate to 'True'/'False' *)
+						val x = valOf (fresh_var xs')  (* a fresh variable must exist since 'fm' did not evaluate to 'True'/'False' *)
 					in
 						case dpll (x::xs') fm' of  (* passing fm' rather than fm should save some simplification work *)
 						  SOME xs'' => SOME xs''
--- a/src/HOL/Tools/specification_package.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/HOL/Tools/specification_package.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -141,7 +141,7 @@
 		val tsig = Sign.tsig_of (sign_of thy)
 		val _ = assert (forall (fn v => Type.of_sort tsig (type_of v,HOLogic.typeS)) frees)
 			       "Specificaton: Only free variables of sort 'type' allowed"
-		val prop_closed = foldr (fn ((vname,T),prop) => HOLogic.mk_all (vname,T,prop)) (map dest_Free frees,prop)
+		val prop_closed = Library.foldr (fn ((vname,T),prop) => HOLogic.mk_all (vname,T,prop)) (map dest_Free frees,prop)
 	    in
 		(prop_closed,frees)
 	    end
@@ -164,7 +164,7 @@
 		val c' = fst (Type.varify (c,[]))
 		val (cname,ctyp) = dest_Const c'
 	    in
-		case filter (fn t => let val (name,typ) = dest_Const t
+		case List.filter (fn t => let val (name,typ) = dest_Const t
 				     in name = cname andalso typ_equiv typ ctyp
 				     end) thawed_prop_consts of
 		    [] => error ("Specification: No suitable instances of constant \"" ^ (Sign.string_of_term sg c) ^ "\" found")
@@ -182,7 +182,7 @@
 	    in
 		HOLogic.exists_const T $ Abs(vname,T,Term.abstract_over (c,prop))
 	    end
-	val ex_prop = foldr mk_exist (proc_consts,prop)
+	val ex_prop = Library.foldr mk_exist (proc_consts,prop)
 	val cnames = map (fst o dest_Const) proc_consts
 	fun post_process (arg as (thy,thm)) =
 	    let
@@ -194,7 +194,7 @@
 		    in
 			thm RS spec'
 		    end
-		fun remove_alls frees thm = foldl (inst_all (sign_of_thm thm)) (thm,frees)
+		fun remove_alls frees thm = Library.foldl (inst_all (sign_of_thm thm)) (thm,frees)
 		fun process_single ((name,atts),rew_imp,frees) args =
 		    let
 			fun undo_imps thm =
--- a/src/HOL/Tools/split_rule.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/HOL/Tools/split_rule.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -66,7 +66,7 @@
 (* complete splitting of partially splitted rules *)
 
 fun ap_split' (T::Ts) U u = Abs ("v", T, ap_split' Ts U
-      (ap_split T (flat (map HOLogic.prodT_factors Ts) ---> U)
+      (ap_split T (List.concat (map HOLogic.prodT_factors Ts) ---> U)
         (incr_boundvars 1 u) $ Bound 0))
   | ap_split' _ _ u = u;
 
@@ -74,9 +74,9 @@
       let
         val cterm = Thm.cterm_of (#sign (Thm.rep_thm rl))
         val (Us', U') = strip_type T;
-        val Us = take (length ts, Us');
-        val U = drop (length ts, Us') ---> U';
-        val T' = flat (map HOLogic.prodT_factors Us) ---> U;
+        val Us = Library.take (length ts, Us');
+        val U = Library.drop (length ts, Us') ---> U';
+        val T' = List.concat (map HOLogic.prodT_factors Us) ---> U;
         fun mk_tuple ((xs, insts), v as Var ((a, _), T)) =
               let
                 val Ts = HOLogic.prodT_factors T;
@@ -87,7 +87,7 @@
           | mk_tuple (x, _) = x;
         val newt = ap_split' Us U (Var (v, T'));
         val cterm = Thm.cterm_of (#sign (Thm.rep_thm rl));
-        val (vs', insts) = foldl mk_tuple ((vs, []), ts);
+        val (vs', insts) = Library.foldl mk_tuple ((vs, []), ts);
       in
         (instantiate ([], [(cterm t, cterm newt)] @ insts) rl, vs')
       end
@@ -96,19 +96,19 @@
 fun collect_vars (vs, Abs (_, _, t)) = collect_vars (vs, t)
   | collect_vars (vs, t) = (case strip_comb t of
         (v as Var _, ts) => (v, ts)::vs
-      | (t, ts) => foldl collect_vars (vs, ts));
+      | (t, ts) => Library.foldl collect_vars (vs, ts));
 
 
 val split_rule_var = Drule.standard o remove_internal_split o split_rule_var';
 
 (*curries ALL function variables occurring in a rule's conclusion*)
 fun split_rule rl =
-  foldr split_rule_var' (Term.term_vars (concl_of rl), rl)
+  Library.foldr split_rule_var' (Term.term_vars (concl_of rl), rl)
   |> remove_internal_split
   |> Drule.standard;
 
 fun complete_split_rule rl =
-  fst (foldr complete_split_rule_var
+  fst (Library.foldr complete_split_rule_var
     (collect_vars ([], concl_of rl),
       (rl, map (fst o fst o dest_Var) (Term.term_vars (#prop (Thm.rep_thm rl))))))
   |> remove_internal_split
@@ -121,7 +121,7 @@
 fun split_rule_goal xss rl =
   let
     fun one_split i (th, s) = Tactic.rule_by_tactic (pair_tac s i) th;
-    fun one_goal (xs, i) th = foldl (one_split i) (th, xs);
+    fun one_goal (xs, i) th = Library.foldl (one_split i) (th, xs);
   in
     Drule.standard (Simplifier.full_simplify split_rule_ss (Library.foldln one_goal xss rl))
     |> RuleCases.save rl
--- a/src/HOL/Tools/typedef_package.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/HOL/Tools/typedef_package.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -104,9 +104,9 @@
     val thms = PureThy.get_thmss thy (map (rpair NONE) witn_names) @ witn_thms;
     val tac =
       witn1_tac THEN
-      TRY (rewrite_goals_tac (filter is_def thms)) THEN
+      TRY (rewrite_goals_tac (List.filter is_def thms)) THEN
       TRY (REPEAT_FIRST (resolve_tac (filter_out is_def thms))) THEN
-      if_none witn2_tac (TRY (ALLGOALS (CLASET' blast_tac)));
+      getOpt (witn2_tac, TRY (ALLGOALS (CLASET' blast_tac)));
   in
     message ("Proving non-emptiness of set " ^ quote (string_of_cterm cset) ^ " ...");
     Tactic.prove (Theory.sign_of thy) [] [] goal (K tac)
@@ -144,12 +144,12 @@
     val goal_pat = mk_nonempty (Var (vname, setT));
 
     (*lhs*)
-    val lhs_tfrees = map (fn v => (v, if_none (assoc (rhs_tfrees, v)) HOLogic.typeS)) vs;
+    val lhs_tfrees = map (fn v => (v, getOpt (assoc (rhs_tfrees, v), HOLogic.typeS))) vs;
     val tname = Syntax.type_name t mx;
     val full_tname = full tname;
     val newT = Type (full_tname, map TFree lhs_tfrees);
 
-    val (Rep_name, Abs_name) = if_none opt_morphs ("Rep_" ^ name, "Abs_" ^ name);
+    val (Rep_name, Abs_name) = getOpt (opt_morphs, ("Rep_" ^ name, "Abs_" ^ name));
     val setC = Const (full_name, setT);
     val RepC = Const (full Rep_name, newT --> oldT);
     val AbsC = Const (full Abs_name, oldT --> newT);
@@ -251,7 +251,7 @@
 
 fun sane_typedef prep_term def opt_name typ set opt_morphs tac =
   gen_typedef prep_term def
-    (if_none opt_name (#1 typ)) typ set opt_morphs all_tac [] [] (SOME tac);
+    (getOpt (opt_name, #1 typ)) typ set opt_morphs all_tac [] [] (SOME tac);
 
 fun add_typedef_x name typ set names thms tac =
   #1 o gen_typedef read_term true name typ set NONE (Tactic.rtac exI 1) names thms tac;
@@ -287,8 +287,8 @@
       in SOME (gr'', Codegen.mk_app brack (Pretty.str id) ps) end;
     fun get_name (Type (tname, _)) = tname
       | get_name _ = "";
-    fun lookup f T = if_none (apsome f (Symtab.lookup
-      (TypedefData.get thy, get_name T))) ""
+    fun lookup f T = getOpt (Option.map f (Symtab.lookup
+      (TypedefData.get thy, get_name T)), "")
   in
     (case strip_comb t of
        (Const (s, Type ("fun", [T, U])), ts) =>
@@ -310,7 +310,7 @@
       (case Symtab.lookup (TypedefData.get thy, s) of
          NONE => NONE
        | SOME (newT as Type (tname, Us), oldT, Abs_name, Rep_name) =>
-           if is_some (Codegen.get_assoc_type thy tname) then NONE else
+           if isSome (Codegen.get_assoc_type thy tname) then NONE else
            let
              val sg = sign_of thy;
              val Abs_id = Codegen.mk_const_id sg Abs_name;
@@ -382,7 +382,7 @@
     Scan.option (P.$$$ "morphisms" |-- P.!!! (P.name -- P.name));
 
 fun mk_typedef_proof ((((((def, opt_name), (vs, t)), mx), A), morphs)) =
-  typedef_proof ((def, if_none opt_name (Syntax.type_name t mx)), (t, vs, mx), A, morphs);
+  typedef_proof ((def, getOpt (opt_name, Syntax.type_name t mx)), (t, vs, mx), A, morphs);
 
 val typedefP =
   OuterSyntax.command "typedef" "HOL type definition (requires non-emptiness proof)" K.thy_goal
--- a/src/HOL/arith_data.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/HOL/arith_data.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -25,7 +25,7 @@
 
 (*normal form of sums: Suc (... (Suc (a + (b + ...))))*)
 fun mk_norm_sum ts =
-  let val (ones, sums) = partition (equal one) ts in
+  let val (ones, sums) = List.partition (equal one) ts in
     funpow (length ones) HOLogic.mk_Suc (mk_sum sums)
   end;
 
--- a/src/HOL/cladata.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/HOL/cladata.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -33,7 +33,7 @@
 (*prevent substitution on bool*)
 fun hyp_subst_tac' i thm = if i <= Thm.nprems_of thm andalso
   Term.exists_Const (fn ("op =", Type (_, [T, _])) => T <> Type ("bool", []) | _ => false)
-    (Library.nth_elem (i - 1, Thm.prems_of thm)) then hyp_subst_tac i thm else no_tac thm;
+    (List.nth (Thm.prems_of thm, i - 1)) then hyp_subst_tac i thm else no_tac thm;
 
 
 
--- a/src/HOL/eqrule_HOL_data.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/HOL/eqrule_HOL_data.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -45,14 +45,14 @@
              (case Term.head_of p of
                 Const(a,_) =>
                   (case Library.assoc(pairs,a) of
-                     SOME(rls) => flat (map atoms ([th] RL rls))
+                     SOME(rls) => List.concat (map atoms ([th] RL rls))
                    | NONE => [th])
               | _ => [th])
          | _ => [th])
   in atoms end;
 
 val prep_meta_eq = 
-    (mapfilter  
+    (List.mapPartial  
        mk_eq
        o (mk_atomize tranformation_pairs)
        o Drule.gen_all 
--- a/src/HOL/ex/svc_funcs.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/HOL/ex/svc_funcs.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -44,11 +44,11 @@
 
  fun toString t =
      let fun ue (Buildin(s, l)) = 
-	     "(" ^ s ^ (foldl (fn (a, b) => a ^ " " ^ (ue b)) ("", l)) ^ ") "
+	     "(" ^ s ^ (Library.foldl (fn (a, b) => a ^ " " ^ (ue b)) ("", l)) ^ ") "
 	   | ue (Interp(s, l)) = 
-	     "{" ^ s ^ (foldl (fn (a, b) => a ^ " " ^ (ue b)) ("", l)) ^ "} "
+	     "{" ^ s ^ (Library.foldl (fn (a, b) => a ^ " " ^ (ue b)) ("", l)) ^ "} "
 	   | ue (UnInterp(s, l)) = 
-	     "(" ^ s ^ (foldl (fn (a, b) => a ^ " " ^ (ue b)) ("", l)) ^ ") "
+	     "(" ^ s ^ (Library.foldl (fn (a, b) => a ^ " " ^ (ue b)) ("", l)) ^ ") "
 	   | ue (FalseExpr) = "FALSE "
 	   | ue (TrueExpr)  = "TRUE "
 	   | ue (Int i)     = (signedInt i) ^ " "
@@ -243,7 +243,7 @@
 
       val body_e = mt pos body  (*evaluate now to assign into !nat_vars*)
   in 
-     foldr add_nat_var (!nat_vars, body_e) 
+     Library.foldr add_nat_var (!nat_vars, body_e) 
   end;
 
 
--- a/src/HOL/hologic.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/HOL/hologic.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -148,7 +148,7 @@
 
 fun all_const T = Const ("All", [T --> boolT] ---> boolT);
 fun mk_all (x, T, P) = all_const T $ absfree (x, T, P);
-val list_all = foldr (fn ((x, T), P) => all_const T $ Abs (x, T, P));
+val list_all = Library.foldr (fn ((x, T), P) => all_const T $ Abs (x, T, P));
 
 fun exists_const T = Const ("Ex", [T --> boolT] ---> boolT);
 fun mk_exists (x, T, P) = exists_const T $ absfree (x, T, P);
@@ -237,7 +237,7 @@
 (*Makes a nested tuple from a list, following the product type structure*)
 fun mk_tuple (Type ("*", [T1, T2])) tms = 
         mk_prod (mk_tuple T1 tms, 
-                 mk_tuple T2 (drop (length (prodT_factors T1), tms)))
+                 mk_tuple T2 (Library.drop (length (prodT_factors T1), tms)))
   | mk_tuple T (t::_) = t;
 
 
@@ -246,13 +246,13 @@
 
 local  (*currently unused*)
 
-fun mk_tupleT Ts = foldr mk_prodT (Ts, unitT);
+fun mk_tupleT Ts = Library.foldr mk_prodT (Ts, unitT);
 
 fun dest_tupleT (Type ("Product_Type.unit", [])) = []
   | dest_tupleT (Type ("*", [T, U])) = T :: dest_tupleT U
   | dest_tupleT T = raise TYPE ("dest_tupleT", [T], []);
 
-fun mk_tuple ts = foldr mk_prod (ts, unit);
+fun mk_tuple ts = Library.foldr mk_prod (ts, unit);
 
 fun dest_tuple (Const ("Product_Type.Unity", _)) = []
   | dest_tuple (Const ("Pair", _) $ t $ u) = t :: dest_tuple u
--- a/src/HOL/simpdata.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/HOL/simpdata.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -253,14 +253,14 @@
              (case head_of p of
                 Const(a,_) =>
                   (case assoc(pairs,a) of
-                     SOME(rls) => flat (map atoms ([th] RL rls))
+                     SOME(rls) => List.concat (map atoms ([th] RL rls))
                    | NONE => [th])
               | _ => [th])
          | _ => [th])
   in atoms end;
 
 fun mksimps pairs =
-  (mapfilter (try mk_eq) o mk_atomize pairs o gen_all);
+  (List.mapPartial (try mk_eq) o mk_atomize pairs o gen_all);
 
 fun unsafe_solver_tac prems =
   FIRST'[resolve_tac(reflexive_thm::TrueI::refl::prems), atac, etac FalseE];
--- a/src/HOL/thy_syntax.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/HOL/thy_syntax.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -14,7 +14,7 @@
 
 fun mk_typedef_decl (((((opt_name, vs), t), mx), rhs), wt) =
   let
-    val name' = if_none opt_name t;
+    val name' = getOpt (opt_name,t);
     val name = unenclose name';
   in
     (cat_lines [name', mk_triple (t, mk_list vs, mx), rhs, wt],
@@ -101,11 +101,11 @@
           fun mk_dt_struct (s, (id, i)) =
             s ^ "structure " ^ id ^ " =\n\
             \struct\n\
-            \  val distinct = nth_elem (" ^ i ^ ", distinct);\n\
-            \  val inject = nth_elem (" ^ i ^ ", inject);\n\
-            \  val exhaust = nth_elem (" ^ i ^ ", exhaustion);\n\
-            \  val cases = nth_elem (" ^ i ^ ", case_thms);\n\
-            \  val (split, split_asm) = nth_elem (" ^ i ^ ", split_thms);\n" ^
+            \  val distinct = List.nth (distinct, " ^ i ^ ");\n\
+            \  val inject = List.nth (inject, " ^ i ^ ");\n\
+            \  val exhaust = List.nth (exhaustion, " ^ i ^ ");\n\
+            \  val cases = List.nth (case_thms, " ^ i ^ ");\n\
+            \  val (split, split_asm) = List.nth (split_thms, " ^ i ^ ");\n" ^
               (if length names = 1 then
                  "  val induct = induction;\n\
                  \  val recs = rec_thms;\n\
@@ -114,7 +114,7 @@
                else "") ^
             "end;\n";
 
-          val structs = foldl mk_dt_struct
+          val structs = Library.foldl mk_dt_struct
             ("", (names ~~ (map string_of_int (0 upto length names - 1))));
 
         in
@@ -131,7 +131,7 @@
   fun mk_dt_string dts =
     let
       val names = map (fn ((((alt_name, _), name), _), _) =>
-        unenclose (if_none alt_name name)) dts;
+        unenclose (getOpt (alt_name,name))) dts;
 
       val add_datatype_args = brackets (commas (map Library.quote names)) ^ " " ^
         brackets (commas (map (fn ((((_, vs), name), mx), cs) =>
--- a/src/HOLCF/IOA/Modelcheck/MuIOAOracle.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/HOLCF/IOA/Modelcheck/MuIOAOracle.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -2,7 +2,7 @@
 (* call_sim_tac invokes oracle "Sim" *)
 fun call_sim_tac thm_list i state = 
 let val sign = #sign (rep_thm state);
-        val (subgoal::_) = drop(i-1,prems_of state);
+        val (subgoal::_) = Library.drop(i-1,prems_of state);
         val OraAss = invoke_oracle MuIOAOracle.thy "Sim" (sign,SimOracleExn (subgoal,thm_list));
 in
 (cut_facts_tac [OraAss] i) state
@@ -13,7 +13,7 @@
 fun is_sim_tac thm_list i state =
 let val sign = #sign (rep_thm state);
 in
-case drop(i-1,prems_of state) of
+case Library.drop(i-1,prems_of state) of
         [] => PureGeneral.Seq.empty |
         subgoal::_ => EVERY[REPEAT(etac thin_rl i),
                         simp_tac (simpset() addsimps [ioa_implements_def]) i,
--- a/src/HOLCF/IOA/meta_theory/Sequence.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/HOLCF/IOA/meta_theory/Sequence.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -1012,7 +1012,7 @@
 fun all_frees_tac x i thm =
   let
     val tsig = Sign.tsig_of (Thm.sign_of_thm thm);
-    val frees = add_frees tsig (nth_elem (i - 1, prems_of thm), [x]);
+    val frees = add_frees tsig (List.nth (prems_of thm, i - 1), [x]);
     val frees' = sort (op >) (frees \ x) @ [x];
   in
     foldl (qnt_tac i) (all_tac, frees') thm
--- a/src/HOLCF/adm.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/HOLCF/adm.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -40,7 +40,7 @@
       if i = lev then [[(Bound 0, path)]]
       else []
   | find_subterms (t as (Abs (_, _, t2))) lev path =
-      if filter (fn x => x<=lev)
+      if List.filter (fn x => x<=lev)
            (add_loose_bnos (t, 0, [])) = [lev] then
         [(incr_bv (~lev, 0, t), path)]::
         (find_subterms t2 (lev+1) (0::path))
@@ -52,7 +52,7 @@
             | combine (x::xs) ys =
                 (map (fn z => x @ z) ys) @ (combine xs ys)
       in
-        (if filter (fn x => x<=lev)
+        (if List.filter (fn x => x<=lev)
               (add_loose_bnos (t, 0, [])) = [lev] then
            [[(incr_bv (~lev, 0, t), path)]]
          else []) @
@@ -116,7 +116,7 @@
       val tsig = Sign.tsig_of sign;
       val parTs = map snd (rev params);
       val rule = lift_rule (state, i) adm_subst;
-      val types = the o (fst (types_sorts rule));
+      val types = valOf o (fst (types_sorts rule));
       val tT = types ("t", j);
       val PT = types ("P", j);
       fun mk_abs [] t = t
@@ -135,7 +135,7 @@
 
 (*** extract subgoal i from proof state ***)
 
-fun nth_subgoal i thm = nth_elem (i-1, prems_of thm);
+fun nth_subgoal i thm = List.nth (prems_of thm, i-1);
 
 
 (*** the admissibility tactic ***)
@@ -155,9 +155,9 @@
           val prems = Logic.strip_assums_hyp goali;
           val params = Logic.strip_params goali;
           val ts = find_subterms t 0 [];
-          val ts' = filter eq_terms ts;
-          val ts'' = filter (is_chfin sign T params) ts';
-          val thms = foldl (prove_cont tac sign s T prems params) ([], ts'');
+          val ts' = List.filter eq_terms ts;
+          val ts'' = List.filter (is_chfin sign T params) ts';
+          val thms = Library.foldl (prove_cont tac sign s T prems params) ([], ts'');
         in
           (case thms of
             ((ts as ((t', _)::_), cont_thm)::_) =>
--- a/src/HOLCF/cont_consts.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/HOLCF/cont_consts.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -43,7 +43,7 @@
   val vnames = argnames (ord "A") n;
   val extra_parse_rule = Syntax.ParseRule (Constant name2, Constant name1);
   in [Syntax.ParsePrintRule (Syntax.mk_appl (Constant name2) (map Variable vnames),
-                          foldl (fn (t,arg) => (Syntax.mk_appl (Constant "Rep_CFun")
+                          Library.foldl (fn (t,arg) => (Syntax.mk_appl (Constant "Rep_CFun")
                                                 [t,Variable arg]))
                           (Constant name1,vnames))]
      @(case mx of InfixName _ => [extra_parse_rule]
@@ -94,7 +94,7 @@
     |> Theory.add_consts_i normal_decls
     |> Theory.add_consts_i (map first transformed_decls)
     |> Theory.add_syntax_i (map second transformed_decls)
-    |> Theory.add_trrules_i (flat (map third transformed_decls))
+    |> Theory.add_trrules_i (List.concat (map third transformed_decls))
   end;
 
 val add_consts = gen_add_consts Thm.read_ctyp;
--- a/src/HOLCF/domain/axioms.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/HOLCF/domain/axioms.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -31,7 +31,7 @@
  val rep_iso_ax = ("rep_iso" ,mk_trp(dc_abs`(dc_rep`%x_name')=== %:x_name'));
 
   val when_def = ("when_def",%%:(dname^"_when") == 
-     foldr (uncurry /\ ) (when_funs cons, /\x_name'((when_body cons (fn (x,y) =>
+     Library.foldr (uncurry /\ ) (when_funs cons, /\x_name'((when_body cons (fn (x,y) =>
 				Bound(1+length cons+x-y)))`(dc_rep`Bound 0))));
 
   fun con_def outer recu m n (_,args) = let
@@ -43,10 +43,10 @@
      fun inj y 1 _ = y
      |   inj y _ 0 = %%:"sinl"`y
      |   inj y i j = %%:"sinr"`(inj y (i-1) (j-1));
-  in foldr /\# (args, outer (inj (parms args) m n)) end;
+  in Library.foldr /\# (args, outer (inj (parms args) m n)) end;
 
   val copy_def = ("copy_def", %%:(dname^"_copy") == /\"f" (dc_abs oo 
-	foldl (op `) (%%:(dname^"_when") , 
+	Library.foldl (op `) (%%:(dname^"_when") , 
 	              mapn (con_def Id true (length cons)) 0 cons)));
 
 (* -- definitions concerning the constructors, discriminators and selectors - *)
@@ -57,7 +57,7 @@
   val dis_defs = let
 	fun ddef (con,_) = (dis_name con ^"_def",%%:(dis_name con) == 
 		 mk_cRep_CFun(%%:(dname^"_when"),map 
-			(fn (con',args) => (foldr /\#
+			(fn (con',args) => (Library.foldr /\#
 			   (args,if con'=con then %%:"TT" else %%:"FF"))) cons))
 	in map ddef cons end;
 
@@ -65,8 +65,8 @@
 	fun sdef con n arg = (sel_of arg^"_def",%%:(sel_of arg) == 
 		 mk_cRep_CFun(%%:(dname^"_when"),map 
 			(fn (con',args) => if con'<>con then %%:"UU" else
-			 foldr /\# (args,Bound (length args - n))) cons));
-	in flat(map (fn (con,args) => mapn (sdef con) 1 args) cons) end;
+			 Library.foldr /\# (args,Bound (length args - n))) cons));
+	in List.concat(map (fn (con,args) => mapn (sdef con) 1 args) cons) end;
 
 
 (* ----- axiom and definitions concerning induction ------------------------- *)
@@ -100,7 +100,7 @@
     let
       fun one_con (con,args) = let
 	val nonrec_args = filter_out is_rec args;
-	val    rec_args = filter     is_rec args;
+	val    rec_args = List.filter     is_rec args;
 	val    recs_cnt = length rec_args;
 	val allargs     = nonrec_args @ rec_args
 				      @ map (upd_vname (fn s=> s^"'")) rec_args;
@@ -114,10 +114,10 @@
 					 (allargs~~((allargs_cnt-1) downto 0)));
 	fun rel_app i ra = proj (Bound(allargs_cnt+2)) eqs (rec_of ra) $ 
 			   Bound (2*recs_cnt-i) $ Bound (recs_cnt-i);
-	val capps = foldr mk_conj (mapn rel_app 1 rec_args, mk_conj(
+	val capps = Library.foldr mk_conj (mapn rel_app 1 rec_args, mk_conj(
 	   Bound(allargs_cnt+1)===mk_cRep_CFun(%%:con,map (bound_arg allvns) vns1),
 	   Bound(allargs_cnt+0)===mk_cRep_CFun(%%:con,map (bound_arg allvns) vns2)));
-        in foldr mk_ex (allvns, foldr mk_conj 
+        in Library.foldr mk_ex (allvns, Library.foldr mk_conj 
 			      (map (defined o Bound) nonlazy_idxs,capps)) end;
       fun one_comp n (_,cons) =mk_all(x_name(n+1),mk_all(x_name(n+1)^"'",mk_imp(
 	 		proj (Bound 2) eqs n $ Bound 1 $ Bound 0,
@@ -129,7 +129,7 @@
 	|> add_axioms_i (infer_types thy' dfs)(*add_defs_i*)
 	|> add_axioms_i (infer_types thy' axs)
 	|> Theory.parent_path;
-  val thy = foldl add_one (thy', mapn (calc_axioms comp_dname eqs) 0 eqs);
+  val thy = Library.foldl add_one (thy', mapn (calc_axioms comp_dname eqs) 0 eqs);
 in thy |> Theory.add_path comp_dnam  
        |> add_axioms_i (infer_types thy' 
 		(bisim_def::(if length eqs>1 then [copy_def] else [])))
--- a/src/HOLCF/domain/extender.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/HOLCF/domain/extender.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -44,11 +44,11 @@
     val defaultS = Sign.defaultS sg;
     val test_dupl_typs = (case duplicates (map fst dtnvs) of 
 	[] => false | dups => error ("Duplicate types: " ^ commas_quote dups));
-    val test_dupl_cons = (case duplicates (map first (flat cons'')) of 
+    val test_dupl_cons = (case duplicates (map first (List.concat cons'')) of 
 	[] => false | dups => error ("Duplicate constructors: " 
 							 ^ commas_quote dups));
     val test_dupl_sels = (case duplicates 
-			       (map second (flat (map third (flat cons'')))) of
+			       (map second (List.concat (map third (List.concat cons'')))) of
         [] => false | dups => error("Duplicate selectors: "^commas_quote dups));
     val test_dupl_tvars = exists(fn s=>case duplicates(map(fst o rep_TFree)s)of
 	[] => false | dups => error("Duplicate type arguments: " 
@@ -110,7 +110,7 @@
     val eqs' = check_and_sort_domain (dtnvs,cons'') sg'';
     val thy' = thy'' |> Domain_Syntax.add_syntax (comp_dnam,eqs');
     val dts  = map (Type o fst) eqs';
-    fun strip ss = drop (find_index_eq "'" ss +1, ss);
+    fun strip ss = Library.drop (find_index_eq "'" ss +1, ss);
     fun typid (Type  (id,_)) =
           let val c = hd (Symbol.explode (Sign.base_name id))
           in if Symbol.is_letter c then c else "t" end
@@ -131,7 +131,7 @@
 in
   theorems_thy
   |> Theory.add_path (Sign.base_name comp_dnam)
-  |> (#1 o (PureThy.add_thmss [(("rews", flat rewss @ take_rews), [])]))
+  |> (#1 o (PureThy.add_thmss [(("rews", List.concat rewss @ take_rews), [])]))
   |> Theory.parent_path
 end;
 
--- a/src/HOLCF/domain/interface.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/HOLCF/domain/interface.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -33,7 +33,7 @@
       cat_lines (map (gen_vals dname) axioms1)^"\n"^
       gen_vall "con_defs"       (map (fn (con,_,_) => 
 		get dname (strip_esc con^"_def")) cons')^"\n"^
-      gen_vall "sel_defs" (flat (map (fn (_,_,args) => map (fn (_,sel,_) => 
+      gen_vall "sel_defs" (List.concat (map (fn (_,_,args) => map (fn (_,sel,_) => 
 		get dname (sel^"_def")) args)    cons'))^"\n"^
       gen_vall "dis_defs"       (map (fn (con,_,_) => 
 		get dname (dis_name_ con^"_def")) cons')^"\n"^
--- a/src/HOLCF/domain/library.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/HOLCF/domain/library.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -13,12 +13,12 @@
 fun mapn f n []      = []
 |   mapn f n (x::xs) = (f n x) :: mapn f (n+1) xs;
 
-fun foldr'' f (l,f2) = let fun itr []  = raise LIST "foldr''"
+fun foldr'' f (l,f2) = let fun itr []  = raise Fail "foldr''"
 			     | itr [a] = f2 a
 			     | itr (a::l) = f(a, itr l)
 in  itr l  end;
 fun foldr' f l = foldr'' f (l,Id);
-fun map_cumulr f start xs = foldr (fn (x,(ys,res))=>case f(x,res) of (y,res2) =>
+fun map_cumulr f start xs = Library.foldr (fn (x,(ys,res))=>case f(x,res) of (y,res2) =>
 						  (y::ys,res2)) (xs,([],start));
 
 
@@ -98,7 +98,7 @@
 fun is_rec         arg = rec_of arg >=0;
 fun is_nonlazy_rec arg = is_rec arg andalso not (is_lazy arg);
 fun nonlazy     args   = map vname (filter_out is_lazy    args);
-fun nonlazy_rec args   = map vname (filter is_nonlazy_rec args);
+fun nonlazy_rec args   = map vname (List.filter is_nonlazy_rec args);
 
 (* ----- support for type and mixfix expressions ----- *)
 
@@ -123,7 +123,7 @@
 	 	    |   sg _       = Imposs "library:sg";
 		    fun sf [] = %%:"_emptysort"
 		    |   sf s  = %%:"_sort" $ sg s
-		    fun tf (Type (s,args)) = foldl (op $) (%:s,map tf args)
+		    fun tf (Type (s,args)) = Library.foldl (op $) (%:s,map tf args)
 		    |   tf (TFree(s,sort)) = %%:"_ofsort" $ %:s $ sf sort
 		    |   tf _               = Imposs "library:tf";
 in
@@ -146,7 +146,7 @@
 infix 9 `  ; fun f`  x = %%:"Rep_CFun" $ f $ x;
 infix 9 `% ; fun f`% s = f` %: s;
 infix 9 `%%; fun f`%%s = f` %%:s;
-fun mk_cRep_CFun (F,As) = foldl (op `) (F,As);
+fun mk_cRep_CFun (F,As) = Library.foldl (op `) (F,As);
 fun con_app2 con f args = mk_cRep_CFun(%%:con,map f args);
 fun con_app con = con_app2 con %#;
 fun if_rec  arg f y   = if is_rec arg then f (rec_of arg) else y;
@@ -162,7 +162,7 @@
 	(fn S => fn t => Const("cfst",mk_prodT(dummyT,t)->>dummyT)`S) 
 	(fn S => fn t => Const("csnd",mk_prodT(t,dummyT)->>dummyT)`S) 
 		       T (map ((fn tp => tp ->> tp) o Type o fix_tp o fst) eqs);
-fun lift tfn = foldr (fn (x,t)=> (mk_trp(tfn x) ===> t));
+fun lift tfn = Library.foldr (fn (x,t)=> (mk_trp(tfn x) ===> t));
 
 fun /\ v T = %%:"Abs_CFun" $ mk_lam(v,T);
 fun /\# (arg,T) = /\ (vname arg) T;
--- a/src/HOLCF/domain/syntax.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/HOLCF/domain/syntax.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -22,14 +22,14 @@
 			    else foldr' mk_sprodT (map opt_lazy args);
   fun freetvar s = let val tvar = mk_TFree s in
 		   if tvar mem typevars then freetvar ("t"^s) else tvar end;
-  fun when_type (_   ,_,args) = foldr (op ->>) (map third args,freetvar "t");
+  fun when_type (_   ,_,args) = Library.foldr (op ->>) (map third args,freetvar "t");
 in
   val dtype  = Type(dname,typevars);
   val dtype2 = foldr' mk_ssumT (map prod cons');
   val dnam = Sign.base_name dname;
   val const_rep  = (dnam^"_rep" ,              dtype  ->> dtype2, NoSyn);
   val const_abs  = (dnam^"_abs" ,              dtype2 ->> dtype , NoSyn);
-  val const_when = (dnam^"_when",foldr (op ->>) ((map when_type cons'),
+  val const_when = (dnam^"_when",Library.foldr (op ->>) ((map when_type cons'),
 					        dtype ->> freetvar "t"), NoSyn);
   val const_copy = (dnam^"_copy", dtypeprod ->> dtype  ->> dtype , NoSyn);
 end;
@@ -42,7 +42,7 @@
 							 else      c::esc cs
 	|   esc []      = []
 	in implode o esc o Symbol.explode end;
-  fun con (name,s,args) = (name,foldr (op ->>) (map third args,dtype),s);
+  fun con (name,s,args) = (name,Library.foldr (op ->>) (map third args,dtype),s);
   fun dis (con ,s,_   ) = (dis_name_ con, dtype->>trT,
 			   Mixfix(escape ("is_" ^ con), [], Syntax.max_pri));
 			(* stricly speaking, these constants have one argument,
@@ -52,7 +52,7 @@
 in
   val consts_con = map con cons';
   val consts_dis = map dis cons';
-  val consts_sel = flat(map sel cons');
+  val consts_sel = List.concat(map sel cons');
 end;
 
 (* ----- constants concerning induction ------------------------------------- *)
@@ -70,7 +70,7 @@
 					 (string_of_int m));
 	fun app s (l,r)   = mk_appl (Constant s) [l,r];
 	fun case1 n (con,mx,args) = mk_appl (Constant "_case1")
-		 [foldl (app "Rep_CFun") (c_ast con mx, (mapn (argvar n) 1 args)),
+		 [Library.foldl (app "Rep_CFun") (c_ast con mx, (mapn (argvar n) 1 args)),
 		  expvar n];
 	fun arg1 n (con,_,args) = if args = [] then expvar n 
 				  else mk_appl (Constant "LAM ") 
@@ -80,7 +80,7 @@
       (mk_appl (Constant "_case_syntax") [Variable "x", foldr'
 				(fn (c,cs) => mk_appl (Constant"_case2") [c,cs])
 				 (mapn case1 1 cons')],
-       mk_appl (Constant "Rep_CFun") [foldl 
+       mk_appl (Constant "Rep_CFun") [Library.foldl 
 				(fn (w,a ) => mk_appl (Constant"Rep_CFun" ) [w,a ])
 				 (Constant (dnam^"_when"),mapn arg1 1 cons'),
 				 Variable "x"])
@@ -107,10 +107,10 @@
   val const_copy   = (comp_dnam^"_copy"  ,funprod ->> funprod, NoSyn);
   val const_bisim  = (comp_dnam^"_bisim" ,relprod --> boolT  , NoSyn);
   val ctt           = map (calc_syntax funprod) eqs';
-in thy'' |> ContConsts.add_consts_i (flat (map fst ctt) @ 
+in thy'' |> ContConsts.add_consts_i (List.concat (map fst ctt) @ 
 				    (if length eqs'>1 then [const_copy] else[])@
 				    [const_bisim])
-	 |> Theory.add_trrules_i (flat(map snd ctt))
+	 |> Theory.add_trrules_i (List.concat(map snd ctt))
 end; (* let *)
 
 end; (* local *)
--- a/src/HOLCF/domain/theorems.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/HOLCF/domain/theorems.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -71,7 +71,7 @@
 val ax_when_def   = ga "when_def" dname;
 val axs_con_def   = map (fn (con,_) => ga (extern_name con^"_def") dname) cons;
 val axs_dis_def   = map (fn (con,_) => ga (   dis_name con^"_def") dname) cons;
-val axs_sel_def   = flat(map (fn (_,args) => 
+val axs_sel_def   = List.concat(map (fn (_,args) => 
                     map (fn     arg => ga (sel_of arg     ^"_def") dname) args)
 									  cons);
 val ax_copy_def   = ga "copy_def" dname;
@@ -101,7 +101,7 @@
                             etac (ax_rep_iso RS subst) 1];
 fun exh foldr1 cn quant foldr2 var = let
   fun one_con (con,args) = let val vns = map vname args in
-    foldr quant (vns, foldr2 ((%:x_name === con_app2 con (var vns) vns)::
+    Library.foldr quant (vns, foldr2 ((%:x_name === con_app2 con (var vns) vns)::
                               map (defined o (var vns)) (nonlazy args))) end
   in foldr1 ((cn(%:x_name===UU))::map one_con cons) end;
 in
@@ -130,9 +130,9 @@
                                 prod_tac args THEN sum_rest_tac p) THEN
                                 sum_tac cons' prems
             |   sum_tac _ _ = Imposs "theorems:sum_tac";
-          in pg'' thy [] (exh (fn l => foldr (op ===>) (l,mk_trp(%:"P")))
+          in pg'' thy [] (exh (fn l => Library.foldr (op ===>) (l,mk_trp(%:"P")))
                               (fn T => T ==> %:"P") mk_All
-                              (fn l => foldr (op ===>) (map mk_trp l,
+                              (fn l => Library.foldr (op ===>) (map mk_trp l,
                                                             mk_trp(%:"P")))
                               bound_arg)
                              (fn prems => [
@@ -153,9 +153,9 @@
 end;
 
 local 
-  fun bind_fun t = foldr mk_All (when_funs cons,t);
+  fun bind_fun t = Library.foldr mk_All (when_funs cons,t);
   fun bound_fun i _ = Bound (length cons - i);
-  val when_app  = foldl (op `) (%%:(dname^"_when"), mapn bound_fun 1 cons);
+  val when_app  = Library.foldl (op `) (%%:(dname^"_when"), mapn bound_fun 1 cons);
   val when_appl = pg [ax_when_def] (bind_fun(mk_trp(when_app`%x_name ===
              when_body cons (fn (m,n)=> bound_fun (n-m) 0)`(dc_rep`%x_name))))[
                                 simp_tac HOLCF_ss 1];
@@ -182,7 +182,7 @@
                         (mk_trp((%%:(dis_name c))`(con_app con args) ===
                               %%:(if con=c then "TT" else "FF"))))) [
                                 asm_simp_tac (HOLCF_ss addsimps when_rews) 1];
-        in flat(map (fn (c,_) => map (one_dis c) cons) cons) end;
+        in List.concat(map (fn (c,_) => map (one_dis c) cons) cons) end;
   val dis_defins = map (fn (con,args) => pg [] (defined(%:x_name) ==> 
                       defined(%%:(dis_name con)`%x_name)) [
                                 rtac casedist 1,
@@ -191,7 +191,7 @@
                                         (HOLCF_ss addsimps dis_apps) 1))]) cons;
 in dis_stricts @ dis_defins @ dis_apps end;
 
-val con_stricts = flat(map (fn (con,args) => map (fn vn =>
+val con_stricts = List.concat(map (fn (con,args) => map (fn vn =>
                         pg (axs_con_def) 
                            (mk_trp(con_app2 con (fn arg => if vname arg = vn 
                                         then UU else %# arg) args === UU))[
@@ -207,22 +207,22 @@
 
 val sel_stricts = let fun one_sel sel = pg axs_sel_def (mk_trp(strict(%%:sel))) [
                                 simp_tac (HOLCF_ss addsimps when_rews) 1];
-in flat(map (fn (_,args) =>map (fn arg => one_sel (sel_of arg)) args) cons) end;
+in List.concat(map (fn (_,args) =>map (fn arg => one_sel (sel_of arg)) args) cons) end;
 val sel_apps = let fun one_sel c n sel = map (fn (con,args) => 
                 let val nlas = nonlazy args;
                     val vns  = map vname args;
                 in pg axs_sel_def (lift_defined %:
-                   (filter (fn v => con=c andalso (v<>nth_elem(n,vns))) nlas,
+                   (List.filter (fn v => con=c andalso (v<>List.nth(vns,n))) nlas,
                                 mk_trp((%%:sel)`(con_app con args) === 
-                                (if con=c then %:(nth_elem(n,vns)) else UU))))
+                                (if con=c then %:(List.nth(vns,n)) else UU))))
                             ( (if con=c then [] 
                        else map(case_UU_tac(when_rews@con_stricts)1) nlas)
-                     @(if con=c andalso ((nth_elem(n,vns)) mem nlas)
+                     @(if con=c andalso ((List.nth(vns,n)) mem nlas)
                                  then[case_UU_tac (when_rews @ con_stricts) 1 
-                                                  (nth_elem(n,vns))] else [])
+                                                  (List.nth(vns,n))] else [])
                      @ [asm_simp_tac(HOLCF_ss addsimps when_rews)1])end) cons;
-in flat(map  (fn (c,args) => 
-     flat(mapn (fn n => fn arg => one_sel c n (sel_of arg)) 0 args)) cons) end;
+in List.concat(map  (fn (c,args) => 
+     List.concat(mapn (fn n => fn arg => one_sel c n (sel_of arg)) 0 args)) cons) end;
 val sel_defins = if length cons=1 then map (fn arg => pg [](defined(%:x_name)==> 
                         defined(%%:(sel_of arg)`%x_name)) [
                                 rtac casedist 1,
@@ -249,7 +249,7 @@
     fun distincts []      = []
     |   distincts (c::cs) = (map (distinct c) cs) :: distincts cs;
 in distincts cons end;
-val dist_les = flat (flat distincts_le);
+val dist_les = List.concat (List.concat distincts_le);
 val dist_eqs = let
     fun distinct (_,args1) ((_,args2),leqs) = let
         val (le1,le2) = (hd leqs, hd(tl leqs));
@@ -273,10 +273,10 @@
                             mk_trp (foldr' mk_conj 
                                 (ListPair.map rel
 				 (map %# largs, map %# rargs)))))) end;
-  val cons' = filter (fn (_,args) => args<>[]) cons;
+  val cons' = List.filter (fn (_,args) => args<>[]) cons;
 in
 val inverts = map (fn (con,args) => 
-                pgterm (op <<) con args (flat(map (fn arg => [
+                pgterm (op <<) con args (List.concat(map (fn arg => [
                                 TRY(rtac conjI 1),
                                 dres_inst_tac [("fo",sel_of arg)] monofun_cfun_arg 1,
                                 asm_full_simp_tac (HOLCF_ss addsimps sel_apps) 1]
@@ -302,7 +302,7 @@
                 (con_app2 con (app_rec_arg (cproj (%:"f") eqs)) args))))
                         (map (case_UU_tac (abs_strict::when_strict::con_stricts)
                                  1 o vname)
-                         (filter (fn a => not (is_rec a orelse is_lazy a)) args)
+                         (List.filter (fn a => not (is_rec a orelse is_lazy a)) args)
                         @[asm_simp_tac (HOLCF_ss addsimps when_apps) 1,
                           simp_tac (HOLCF_ss addsimps axs_con_def) 1]))cons;
 val copy_stricts = map (fn (con,args) => pg [] (mk_trp(dc_copy`UU`
@@ -310,7 +310,7 @@
      (let val rews = cfst_strict::csnd_strict::copy_strict::copy_apps@con_rews
                          in map (case_UU_tac rews 1) (nonlazy args) @ [
                              asm_simp_tac (HOLCF_ss addsimps rews) 1] end))
-                        (filter (fn (_,args)=>exists is_nonlazy_rec args) cons);
+                        (List.filter (fn (_,args)=>exists is_nonlazy_rec args) cons);
 val copy_rews = copy_strict::copy_apps @ copy_stricts;
 in thy |> Theory.add_path (Sign.base_name dname)
        |> (#1 o (PureThy.add_thmss (map Thm.no_attributes [
@@ -352,8 +352,8 @@
 local fun gt  s dn = get_thm  thy (dn ^ "." ^ s, NONE);
       fun gts s dn = get_thms thy (dn ^ "." ^ s, NONE) in
 val cases     =       map (gt  "casedist" ) dnames;
-val con_rews  = flat (map (gts "con_rews" ) dnames);
-val copy_rews = flat (map (gts "copy_rews") dnames);
+val con_rews  = List.concat (map (gts "con_rews" ) dnames);
+val copy_rews = List.concat (map (gts "copy_rews") dnames);
 end; (* local *)
 
 fun dc_take dn = %%:(dn^"_take");
@@ -379,17 +379,17 @@
                                 simp_tac iterate_Cprod_ss 1]) 1 dnames;
   val c_UU_tac = case_UU_tac (take_stricts'::copy_con_rews) 1;
   val take_apps = pg copy_take_defs (mk_trp(foldr' mk_conj 
-            (flat(map (fn ((dn,_),cons) => map (fn (con,args) => foldr mk_all 
+            (List.concat(map (fn ((dn,_),cons) => map (fn (con,args) => Library.foldr mk_all 
         (map vname args,(dc_take dn $ (%%:"Suc" $ %:"n"))`(con_app con args) ===
-         con_app2 con (app_rec_arg (fn n=>dc_take (nth_elem(n,dnames))$ %:"n"))
+         con_app2 con (app_rec_arg (fn n=>dc_take (List.nth(dnames,n))$ %:"n"))
                               args)) cons) eqs)))) ([
                                 simp_tac iterate_Cprod_ss 1,
                                 induct_tac "n" 1,
                             simp_tac(iterate_Cprod_ss addsimps copy_con_rews) 1,
                                 asm_full_simp_tac (HOLCF_ss addsimps 
-                                      (filter (has_fewer_prems 1) copy_rews)) 1,
+                                      (List.filter (has_fewer_prems 1) copy_rews)) 1,
                                 TRY(safe_tac HOL_cs)] @
-                        (flat(map (fn ((dn,_),cons) => map (fn (con,args) => 
+                        (List.concat(map (fn ((dn,_),cons) => map (fn (con,args) => 
                                 if nonlazy_rec args = [] then all_tac else
                                 EVERY(map c_UU_tac (nonlazy_rec args)) THEN
                                 asm_full_simp_tac (HOLCF_ss addsimps copy_rews)1
@@ -399,23 +399,23 @@
 end; (* local *)
 
 local
-  fun one_con p (con,args) = foldr mk_All (map vname args,
+  fun one_con p (con,args) = Library.foldr mk_All (map vname args,
         lift_defined (bound_arg (map vname args)) (nonlazy args,
         lift (fn arg => %:(P_name (1+rec_of arg)) $ bound_arg args arg)
-         (filter is_rec args,mk_trp(%:p $ con_app2 con (bound_arg args) args))));
+         (List.filter is_rec args,mk_trp(%:p $ con_app2 con (bound_arg args) args))));
   fun one_eq ((p,cons),concl) = (mk_trp(%:p $ UU) ===> 
-                           foldr (op ===>) (map (one_con p) cons,concl));
-  fun ind_term concf = foldr one_eq (mapn (fn n => fn x => (P_name n, x))1conss,
+                           Library.foldr (op ===>) (map (one_con p) cons,concl));
+  fun ind_term concf = Library.foldr one_eq (mapn (fn n => fn x => (P_name n, x))1conss,
                         mk_trp(foldr' mk_conj (mapn concf 1 dnames)));
   val take_ss = HOL_ss addsimps take_rews;
   fun quant_tac i = EVERY(mapn(fn n=> fn _=> res_inst_tac[("x",x_name n)]spec i)
                                1 dnames);
-  fun ind_prems_tac prems = EVERY(flat (map (fn cons => (
+  fun ind_prems_tac prems = EVERY(List.concat (map (fn cons => (
                                      resolve_tac prems 1 ::
-                                     flat (map (fn (_,args) => 
+                                     List.concat (map (fn (_,args) => 
                                        resolve_tac prems 1 ::
                                        map (K(atac 1)) (nonlazy args) @
-                                       map (K(atac 1)) (filter is_rec args))
+                                       map (K(atac 1)) (List.filter is_rec args))
                                      cons))) conss));
   local 
     (* check whether every/exists constructor of the n-th part of the equation:
@@ -425,11 +425,11 @@
           is_rec arg andalso not(rec_of arg mem ns) andalso
           ((rec_of arg =  n andalso nfn(lazy_rec orelse is_lazy arg)) orelse 
             rec_of arg <> n andalso rec_to quant nfn rfn (rec_of arg::ns) 
-              (lazy_rec orelse is_lazy arg) (n, (nth_elem(rec_of arg,conss))))
+              (lazy_rec orelse is_lazy arg) (n, (List.nth(conss,rec_of arg))))
           ) o snd) cons;
     fun all_rec_to ns  = rec_to forall not all_rec_to  ns;
     fun warn (n,cons)  = if all_rec_to [] false (n,cons) then (warning
-        ("domain "^nth_elem(n,dnames)^" is empty!"); true) else false;
+        ("domain "^List.nth(dnames,n)^" is empty!"); true) else false;
     fun lazy_rec_to ns = rec_to exists Id  lazy_rec_to ns;
 
   in val n__eqs     = mapn (fn n => fn (_,cons) => (n,cons)) 0 eqs;
@@ -444,18 +444,18 @@
                                 induct_tac "n" 1,
                                 simp_tac (take_ss addsimps prems) 1,
                                 TRY(safe_tac HOL_cs)]
-                                @ flat(map (fn (cons,cases) => [
+                                @ List.concat(map (fn (cons,cases) => [
                                  res_inst_tac [("x","x")] cases 1,
                                  asm_simp_tac (take_ss addsimps prems) 1]
-                                 @ flat(map (fn (con,args) => 
+                                 @ List.concat(map (fn (con,args) => 
                                   asm_simp_tac take_ss 1 ::
                                   map (fn arg =>
                                    case_UU_tac (prems@con_rews) 1 (
-                           nth_elem(rec_of arg,dnames)^"_take n$"^vname arg))
-                                  (filter is_nonlazy_rec args) @ [
+                           List.nth(dnames,rec_of arg)^"_take n$"^vname arg))
+                                  (List.filter is_nonlazy_rec args) @ [
                                   resolve_tac prems 1] @
                                   map (K (atac 1))      (nonlazy args) @
-                                  map (K (etac spec 1)) (filter is_rec args)) 
+                                  map (K (etac spec 1)) (List.filter is_rec args)) 
                                  cons))
                                 (conss~~cases)));
 
@@ -496,14 +496,14 @@
                                 induct_tac "n" 1,
                                 simp_tac take_ss 1,
                         TRY(safe_tac(empty_cs addSEs[conjE] addSIs[conjI]))] @
-                                flat(mapn (fn n => fn (cons,cases) => [
+                                List.concat(mapn (fn n => fn (cons,cases) => [
                                   simp_tac take_ss 1,
                                   rtac allI 1,
                                   res_inst_tac [("x",x_name n)] cases 1,
                                   asm_simp_tac take_ss 1] @ 
-                                  flat(map (fn (con,args) => 
+                                  List.concat(map (fn (con,args) => 
                                     asm_simp_tac take_ss 1 ::
-                                    flat(map (fn vn => [
+                                    List.concat(map (fn vn => [
                                       eres_inst_tac [("x",vn)] all_dupE 1,
                                       etac disjE 1,
                                       asm_simp_tac (HOL_ss addsimps con_rews) 1,
@@ -523,7 +523,7 @@
   (finites,
    pg'' thy[](ind_term (fn n => fn dn => %:(P_name n) $ %:(x_name n)))(fn prems =>
                                 TRY(safe_tac HOL_cs) ::
-                         flat (map (fn (finite,fin_ind) => [
+                         List.concat (map (fn (finite,fin_ind) => [
                                rtac(rewrite_rule axs_finite_def finite RS exE)1,
                                 etac subst 1,
                                 rtac fin_ind 1,
@@ -532,7 +532,7 @@
 ) end (* let *) else
   (mapn (fn n => fn dn => read_instantiate_sg (sign_of thy) 
                     [("P",dn^"_finite "^x_name n)] excluded_middle) 1 dnames,
-   pg'' thy [] (foldr (op ===>) (mapn (fn n => K(mk_trp(%%:"adm" $ %:(P_name n))))
+   pg'' thy [] (Library.foldr (op ===>) (mapn (fn n => K(mk_trp(%%:"adm" $ %:(P_name n))))
                1 dnames, ind_term (fn n => fn dn => %:(P_name n) $ %:(x_name n))))
                    (fn prems => map (fn ax_reach => rtac (ax_reach RS subst) 1) 
                                     axs_reach @ [
@@ -556,8 +556,8 @@
   val take_ss = HOL_ss addsimps take_rews;
   val sproj   = prj (fn s => K("fst("^s^")")) (fn s => K("snd("^s^")"));
   val coind_lemma=pg[ax_bisim_def](mk_trp(mk_imp(%%:(comp_dname^"_bisim") $ %:"R",
-                foldr (fn (x,t)=> mk_all(x,mk_all(x^"'",t))) (xs,
-                  foldr mk_imp (mapn (fn n => K(proj (%:"R") eqs n $ 
+                Library.foldr (fn (x,t)=> mk_all(x,mk_all(x^"'",t))) (xs,
+                  Library.foldr mk_imp (mapn (fn n => K(proj (%:"R") eqs n $ 
                                       bnd_arg n 0 $ bnd_arg n 1)) 0 dnames,
                     foldr' mk_conj (mapn (fn n => fn dn => 
                                 (dc_take dn $ %:"n" `bnd_arg n 0 === 
@@ -566,7 +566,7 @@
                                 induct_tac "n" 1,
                                 simp_tac take_ss 1,
                                 safe_tac HOL_cs] @
-                                flat(mapn (fn n => fn x => [
+                                List.concat(mapn (fn n => fn x => [
                                   rotate_tac (n+1) 1,
                                   etac all2E 1,
                                   eres_inst_tac [("P1", sproj "R" eqs n^
@@ -576,11 +576,11 @@
                                 0 xs));
 in
 val coind = pg [] (mk_trp(%%:(comp_dname^"_bisim") $ %:"R") ===>
-                foldr (op ===>) (mapn (fn n => fn x => 
+                Library.foldr (op ===>) (mapn (fn n => fn x => 
                   mk_trp(proj (%:"R") eqs n $ %:x $ %:(x^"'"))) 0 xs,
                   mk_trp(foldr' mk_conj (map (fn x => %:x === %:(x^"'")) xs)))) ([
                                 TRY(safe_tac HOL_cs)] @
-                                flat(map (fn take_lemma => [
+                                List.concat(map (fn take_lemma => [
                                   rtac take_lemma 1,
                                   cut_facts_tac [coind_lemma] 1,
                                   fast_tac HOL_cs 1])
--- a/src/Provers/Arith/abel_cancel.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/Provers/Arith/abel_cancel.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -160,7 +160,7 @@
        val _ = if null common then raise Cancel  (*nothing to do*)
                                    else ()
 
-       fun cancelled tms = mk_sum ty (foldl cancel1 (tms, common))
+       fun cancelled tms = mk_sum ty (Library.foldl cancel1 (tms, common))
 
        val lt' = cancelled ltms
        and rt' = cancelled rtms
--- a/src/Provers/Arith/cancel_numeral_factor.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/Provers/Arith/cancel_numeral_factor.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -75,7 +75,7 @@
 	    Data.prove_conv [Data.norm_tac] sg hyps xs
 	      (t',   Data.mk_bal (newshape(n1,t1'), newshape(n2,t2')))
   in
-      apsome Data.simplify_meta_eq
+      Option.map Data.simplify_meta_eq
        (Data.prove_conv 
 	       [Data.trans_tac reshape, rtac Data.cancel 1,
 		Data.numeral_simp_tac] sg hyps xs (t', rhs))
--- a/src/Provers/Arith/cancel_numerals.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/Provers/Arith/cancel_numerals.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -59,11 +59,11 @@
 (*a left-to-right scan of terms1, seeking a term of the form #n*u, where
   #m*u is in terms2 for some m*)
 fun find_common (terms1,terms2) =
-  let val tab2 = foldl update_by_coeff (Termtab.empty, terms2)
+  let val tab2 = Library.foldl update_by_coeff (Termtab.empty, terms2)
       fun seek [] = raise TERM("find_common", []) 
 	| seek (t::terms) =
 	      let val (_,u) = Data.dest_coeff t 
-	      in  if is_some (Termtab.lookup (tab2, u)) then u
+	      in  if isSome (Termtab.lookup (tab2, u)) then u
 		  else seek terms
 	      end
   in  seek terms1 end;
@@ -91,7 +91,7 @@
 			 Data.mk_bal (newshape(n1,terms1'), 
 				      newshape(n2,terms2')))
   in
-      apsome Data.simplify_meta_eq
+      Option.map Data.simplify_meta_eq
        (if n2<=n1 then 
 	    Data.prove_conv 
 	       [Data.trans_tac reshape, rtac Data.bal_add1 1,
--- a/src/Provers/Arith/combine_numerals.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/Provers/Arith/combine_numerals.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -78,7 +78,7 @@
 			 Data.mk_sum T ([Data.mk_coeff(m,u),
 				         Data.mk_coeff(n,u)] @ terms))
   in
-      apsome Data.simplify_meta_eq
+      Option.map Data.simplify_meta_eq
 	 (Data.prove_conv 
 	    [Data.trans_tac reshape, rtac Data.left_distrib 1,
 	     Data.numeral_simp_tac] sg xs
--- a/src/Provers/Arith/extract_common_term.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/Provers/Arith/extract_common_term.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -42,10 +42,10 @@
 
 (*a left-to-right scan of terms1, seeking a term u that is also in terms2*)
 fun find_common (terms1,terms2) =
-  let val tab2 = foldl update_by_coeff (Termtab.empty, terms2)
+  let val tab2 = Library.foldl update_by_coeff (Termtab.empty, terms2)
       fun seek [] = raise TERM("find_common", []) 
 	| seek (u::terms) =
-	      if is_some (Termtab.lookup (tab2, u)) then u
+	      if isSome (Termtab.lookup (tab2, u)) then u
 	      else seek terms
   in  seek terms1 end;
 
@@ -68,7 +68,7 @@
 		 Data.mk_bal (Data.mk_sum T (u::terms1'), 
 		              Data.mk_sum T (u::terms2')))
   in
-      apsome Data.simplify_meta_eq reshape
+      Option.map Data.simplify_meta_eq reshape
   end
   handle TERM _ => NONE
        | TYPE _ => NONE;   (*Typically (if thy doesn't include Numeral)
--- a/src/Provers/Arith/fast_lin_arith.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/Provers/Arith/fast_lin_arith.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -171,7 +171,7 @@
 (* PRE: ex[v] must be 0! *)
 fun eval (ex:rat list) v (a:int,le,cs:int list) =
   let val rs = map rat_of_int cs
-      val rsum = foldl ratadd (rat0,map ratmul (rs ~~ ex))
+      val rsum = Library.foldl ratadd (rat0,map ratmul (rs ~~ ex))
   in (ratmul(ratadd(rat_of_int a,ratneg rsum), ratinv(el v rs)), le) end;
 (* If el v rs < 0, le should be negated.
    Instead this swap is taken into account in ratrelmin2.
@@ -217,14 +217,14 @@
                     in if ratle(lb,ub') then ub' else raise NoEx end;
 
 fun findex1 discr (ex,(v,lineqs)) =
-  let val nz = filter (fn (Lineq(_,_,cs,_)) => el v cs <> 0) lineqs;
-      val ineqs = foldl elim_eqns ([],nz)
-      val (ge,le) = partition (fn (_,_,cs) => el v cs > 0) ineqs
+  let val nz = List.filter (fn (Lineq(_,_,cs,_)) => el v cs <> 0) lineqs;
+      val ineqs = Library.foldl elim_eqns ([],nz)
+      val (ge,le) = List.partition (fn (_,_,cs) => el v cs > 0) ineqs
       val lb = ratrelmax(map (eval ex v) ge)
       val ub = ratrelmin(map (eval ex v) le)
-  in nth_update (choose2 (nth_elem(v,discr)) (lb,ub)) (v,ex) end;
+  in nth_update (choose2 (List.nth(discr,v)) (lb,ub)) (v,ex) end;
 
-fun findex discr = foldl (findex1 discr);
+fun findex discr = Library.foldl (findex1 discr);
 
 fun elim1 v x =
   map (fn (a,le,bs) => (ratadd(a,ratneg(ratmul(el v bs,x))), le,
@@ -239,9 +239,9 @@
   in case nz of [] => ex
      | (_,_,cs) :: _ =>
        let val v = find_index (not o equal rat0) cs
-           val d = nth_elem(v,discr)
+           val d = List.nth(discr,v)
            val pos = ratge0(el v cs)
-           val sv = filter (single_var v) nz
+           val sv = List.filter (single_var v) nz
            val minmax =
              if pos then if d then ratroundup o fst o ratrelmax
                          else ratexact true o ratrelmax
@@ -255,7 +255,7 @@
   end;
 
 fun findex0 discr n lineqs =
-  let val ineqs = foldl elim_eqns ([],lineqs)
+  let val ineqs = Library.foldl elim_eqns ([],lineqs)
       val rineqs = map (fn (a,le,cs) => (rat_of_int a, le, map rat_of_int cs))
                        ineqs
   in pick_vars discr (rineqs,replicate n rat0) end;
@@ -321,7 +321,7 @@
   case ty  of Eq => k <> 0 | Le => k > 0 | Lt => k >= 0;
 
 fun calc_blowup l =
-  let val (p,n) = partition (apl(0,op<)) (filter (apl(0,op<>)) l)
+  let val (p,n) = List.partition (apl(0,op<)) (List.filter (apl(0,op<>)) l)
   in (length p) * (length n) end;
 
 (* ------------------------------------------------------------------------- *)
@@ -337,7 +337,7 @@
 (* ------------------------------------------------------------------------- *)
 
 fun allpairs f xs ys =
-  flat(map (fn x => map (fn y => f x y) ys) xs);
+  List.concat(map (fn x => map (fn y => f x y) ys) xs);
 
 fun extract_first p =
   let fun extract xs (y::ys) = if p y then (SOME y,xs@ys)
@@ -358,7 +358,7 @@
 
 fun elim(ineqs,hist) =
   let val dummy = print_ineqs ineqs;
-      val (triv,nontriv) = partition is_trivial ineqs in
+      val (triv,nontriv) = List.partition is_trivial ineqs in
   if not(null triv)
   then case Library.find_first is_answer triv of
          NONE => elim(nontriv,hist)
@@ -366,16 +366,16 @@
   else
   if null nontriv then Failure(hist)
   else
-  let val (eqs,noneqs) = partition (fn (Lineq(_,ty,_,_)) => ty=Eq) nontriv in
+  let val (eqs,noneqs) = List.partition (fn (Lineq(_,ty,_,_)) => ty=Eq) nontriv in
   if not(null eqs) then
-     let val clist = foldl (fn (cs,Lineq(_,_,l,_)) => l union cs) ([],eqs)
+     let val clist = Library.foldl (fn (cs,Lineq(_,_,l,_)) => l union cs) ([],eqs)
          val sclist = sort (fn (x,y) => int_ord(abs(x),abs(y)))
-                           (filter (fn i => i<>0) clist)
+                           (List.filter (fn i => i<>0) clist)
          val c = hd sclist
          val (SOME(eq as Lineq(_,_,ceq,_)),othereqs) =
                extract_first (fn Lineq(_,_,l,_) => c mem l) eqs
          val v = find_index_eq c ceq
-         val (ioth,roth) = partition (fn (Lineq(_,_,l,_)) => el v l = 0)
+         val (ioth,roth) = List.partition (fn (Lineq(_,_,l,_)) => el v l = 0)
                                      (othereqs @ noneqs)
          val others = map (elim_var v eq) roth @ ioth
      in elim(others,(v,nontriv)::hist) end
@@ -385,12 +385,12 @@
       val coeffs = map (fn i => map (el i) lists) numlist
       val blows = map calc_blowup coeffs
       val iblows = blows ~~ numlist
-      val nziblows = filter (fn (i,_) => i<>0) iblows
+      val nziblows = List.filter (fn (i,_) => i<>0) iblows
   in if null nziblows then Failure((~1,nontriv)::hist)
      else
      let val (c,v) = hd(sort (fn (x,y) => int_ord(fst(x),fst(y))) nziblows)
-         val (no,yes) = partition (fn (Lineq(_,_,l,_)) => el v l = 0) ineqs
-         val (pos,neg) = partition(fn (Lineq(_,_,l,_)) => el v l > 0) yes
+         val (no,yes) = List.partition (fn (Lineq(_,_,l,_)) => el v l = 0) ineqs
+         val (pos,neg) = List.partition(fn (Lineq(_,_,l,_)) => el v l > 0) yes
      in elim(no @ allpairs (elim_var v) pos neg, (v,nontriv)::hist) end
   end
   end
@@ -420,9 +420,9 @@
 in
 fun mkthm sg asms just =
   let val {add_mono_thms, mult_mono_thms, inj_thms, lessD, simpset} = Data.get_sg sg;
-      val atoms = foldl (fn (ats,(lhs,_,_,rhs,_,_)) =>
+      val atoms = Library.foldl (fn (ats,(lhs,_,_,rhs,_,_)) =>
                             map fst lhs  union  (map fst rhs  union  ats))
-                        ([], mapfilter (fn thm => if Thm.no_prems thm
+                        ([], List.mapPartial (fn thm => if Thm.no_prems thm
                                         then LA_Data.decomp sg (concl_of thm)
                                         else NONE) asms)
 
@@ -438,7 +438,7 @@
       fun addthms thm1 thm2 =
         case add2 thm1 thm2 of
           NONE => (case try_add ([thm1] RL inj_thms) thm2 of
-                     NONE => ( the(try_add ([thm2] RL inj_thms) thm1)
+                     NONE => ( valOf(try_add ([thm2] RL inj_thms) thm1)
                                handle OPTION =>
                                (trace_thm "" thm1; trace_thm "" thm2;
                                 sys_error "Lin.arith. failed to add thms")
@@ -468,8 +468,8 @@
         let val thm' = trace_thm "Simplified:" (full_simplify simpset thm)
         in if LA_Logic.is_False thm' then raise FalseE thm' else thm' end
 
-      fun mk(Asm i) = trace_thm "Asm" (nth_elem(i,asms))
-        | mk(Nat i) = (trace_msg "Nat"; LA_Logic.mk_nat_thm sg (nth_elem(i,atoms)))
+      fun mk(Asm i) = trace_thm "Asm" (List.nth(asms,i))
+        | mk(Nat i) = (trace_msg "Nat"; LA_Logic.mk_nat_thm sg (List.nth(atoms,i)))
         | mk(LessD(j)) = trace_thm "L" (hd([mk j] RL lessD))
         | mk(NotLeD(j)) = trace_thm "NLe" (mk j RS LA_Logic.not_leD)
         | mk(NotLeDD(j)) = trace_thm "NLeD" (hd([mk j RS LA_Logic.not_leD] RL lessD))
@@ -484,7 +484,7 @@
         in trace_thm "After simplification:" fls;
            if LA_Logic.is_False fls then fls
            else
-            (tracing "Assumptions:"; seq print_thm asms;
+            (tracing "Assumptions:"; List.app print_thm asms;
              tracing "Proved:"; print_thm fls;
              warning "Linear arithmetic should have refuted the assumptions.\n\
                      \Please inform Tobias Nipkow (nipkow@in.tum.de).";
@@ -496,7 +496,7 @@
 
 fun coeff poly atom = case assoc(poly,atom) of NONE => 0 | SOME i => i;
 
-fun lcms is = foldl lcm (1,is);
+fun lcms is = Library.foldl lcm (1,is);
 
 fun integ(rlhs,r,rel,rrhs,s,d) =
 let val (rn,rd) = rep_rat r and (sn,sd) = rep_rat s
@@ -593,17 +593,17 @@
 fun add_datoms(dats,((lhs,_,_,rhs,_,d),_)) =
     (map (pair d o fst) lhs) union ((map (pair d o fst) rhs) union dats)
 
-fun discr initems = map fst (foldl add_datoms ([],initems));
+fun discr initems = map fst (Library.foldl add_datoms ([],initems));
 
 fun refutes sg (pTs,params) ex =
 let
   fun refute (initems::initemss) js =
-    let val atoms = foldl add_atoms ([],initems)
+    let val atoms = Library.foldl add_atoms ([],initems)
         val n = length atoms
         val mkleq = mklineq n atoms
         val ixs = 0 upto (n-1)
         val iatoms = atoms ~~ ixs
-        val natlineqs = mapfilter (mknat pTs ixs) iatoms
+        val natlineqs = List.mapPartial (mknat pTs ixs) iatoms
         val ineqs = map mkleq initems @ natlineqs
     in case elim(ineqs,[]) of
          Success(j) =>
@@ -628,7 +628,7 @@
     end
     state;
 
-fun count P xs = length(filter P xs);
+fun count P xs = length(List.filter P xs);
 
 (* The limit on the number of ~= allowed.
    Because each ~= is split into two cases, this can lead to an explosion.
--- a/src/Provers/blast.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/Provers/blast.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -134,7 +134,7 @@
 fun rand (f$x) = x;
 
 (* maps   (f, [t1,...,tn])  to  f(t1,...,tn) *)
-val list_comb : term * term list -> term = foldl (op $);
+val list_comb : term * term list -> term = Library.foldl (op $);
 
 
 (* maps   f(t1,...,tn)  to  (f, [t1,...,tn]) ; naturally tail-recursive*)
@@ -412,7 +412,7 @@
 	| inst (Abs(a,t))    = inst t
 	| inst (f $ u)       = (inst f; inst u)
 	| inst _             = ()
-      fun revert() = seq (fn v => v:=NONE) (!updated)
+      fun revert() = List.app (fn v => v:=NONE) (!updated)
   in  inst t; revert  end;
 
 
@@ -635,7 +635,7 @@
 	| printPairs _                 = ()
       fun printBrs (brs0 as {pairs, lits, lim, ...} :: brs) =
 	    (fullTrace := brs0 :: !fullTrace;
-	     seq (fn _ => immediate_output "+") brs;
+	     List.app (fn _ => immediate_output "+") brs;
 	     immediate_output (" [" ^ Int.toString lim ^ "] ");
 	     printPairs pairs;
 	     writeln"")
@@ -652,7 +652,7 @@
 	  | 1 => immediate_output"\t1 variable UPDATED:"
 	  | n => immediate_output("\t" ^ Int.toString n ^ " variables UPDATED:");
        (*display the instantiations themselves, though no variable names*)
-       seq (fn v => immediate_output("   " ^ string_of sign 4 (the (!v))))
+       List.app (fn v => immediate_output("   " ^ string_of sign 4 (valOf (!v))))
            (List.take(!trail, !ntrail-ntrl));
        writeln"")
     else ();
@@ -751,8 +751,8 @@
             end
       (*substitute throughout "stack frame"; extract affected formulae*)
       fun subFrame ((Gs,Hs), (changed, frames)) =
-	    let val (changed', Gs') = foldr subForm (Gs, (changed, []))
-                val (changed'', Hs') = foldr subForm (Hs, (changed', []))
+	    let val (changed', Gs') = Library.foldr subForm (Gs, (changed, []))
+                val (changed'', Hs') = Library.foldr subForm (Hs, (changed', []))
             in  (changed'', (Gs',Hs')::frames)  end
       (*substitute throughout literals; extract affected ones*)
       fun subLit (lit, (changed, nlits)) =
@@ -760,8 +760,8 @@
 	    in  if nlit aconv lit then (changed, nlit::nlits)
 		                  else ((nlit,true)::changed, nlits)
             end
-      val (changed, lits') = foldr subLit (lits, ([], []))
-      val (changed', pairs') = foldr subFrame (pairs, (changed, []))
+      val (changed, lits') = Library.foldr subLit (lits, ([], []))
+      val (changed', pairs') = Library.foldr subFrame (pairs, (changed, []))
   in  if !trace then writeln ("Substituting " ^ traceTerm sign u ^
 			      " for " ^ traceTerm sign t ^ " in branch" )
       else ();
@@ -974,7 +974,7 @@
 				    then lim - (1+log(length rules))
 				    else lim   (*discourage branching updates*)
 			 val vars  = vars_in_vars vars
-			 val vars' = foldr add_terms_vars (prems, vars)
+			 val vars' = Library.foldr add_terms_vars (prems, vars)
 			 val choices' = (ntrl, nbrs, PRV) :: choices
 			 val tacs' = (tac(updated,false,true)) 
                                      :: tacs  (*no duplication; rotate*)
@@ -1101,7 +1101,7 @@
 		    then
 		     let val updated = ntrl < !ntrail (*branch updated*)
 			 val vars  = vars_in_vars vars
-			 val vars' = foldr add_terms_vars (prems, vars)
+			 val vars' = Library.foldr add_terms_vars (prems, vars)
 			    (*duplicate H if md permits*)
 			 val dup = md (*earlier had "andalso vars' <> vars":
                                   duplicate only if the subgoal has new vars*)
--- a/src/Provers/clasimp.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/Provers/clasimp.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -151,30 +151,30 @@
 in
 
 val op addIffs =
-  foldl (addIff (Classical.addSDs, Classical.addSEs, Classical.addSIs)
+  Library.foldl (addIff (Classical.addSDs, Classical.addSEs, Classical.addSIs)
     (Classical.addDs, Classical.addEs, Classical.addIs) Simplifier.addsimps);
-val op delIffs = foldl (delIff Classical.delrules Simplifier.delsimps);
+val op delIffs = Library.foldl (delIff Classical.delrules Simplifier.delsimps);
 
 fun AddIffs thms = store_clasimp (clasimpset () addIffs thms);
 fun DelIffs thms = store_clasimp (clasimpset () delIffs thms);
 
 fun addIffs_global (thy, ths) =
-  foldl (addIff
+  Library.foldl (addIff
     (ContextRules.addXDs_global, ContextRules.addXEs_global, ContextRules.addXIs_global)
     (ContextRules.addXDs_global, ContextRules.addXEs_global, ContextRules.addXIs_global) #1)
   ((thy, ()), ths) |> #1;
 
 fun addIffs_local (ctxt, ths) =
-  foldl (addIff
+  Library.foldl (addIff
     (ContextRules.addXDs_local, ContextRules.addXEs_local, ContextRules.addXIs_local)
     (ContextRules.addXDs_local, ContextRules.addXEs_local, ContextRules.addXIs_local) #1)
   ((ctxt, ()), ths) |> #1;
 
 fun delIffs_global (thy, ths) =
-  foldl (delIff ContextRules.delrules_global #1) ((thy, ()), ths) |> #1;
+  Library.foldl (delIff ContextRules.delrules_global #1) ((thy, ()), ths) |> #1;
 
 fun delIffs_local (ctxt, ths) =
-  foldl (delIff ContextRules.delrules_local #1) ((ctxt, ()), ths) |> #1;
+  Library.foldl (delIff ContextRules.delrules_local #1) ((ctxt, ()), ths) |> #1;
 
 end;
 
--- a/src/Provers/classical.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/Provers/classical.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -214,7 +214,7 @@
     let fun addrl (rl,brls) = (false, rl) :: (true, rl RSN (2,swap)) :: brls
     in  assume_tac      ORELSE'
         contr_tac       ORELSE'
-        biresolve_tac (foldr addrl (rls,[]))
+        biresolve_tac (Library.foldr addrl (rls,[]))
     end;
 
 (*Duplication of hazardous rules, for complete provers*)
@@ -286,7 +286,7 @@
 fun rep_cs (CS args) = args;
 
 local
-  fun wrap l tac = foldr (fn ((name,tacf),w) => tacf w) (l, tac);
+  fun wrap l tac = Library.foldr (fn ((name,tacf),w) => tacf w) (l, tac);
 in
   fun appSWrappers (CS{swrappers,...}) = wrap swrappers;
   fun appWrappers  (CS{uwrappers,...}) = wrap uwrappers;
@@ -316,7 +316,7 @@
 fun tag_brls' _ _ [] = []
   | tag_brls' w k (brl::brls) = ((w, k), brl) :: tag_brls' w (k + 1) brls;
 
-fun insert_tagged_list kbrls netpr = foldr Tactic.insert_tagged_brl (kbrls, netpr);
+fun insert_tagged_list kbrls netpr = Library.foldr Tactic.insert_tagged_brl (kbrls, netpr);
 
 (*Insert into netpair that already has nI intr rules and nE elim rules.
   Count the intr rules double (to account for swapify).  Negate to give the
@@ -324,7 +324,7 @@
 fun insert (nI, nE) = insert_tagged_list o (tag_brls (~(2*nI+nE))) o joinrules;
 fun insert' w (nI, nE) = insert_tagged_list o tag_brls' w (~(nI + nE)) o joinrules';
 
-fun delete_tagged_list brls netpr = foldr Tactic.delete_tagged_brl (brls, netpr);
+fun delete_tagged_list brls netpr = Library.foldr Tactic.delete_tagged_brl (brls, netpr);
 fun delete x = delete_tagged_list (joinrules x);
 fun delete' x = delete_tagged_list (joinrules' x);
 
@@ -355,7 +355,7 @@
           cs)
   else
   let val (safe0_rls, safep_rls) = (*0 subgoals vs 1 or more*)
-          partition Thm.no_prems [th]
+          List.partition Thm.no_prems [th]
       val nI = length safeIs + 1
       and nE = length safeEs
   in warn_dup th cs;
@@ -380,7 +380,7 @@
           cs)
   else
   let val (safe0_rls, safep_rls) = (*0 subgoals vs 1 or more*)
-          partition (fn rl => nprems_of rl=1) [th]
+          List.partition (fn rl => nprems_of rl=1) [th]
       val nI = length safeIs
       and nE = length safeEs + 1
   in warn_dup th cs;
@@ -397,7 +397,7 @@
         xtra_netpair = insert' 0 (nI,nE) ([], [th]) xtra_netpair}
   end;
 
-fun rev_foldl f (e, l) = foldl f (e, rev l);
+fun rev_foldl f (e, l) = Library.foldl f (e, rev l);
 
 val op addSIs = rev_foldl addSI;
 val op addSEs = rev_foldl addSE;
@@ -470,7 +470,7 @@
           (cs as CS{safeIs, safeEs, hazIs, hazEs, swrappers, uwrappers,
                     safe0_netpair, safep_netpair, haz_netpair, dup_netpair, xtra_netpair}) =
  if mem_thm (th, safeIs) then
-   let val (safe0_rls, safep_rls) = partition Thm.no_prems [th]
+   let val (safe0_rls, safep_rls) = List.partition Thm.no_prems [th]
    in CS{safe0_netpair = delete (safe0_rls, []) safe0_netpair,
          safep_netpair = delete (safep_rls, []) safep_netpair,
          safeIs = rem_thm (safeIs,th),
@@ -489,7 +489,7 @@
           (cs as CS{safeIs, safeEs, hazIs, hazEs, swrappers, uwrappers,
                     safe0_netpair, safep_netpair, haz_netpair, dup_netpair, xtra_netpair}) =
  if mem_thm (th, safeEs) then
-   let val (safe0_rls, safep_rls) = partition (fn rl => nprems_of rl=1) [th]
+   let val (safe0_rls, safep_rls) = List.partition (fn rl => nprems_of rl=1) [th]
    in CS{safe0_netpair = delete ([], safe0_rls) safe0_netpair,
          safep_netpair = delete ([], safep_rls) safep_netpair,
          safeIs = safeIs,
@@ -550,7 +550,7 @@
     else (warning ("Undeclared classical rule\n" ^ (string_of_thm th)); cs)
   end;
 
-val op delrules = foldl delrule;
+val op delrules = Library.foldl delrule;
 
 
 (*** Modifying the wrapper tacticals ***)
@@ -661,7 +661,7 @@
 (*version of bimatch_from_nets_tac that only applies rules that
   create precisely n subgoals.*)
 fun n_bimatch_from_nets_tac n =
-    biresolution_from_nets_tac (Tactic.orderlist o filter (nsubgoalsP n)) true;
+    biresolution_from_nets_tac (Tactic.orderlist o List.filter (nsubgoalsP n)) true;
 
 fun eq_contr_tac i = ematch_tac [not_elim] i  THEN  eq_assume_tac i;
 val eq_assume_contr_tac = eq_assume_tac ORELSE' eq_contr_tac;
--- a/src/Provers/ind.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/Provers/ind.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -41,9 +41,9 @@
 (*Generalizes over all free variables, with the named var outermost.*)
 fun all_frees_tac (var:string) i thm = 
     let val tsig = Sign.tsig_of (Thm.sign_of_thm thm);
-        val frees = add_term_frees tsig (nth_elem(i-1,prems_of thm),[var]);
+        val frees = add_term_frees tsig (List.nth(prems_of thm,i-1),[var]);
         val frees' = sort (rev_order o string_ord) (frees \ var) @ [var]
-    in foldl (qnt_tac i) (all_tac,frees') thm end;
+    in Library.foldl (qnt_tac i) (all_tac,frees') thm end;
 
 fun REPEAT_SIMP_TAC simp_tac n i =
 let fun repeat thm = 
--- a/src/Provers/induct_method.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/Provers/induct_method.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -59,7 +59,7 @@
     val xs = InductAttrib.vars_of tm;
   in
     align "Rule has fewer variables than instantiations given" xs ts
-    |> mapfilter prep_var
+    |> List.mapPartial prep_var
   end;
 
 
@@ -96,7 +96,7 @@
     fun inst_rule r =
       if null insts then RuleCases.add r
       else (align_left "Rule has fewer premises than arguments given" (Thm.prems_of r) insts
-        |> (flat o map (prep_inst align_left cert I))
+        |> (List.concat o map (prep_inst align_left cert I))
         |> Drule.cterm_instantiate) r |> rpair (RuleCases.get r);
 
     val ruleq =
@@ -108,8 +108,8 @@
           end
       | SOME r => Seq.single (inst_rule r));
 
-    fun prep_rule (th, (cases, n)) = Seq.map (apsnd (rpair (drop (n, facts))) o rpair cases)
-      (Method.multi_resolves (take (n, facts)) [th]);
+    fun prep_rule (th, (cases, n)) = Seq.map (apsnd (rpair (Library.drop (n, facts))) o rpair cases)
+      (Method.multi_resolves (Library.take (n, facts)) [th]);
   in resolveq_cases_tac (RuleCases.make is_open NONE) (Seq.flat (Seq.map prep_rule ruleq)) end;
 
 in
@@ -161,7 +161,7 @@
   let
     val th = Thm.permute_prems (i - 1) 1 raw_th;
     val cprems = Drule.cprems_of th;
-    val As = take (length cprems - 1, cprems);
+    val As = Library.take (length cprems - 1, cprems);
     val C = Thm.cterm_of (Thm.sign_of_thm th) (Var (("C", #maxidx (Thm.rep_thm th) + 1), propT));
     val dummy_st = Drule.mk_triv_goal (Drule.list_implies (As, C));
   in th COMP Thm.lift_rule (dummy_st, 1) Data.local_impI end;
@@ -256,7 +256,7 @@
       | rename_params ((y,_)::ys) = y::rename_params ys;
     fun rename_asm (A:term):term = 
       let val xs = rename_params (Logic.strip_params A)
-          val xs' = case filter (equal x) xs of
+          val xs' = case List.filter (equal x) xs of
                       [] => xs | [_] => xs | _ => index 1 xs
       in Logic.list_rename_params (xs',A) end;
     fun rename_prop (p:term) =
@@ -268,9 +268,9 @@
   | rename _ thm = thm;
 
 fun find_inductT ctxt insts =
-  foldr multiply (insts |> mapfilter (fn [] => NONE | ts => last_elem ts)
+  Library.foldr multiply (insts |> List.mapPartial (fn [] => NONE | ts => List.last ts)
     |> map (InductAttrib.find_inductT ctxt o fastype_of), [[]])
-  |> map join_rules |> flat |> map (rename insts);
+  |> map join_rules |> List.concat |> map (rename insts);
 
 fun find_inductS ctxt (fact :: _) = InductAttrib.find_inductS ctxt fact
   | find_inductS _ _ = [];
@@ -291,7 +291,7 @@
       if null insts then r
       else (align_right "Rule has fewer conclusions than arguments given"
           (Data.dest_concls (Thm.concl_of r)) insts
-        |> (flat o map (prep_inst align_right cert (atomize_term sg)))
+        |> (List.concat o map (prep_inst align_right cert (atomize_term sg)))
         |> Drule.cterm_instantiate) r);
 
     val ruleq =
@@ -305,8 +305,8 @@
       | SOME r => r |> Seq.THEN (rule_versions, Seq.single o inst_rule));
 
     fun prep_rule (th, (cases, n)) =
-      Seq.map (rpair (cases, n - length facts, drop (n, facts)))
-        (Method.multi_resolves (take (n, facts)) [th]);
+      Seq.map (rpair (cases, n - length facts, Library.drop (n, facts)))
+        (Method.multi_resolves (Library.take (n, facts)) [th]);
     val tac = resolveq_cases_tac' RuleCases.make is_open (Seq.flat (Seq.map prep_rule ruleq));
   in tac THEN_ALL_NEW_CASES rulify_tac end;
 
--- a/src/Provers/make_elim.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/Provers/make_elim.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -41,7 +41,7 @@
 	      | rl'::_ => making (i+1,rl')
     in  making (2, hd (compose_extra 1 (rl, 1, revcut_rl')))  end
     handle (*in default, use the previous version, which never fails*)
-	   THM _ => Tactic.make_elim rl | LIST _ => Tactic.make_elim rl;
+	   THM _ => Tactic.make_elim rl | Empty => Tactic.make_elim rl;
 
 end
  
--- a/src/Provers/order.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/Provers/order.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -91,7 +91,7 @@
   (* Internal exception, raised if contradiction ( x < x ) was derived *)
 
 fun prove asms = 
-  let fun pr (Asm i) = nth_elem (i, asms)
+  let fun pr (Asm i) = List.nth (asms, i)
   |       pr (Thm (prfs, thm)) = (map pr prfs) MRS thm
   in pr end;
 
@@ -437,7 +437,7 @@
 
    (* Compute, for each adjacency list, the list with reversed edges,
       and concatenate these lists. *)
-   val flipped = foldr (op @) ((map flip g),nil)
+   val flipped = Library.foldr (op @) ((map flip g),nil)
  
  in assemble g flipped end    
       
@@ -475,7 +475,7 @@
       let
    val _ = visited := u :: !visited
    val descendents =
-       foldr (fn ((v,l),ds) => if been_visited v then ds
+       Library.foldr (fn ((v,l),ds) => if been_visited v then ds
             else v :: dfs_visit g v @ ds)
         ((adjacent (op aconv) g u) ,nil)
       in
@@ -499,7 +499,7 @@
      dfs_visit along with u form a connected component. We
      collect all the connected components together in a
      list, which is what is returned. *)
-  foldl (fn (comps,u) =>  
+  Library.foldl (fn (comps,u) =>  
       if been_visited u then comps
       else ((u :: dfs_visit (transpose (op aconv) G) u) :: comps))  (nil,(!finish))
 end;
@@ -525,7 +525,7 @@
       let
    val _ = visited := u :: !visited
    val descendents =
-       foldr (fn ((v,l),ds) => if been_visited v then ds
+       Library.foldr (fn ((v,l),ds) => if been_visited v then ds
             else v :: dfs_visit g v @ ds)
         ( ((adjacent (op =) g u)) ,nil)
    in  descendents end
@@ -537,7 +537,7 @@
     ListPair.map (fn (a,b) => (a,b)) (0 upto (length components -1), components);
 
 fun indexNodes IndexComp = 
-    flat (map (fn (index, comp) => (map (fn v => (v,index)) comp)) IndexComp);
+    List.concat (map (fn (index, comp) => (map (fn v => (v,index)) comp)) IndexComp);
     
 fun getIndex v [] = ~1
 |   getIndex v ((v',k)::vs) = if v aconv v' then k else getIndex v vs; 
@@ -651,15 +651,15 @@
 	       val v = upper edge
 	   in
              if (getIndex u ntc) = xi then 
-	       (completeTermPath x u (nth_elem(xi, sccSubgraphs)) )@[edge]
-	       @(completeTermPath v y' (nth_elem((getIndex y' ntc),sccSubgraphs)) )
+	       (completeTermPath x u (List.nth(sccSubgraphs, xi)) )@[edge]
+	       @(completeTermPath v y' (List.nth(sccSubgraphs, getIndex y' ntc)) )
 	     else (rev_completeComponentPath u)@[edge]
-	          @(completeTermPath v y' (nth_elem((getIndex y' ntc),sccSubgraphs)) )
+	          @(completeTermPath v y' (List.nth(sccSubgraphs, getIndex y' ntc)) )
            end
    in  
       if x aconv y then 
         [(Le (x, y, (Thm ([], Less.le_refl))))]
-      else ( if xi = yi then completeTermPath x y (nth_elem(xi, sccSubgraphs))
+      else ( if xi = yi then completeTermPath x y (List.nth(sccSubgraphs, xi))
              else rev_completeComponentPath y )  
    end;
 
@@ -820,15 +820,15 @@
                 (* if SCC_x is linked to SCC_y via edge e *)
 		 else if ui = xi andalso vi = yi then (
                    case e of (Less (_, _,_)) => (
-		        let val xypath = (completeTermPath x u (nth_elem(ui, sccSubgraphs)) ) @ [e] @ (completeTermPath v y (nth_elem(vi, sccSubgraphs)) )
+		        let val xypath = (completeTermPath x u (List.nth(sccSubgraphs, ui)) ) @ [e] @ (completeTermPath v y (List.nth(sccSubgraphs, vi)) )
 			    val xyLesss = transPath (tl xypath, hd xypath)
 			in  (Thm ([getprf xyLesss], Less.less_imp_neq)) end)
 		   | _ => (   
 		        let 
-			    val xupath = completeTermPath x u  (nth_elem(ui, sccSubgraphs))
-			    val uxpath = completeTermPath u x  (nth_elem(ui, sccSubgraphs))
-			    val vypath = completeTermPath v y  (nth_elem(vi, sccSubgraphs))
-			    val yvpath = completeTermPath y v  (nth_elem(vi, sccSubgraphs))
+			    val xupath = completeTermPath x u  (List.nth(sccSubgraphs, ui))
+			    val uxpath = completeTermPath u x  (List.nth(sccSubgraphs, ui))
+			    val vypath = completeTermPath v y  (List.nth(sccSubgraphs, vi))
+			    val yvpath = completeTermPath y v  (List.nth(sccSubgraphs, vi))
 			    val xuLesss = transPath (tl xupath, hd xupath)     
 			    val uxLesss = transPath (tl uxpath, hd uxpath)			    
 			    val vyLesss = transPath (tl vypath, hd vypath)			
@@ -841,15 +841,15 @@
 			)       
 		  ) else if ui = yi andalso vi = xi then (
 		     case e of (Less (_, _,_)) => (
-		        let val xypath = (completeTermPath y u (nth_elem(ui, sccSubgraphs)) ) @ [e] @ (completeTermPath v x (nth_elem(vi, sccSubgraphs)) )
+		        let val xypath = (completeTermPath y u (List.nth(sccSubgraphs, ui)) ) @ [e] @ (completeTermPath v x (List.nth(sccSubgraphs, vi)) )
 			    val xyLesss = transPath (tl xypath, hd xypath)
 			in (Thm ([(Thm ([getprf xyLesss], Less.less_imp_neq))] , thm "not_sym")) end ) 
 		     | _ => (
 		        
-			let val yupath = completeTermPath y u (nth_elem(ui, sccSubgraphs))
-			    val uypath = completeTermPath u y (nth_elem(ui, sccSubgraphs))
-			    val vxpath = completeTermPath v x (nth_elem(vi, sccSubgraphs))
-			    val xvpath = completeTermPath x v (nth_elem(vi, sccSubgraphs))
+			let val yupath = completeTermPath y u (List.nth(sccSubgraphs, ui))
+			    val uypath = completeTermPath u y (List.nth(sccSubgraphs, ui))
+			    val vxpath = completeTermPath v x (List.nth(sccSubgraphs, vi))
+			    val xvpath = completeTermPath x v (List.nth(sccSubgraphs, vi))
 			    val yuLesss = transPath (tl yupath, hd yupath)     
 			    val uyLesss = transPath (tl uypath, hd uypath)			    
 			    val vxLesss = transPath (tl vxpath, hd vxpath)			
@@ -944,9 +944,9 @@
     fun processComponent (k, comp) = 
      let    
         (* all edges with weight <= of the actual component *)  
-        val leqEdges = flat (map (adjacent (op aconv) leqG) comp);
+        val leqEdges = List.concat (map (adjacent (op aconv) leqG) comp);
         (* all edges with weight ~= of the actual component *)  
-        val neqEdges = map snd (flat (map (adjacent (op aconv) neqG) comp));
+        val neqEdges = map snd (List.concat (map (adjacent (op aconv) neqG) comp));
 
        (* find an edge leading to a contradiction *)   
        fun findContr [] = NONE
@@ -1064,7 +1064,7 @@
   val rfrees = map Free (rename_wrt_term A (Logic.strip_params A))
   val Hs = map (fn H => subst_bounds (rfrees, H)) (Logic.strip_assums_hyp A)
   val C = subst_bounds (rfrees, Logic.strip_assums_concl A)
-  val lesss = flat (ListPair.map (mkasm_partial sign) (Hs, 0 upto (length Hs - 1)))
+  val lesss = List.concat (ListPair.map (mkasm_partial sign) (Hs, 0 upto (length Hs - 1)))
   val prfs = solvePartialOrder sign (lesss, C);
   val (subgoals, prf) = mkconcl_partial sign C;
  in
@@ -1082,7 +1082,7 @@
   val rfrees = map Free (rename_wrt_term A (Logic.strip_params A))
   val Hs = map (fn H => subst_bounds (rfrees, H)) (Logic.strip_assums_hyp A)
   val C = subst_bounds (rfrees, Logic.strip_assums_concl A)
-  val lesss = flat (ListPair.map (mkasm_linear sign) (Hs, 0 upto (length Hs - 1)))
+  val lesss = List.concat (ListPair.map (mkasm_linear sign) (Hs, 0 upto (length Hs - 1)))
   val prfs = solveTotalOrder sign (lesss, C);
   val (subgoals, prf) = mkconcl_linear sign C;
  in
--- a/src/Provers/quasi.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/Provers/quasi.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -92,7 +92,7 @@
   (* Internal exception, raised if contradiction ( x < x ) was derived *)
 
 fun prove asms = 
-  let fun pr (Asm i) = nth_elem (i, asms)
+  let fun pr (Asm i) = List.nth (asms, i)
   |       pr (Thm (prfs, thm)) = (map pr prfs) MRS thm
   in pr end;
 
@@ -560,7 +560,7 @@
   val rfrees = map Free (rename_wrt_term A (Logic.strip_params A))
   val Hs = map (fn H => subst_bounds (rfrees, H)) (Logic.strip_assums_hyp A)
   val C = subst_bounds (rfrees, Logic.strip_assums_concl A)
-  val lesss = flat (ListPair.map (mkasm_trans  sign) (Hs, 0 upto (length Hs - 1)))
+  val lesss = List.concat (ListPair.map (mkasm_trans  sign) (Hs, 0 upto (length Hs - 1)))
   val prfs = solveLeTrans  sign (lesss, C);
   
   val (subgoal, prf) = mkconcl_trans  sign C;
@@ -581,7 +581,7 @@
   val rfrees = map Free (rename_wrt_term A (Logic.strip_params A))
   val Hs = map (fn H => subst_bounds (rfrees, H)) (Logic.strip_assums_hyp A)
   val C = subst_bounds (rfrees, Logic.strip_assums_concl A)
-  val lesss = flat (ListPair.map (mkasm_quasi sign) (Hs, 0 upto (length Hs - 1)))
+  val lesss = List.concat (ListPair.map (mkasm_quasi sign) (Hs, 0 upto (length Hs - 1)))
   val prfs = solveQuasiOrder sign (lesss, C);
   val (subgoals, prf) = mkconcl_quasi sign C;
  in
--- a/src/Provers/simp.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/Provers/simp.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -78,7 +78,7 @@
 	  bimatch_tac (Net.match_term net
 		       (lhs_of (strip_assums_concl prem))) i);
 
-fun nth_subgoal i thm = nth_elem(i-1,prems_of thm);
+fun nth_subgoal i thm = List.nth(prems_of thm,i-1);
 
 fun goal_concl i thm = strip_assums_concl(nth_subgoal i thm);
 
@@ -155,7 +155,7 @@
 		     in case f of
 			    Const(c,T) => 
 				if c mem ccs
-				then foldr add_hvars (args,hvars)
+				then Library.foldr add_hvars (args,hvars)
 				else add_term_vars(tm,hvars)
 			  | _ => add_term_vars(tm,hvars)
 		     end
@@ -167,7 +167,7 @@
 		if at then vars else add_term_vars(tm,vars)
 	fun add_list(tm,al,vars) = let val (_,tml) = strip_comb tm
 		in if length(tml)=length(al)
-		   then foldr itf (tml~~al,vars)
+		   then Library.foldr itf (tml~~al,vars)
 		   else vars
 		end
 	fun add_vars (tm,vars) = case tm of
@@ -188,12 +188,12 @@
     val lhs = rhs_of_eq 1 thm'
     val rhs = lhs_of_eq nops thm'
     val asms = tl(rev(tl(prems_of thm')))
-    val hvars = foldr (add_hidden_vars ccs) (lhs::rhs::asms,[])
+    val hvars = Library.foldr (add_hidden_vars ccs) (lhs::rhs::asms,[])
     val hvars = add_new_asm_vars new_asms (rhs,hvars)
     fun it_asms (asm,hvars) =
 	if atomic asm then add_new_asm_vars new_asms (asm,hvars)
 	else add_term_frees(asm,hvars)
-    val hvars = foldr it_asms (asms,hvars)
+    val hvars = Library.foldr it_asms (asms,hvars)
     val hvs = map (#1 o dest_Var) hvars
     val refl1_tac = refl_tac 1
     fun norm_step_tac st = st |>
@@ -210,7 +210,7 @@
 
 fun add_norm_tags congs =
     let val ccs = map cong_const congs
-	val new_asms = filter (exists not o #2)
+	val new_asms = List.filter (exists not o #2)
 		(ccs ~~ (map (map atomic o prems_of) congs));
     in add_norms(congs,ccs,new_asms) end;
 
@@ -249,7 +249,7 @@
     (writeln"\nDuplicate rewrite or congruence rule:"; print_thm th;
      net);
 
-val insert_thms = foldr insert_thm_warn;
+val insert_thms = Library.foldr insert_thm_warn;
 
 fun addrew(SS{auto_tac,congs,cong_net,mk_simps,simps,simp_net,
               splits,split_consts}, thm) =
@@ -259,7 +259,7 @@
       splits=splits,split_consts=split_consts}
 end;
 
-val op addrews = foldl addrew;
+val op addrews = Library.foldl addrew;
 
 fun op addcongs(SS{auto_tac,congs,cong_net,mk_simps,simps,simp_net,
                    splits,split_consts}, thms) =
@@ -283,7 +283,7 @@
       mk_simps=mk_simps,simps=simps,simp_net=simp_net,
       splits=splits@[mk_trans thm],split_consts=split_consts@[a]} end;
 
-val op addsplits = foldl addsplit;
+val op addsplits = Library.foldl addsplit;
 
 (** Deletion of congruences and rewrites **)
 
@@ -294,11 +294,11 @@
     (writeln"\nNo such rewrite or congruence rule:";  print_thm th;
      net);
 
-val delete_thms = foldr delete_thm_warn;
+val delete_thms = Library.foldr delete_thm_warn;
 
 fun op delcongs(SS{auto_tac,congs,cong_net,mk_simps,simps,simp_net,
                    splits,split_consts}, thms) =
-let val congs' = foldl (gen_rem Drule.eq_thm_prop) (congs,thms)
+let val congs' = Library.foldl (gen_rem Drule.eq_thm_prop) (congs,thms)
 in SS{auto_tac=auto_tac, congs= congs',
       cong_net= delete_thms(map mk_trans thms,cong_net),
       mk_simps= normed_rews congs', simps=simps, simp_net=simp_net,
@@ -318,7 +318,7 @@
       splits=splits,split_consts=split_consts}
 end;
 
-val op delrews = foldl delrew;
+val op delrews = Library.foldl delrew;
 
 
 fun op setauto(SS{congs,cong_net,mk_simps,simps,simp_net,
@@ -447,9 +447,9 @@
 	    SOME(thm',_) =>
 		    let val ps = prems_of thm and ps' = prems_of thm';
 			val n = length(ps')-length(ps);
-			val a = length(strip_assums_hyp(nth_elem(i-1,ps)))
+			val a = length(strip_assums_hyp(List.nth(ps,i-1)))
 			val l = map (fn p => length(strip_assums_hyp(p)))
-				    (take(n,drop(i-1,ps')));
+				    (Library.take(n,Library.drop(i-1,ps')));
 		    in (simp_refl(rev(l),a,REW::ss),thm',anet,ats,cs) end
 	  | NONE => (REW::ss,thm,anet,ats,cs);
 
@@ -460,7 +460,7 @@
 	val thms = map (trivial o cterm_of(#sign(rep_thm(thm))))As;
 	val new_rws = flat(map mk_rew_rules thms);
 	val rwrls = map mk_trans (flat(map mk_rew_rules thms));
-	val anet' = foldr lhs_insert_thm (rwrls,anet)
+	val anet' = Library.foldr lhs_insert_thm (rwrls,anet)
     in  if !tracing andalso not(null new_rws)
 	then (writeln"Adding rewrites:";  prths new_rws;  ())
 	else ();
@@ -565,7 +565,7 @@
 fun Pinst(f,fT,(eq,eqT),k,i,T,yik,Ts) =
 let fun xn_list(x,n) =
 	let val ixs = map (fn i => (x^(radixstring(26,"a",i)),0)) (0 upto n);
-	in ListPair.map eta_Var (ixs, take(n+1,Ts)) end
+	in ListPair.map eta_Var (ixs, Library.take(n+1,Ts)) end
     val lhs = list_comb(f,xn_list("X",k-1))
     val rhs = list_comb(f,xn_list("X",i-1) @ [Bound 0] @ yik)
 in Abs("", T, Const(eq,[fT,fT]--->eqT) $ lhs $ rhs) end;
--- a/src/Provers/splitter.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/Provers/splitter.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -102,8 +102,8 @@
       fun down [] t i = Bound 0
         | down (p::ps) t i =
             let val (h,ts) = strip_comb t
-                val v1 = ListPair.map var (take(p,ts), i upto (i+p-1))
-                val u::us = drop(p,ts)
+                val v1 = ListPair.map var (Library.take(p,ts), i upto (i+p-1))
+                val u::us = Library.drop(p,ts)
                 val v2 = ListPair.map var (us, (i+p) upto (i+length(ts)-2))
       in list_comb(h,v1@[down ps u (i+length ts)]@v2) end;
   in Abs("", T, down (rev pos) t maxi) end;
@@ -137,7 +137,7 @@
    has a body of type T; otherwise the expansion thm will fail later on
 *)
 fun type_test(T,lbnos,apsns) =
-  let val (_,U,_) = nth_elem(foldl Int.min (hd lbnos, tl lbnos), apsns)
+  let val (_,U,_) = List.nth(apsns, Library.foldl Int.min (hd lbnos, tl lbnos))
   in T=U end;
 
 (*************************************************************************
@@ -171,8 +171,8 @@
 fun mk_split_pack(thm, T, T', n, ts, apsns, pos, TB, t) =
   if n > length ts then []
   else let val lev = length apsns
-           val lbnos = foldl add_lbnos ([],take(n,ts))
-           val flbnos = filter (fn i => i < lev) lbnos
+           val lbnos = Library.foldl add_lbnos ([],Library.take(n,ts))
+           val flbnos = List.filter (fn i => i < lev) lbnos
            val tt = incr_boundvars (~lev) t
        in if null flbnos then
             if T = T' then [(thm,[],pos,TB,tt)] else []
@@ -234,7 +234,7 @@
               Const(c, cT) =>
                 let fun find [] = []
                       | find ((gcT, pat, thm, T, n)::tups) =
-                          let val t2 = list_comb (h, take (n, ts))
+                          let val t2 = list_comb (h, Library.take (n, ts))
                           in if Sign.typ_instance sg (cT, gcT)
                                 andalso fomatch (Sign.tsig_of sg) (Ts,pat,t2)
                              then mk_split_pack(thm,T,T',n,ts,apsns,pos,type_of1(Ts,t2),t2)
@@ -242,11 +242,11 @@
                           end
                 in find (assocs cmap c) end
             | _ => []
-          in snd(foldl iter ((0, a), ts)) end
+          in snd(Library.foldl iter ((0, a), ts)) end
   in posns Ts [] [] t end;
 
 
-fun nth_subgoal i thm = nth_elem(i-1,prems_of thm);
+fun nth_subgoal i thm = List.nth(prems_of thm,i-1);
 
 fun shorter((_,ps,pos,_,_),(_,qs,qos,_,_)) =
   prod_ord (int_ord o pairself length) (order o pairself length)
@@ -312,7 +312,7 @@
       (Logic.strip_assums_concl (#prop (rep_thm thm')))));
     val cert = cterm_of (sign_of_thm state);
     val cntxt = mk_cntxt_splitthm t tt TB;
-    val abss = foldl (fn (t, T) => Abs ("", T, t));
+    val abss = Library.foldl (fn (t, T) => Abs ("", T, t));
   in cterm_instantiate [(cert P, cert (abss (cntxt, Ts)))] thm'
   end;
 
@@ -337,7 +337,7 @@
                   end
                 | _ => split_format_err())
              | _ => split_format_err())
-      val cmap = foldl add_thm ([],splits);
+      val cmap = Library.foldl add_thm ([],splits);
       fun lift_tac Ts t p st = rtac (inst_lift Ts t p st i) i st
       fun lift_split_tac state =
             let val (Ts, t, splits) = select cmap state i
@@ -421,13 +421,13 @@
         let val (name,asm) = split_thm_info split
         in Simplifier.addloop (ss, (split_name name asm,
 		       (if asm then split_asm_tac else split_tac) [split])) end
-  in foldl addsplit (ss,splits) end;
+  in Library.foldl addsplit (ss,splits) end;
 
 fun ss delsplits splits =
   let fun delsplit(ss,split) =
         let val (name,asm) = split_thm_info split
         in Simplifier.delloop (ss, split_name name asm)
-  end in foldl delsplit (ss,splits) end;
+  end in Library.foldl delsplit (ss,splits) end;
 
 fun Addsplits splits = (Simplifier.simpset_ref() := 
 			Simplifier.simpset() addsplits splits);
--- a/src/Provers/trancl.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/Provers/trancl.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -88,7 +88,7 @@
  exception Cannot; (* internal exception: raised if no proof can be found *)
 
  fun prove asms = 
-  let fun pr (Asm i) = nth_elem (i, asms)
+  let fun pr (Asm i) = List.nth (asms, i)
   |       pr (Thm (prfs, thm)) = (map pr prfs) MRS thm
   in pr end;
 
@@ -327,7 +327,7 @@
 
    (* Compute, for each adjacency list, the list with reversed edges,
       and concatenate these lists. *)
-   val flipped = foldr (op @) ((map flip g),nil)
+   val flipped = Library.foldr (op @) ((map flip g),nil)
  
  in assemble g flipped end    
  
@@ -351,7 +351,7 @@
       let
    val _ = visited := u :: !visited
    val descendents =
-       foldr (fn ((v,l),ds) => if been_visited v then ds
+       Library.foldr (fn ((v,l),ds) => if been_visited v then ds
             else v :: dfs_visit g v @ ds)
         ( ((adjacent eq_comp g u)) ,nil)
    in  descendents end
@@ -530,7 +530,7 @@
   val Hs = Logic.strip_assums_hyp A;
   val C = Logic.strip_assums_concl A;
   val (rel,subgoals, prf) = mkconcl_trancl C;
-  val prems = flat (ListPair.map (mkasm_trancl rel) (Hs, 0 upto (length Hs - 1)))
+  val prems = List.concat (ListPair.map (mkasm_trancl rel) (Hs, 0 upto (length Hs - 1)))
   val prfs = solveTrancl (prems, C);
 
  in
@@ -548,7 +548,7 @@
   val C = Logic.strip_assums_concl A;
   val (rel,subgoals, prf) = mkconcl_rtrancl C;
 
-  val prems = flat (ListPair.map (mkasm_rtrancl rel) (Hs, 0 upto (length Hs - 1)))
+  val prems = List.concat (ListPair.map (mkasm_rtrancl rel) (Hs, 0 upto (length Hs - 1)))
   val prfs = solveRtrancl (prems, C);
  in
   METAHYPS (fn asms =>
--- a/src/Provers/typedsimp.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/Provers/typedsimp.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -70,7 +70,7 @@
     handle THM _ => (simp_rls, rl :: other_rls);
 
 (*Given the list rls, return the pair (simp_rls, other_rls).*)
-fun process_rules rls = foldr add_rule (rls, ([],[]));
+fun process_rules rls = Library.foldr add_rule (rls, ([],[]));
 
 (*Given list of rewrite rules, return list of both forms, reject others*)
 fun process_rewrites rls = 
--- a/src/Pure/General/file.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/Pure/General/file.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -96,7 +96,7 @@
     | s => SOME (Info s))
   end;
 
-val exists = is_some o info;
+val exists = isSome o info;
 
 
 (* directories *)
--- a/src/Pure/General/graph.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/Pure/General/graph.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -67,7 +67,7 @@
 val empty_keys = Table.empty: keys;
 
 infix mem_keys;
-fun x mem_keys tab = is_some (Table.lookup (tab: keys, x));
+fun x mem_keys tab = isSome (Table.lookup (tab: keys, x));
 
 infix ins_keys;
 fun x ins_keys tab = if x mem_keys tab then tab else Table.update ((x, ()), tab);
@@ -114,7 +114,7 @@
     fun reach ((R, rs), x) =
       if x mem_keys R then (R, rs)
       else apsnd (cons x) (reachs ((x ins_keys R, rs), next x))
-    and reachs R_xs = foldl reach R_xs;
+    and reachs R_xs = Library.foldl reach R_xs;
   in foldl_map (reach o apfst (rpair [])) (empty_keys, xs) end;
 
 (*immediate*)
@@ -122,13 +122,13 @@
 fun imm_succs G = #2 o #2 o get_entry G;
 
 (*transitive*)
-fun all_preds G = flat o snd o reachable (imm_preds G);
-fun all_succs G = flat o snd o reachable (imm_succs G);
+fun all_preds G = List.concat o snd o reachable (imm_preds G);
+fun all_succs G = List.concat o snd o reachable (imm_succs G);
 
 (*strongly connected components; see: David King and John Launchbury,
   "Structuring Depth First Search Algorithms in Haskell"*)
 fun strong_conn G = filter_out null (snd (reachable (imm_preds G)
-  (flat (rev (snd (reachable (imm_succs G) (keys G)))))));
+  (List.concat (rev (snd (reachable (imm_succs G) (keys G)))))));
 
 
 (* paths *)
@@ -139,7 +139,7 @@
     fun paths ps p =
       if not (null ps) andalso eq_key (p, x) then [p :: ps]
       else if p mem_keys X andalso not (p mem_key ps)
-      then flat (map (paths (p :: ps)) (imm_preds G p))
+      then List.concat (map (paths (p :: ps)) (imm_preds G p))
       else [];
   in paths [] y end;
 
@@ -155,8 +155,8 @@
   let
     fun del (x, (i, (preds, succs))) =
       if x mem_key xs then NONE
-      else SOME (x, (i, (foldl op del_key (preds, xs), foldl op del_key (succs, xs))));
-  in Graph (Table.make (mapfilter del (Table.dest tab))) end;
+      else SOME (x, (i, (Library.foldl op del_key (preds, xs), Library.foldl op del_key (succs, xs))));
+  in Graph (Table.make (List.mapPartial del (Table.dest tab))) end;
 
 
 (* edges *)
@@ -176,7 +176,7 @@
   else G;
 
 fun diff_edges G1 G2 =
-  flat (dest G1 |> map (fn (x, ys) => ys |> mapfilter (fn y =>
+  List.concat (dest G1 |> map (fn (x, ys) => ys |> List.mapPartial (fn y =>
     if is_edge G2 (x, y) then NONE else SOME (x, y))));
 
 fun edges G = diff_edges G empty;
@@ -205,7 +205,7 @@
     | cycles => raise CYCLES (map (cons x) cycles));
 
 fun add_deps_acyclic (y, xs) G =
-  foldl (fn (H, x) => add_edge_acyclic (x, y) H) (G, xs);
+  Library.foldl (fn (H, x) => add_edge_acyclic (x, y) H) (G, xs);
 
 fun merge_acyclic eq GG = gen_merge add_edge_acyclic eq GG;
 
--- a/src/Pure/General/history.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/Pure/General/history.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -35,7 +35,7 @@
 fun current (History (x, _)) = x;
 
 fun clear n (History (x, (lim, len, undo_list, redo_list))) =
-  History (x, (lim, Int.max (0, len - n), drop (n, undo_list), redo_list));
+  History (x, (lim, Int.max (0, len - n), Library.drop (n, undo_list), redo_list));
 
 fun undo (History (_, (_, _, [], _))) = error "No further undo information"
   | undo (History (x, (lim, len, u :: undo_list, redo_list))) =
@@ -47,7 +47,7 @@
 
 fun push NONE _ x xs = x :: xs
   | push (SOME 0) _ _ _ = []
-  | push (SOME n) len x xs = if len < n then x :: xs else take (n, x :: xs);
+  | push (SOME n) len x xs = if len < n then x :: xs else Library.take (n, x :: xs);
 
 fun apply_copy cp f (History (x, (lim, len, undo_list, _))) =
   let val x' = cp x
--- a/src/Pure/General/lazy_seq.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/Pure/General/lazy_seq.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -83,7 +83,7 @@
 fun getItem (Seq s) = force s
 fun make f = Seq (delay f)
 
-fun null s = is_some (getItem s)
+fun null s = isSome (getItem s)
 
 local
     fun F n NONE = n
@@ -397,8 +397,8 @@
 	make (fn () => copy (f x))
     end
 
-fun EVERY fs = foldr THEN (fs, succeed)
-fun FIRST fs = foldr ORELSE (fs, fail)
+fun EVERY fs = Library.foldr THEN (fs, succeed)
+fun FIRST fs = Library.foldr ORELSE (fs, fail)
 
 fun TRY f x =
     make (fn () =>
--- a/src/Pure/General/name_space.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/Pure/General/name_space.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -50,7 +50,7 @@
 val unpack = space_explode separator;
 val pack = space_implode separator;
 
-val base = last_elem o unpack;
+val base = List.last o unpack;
 
 fun map_base f name =
   let val uname = unpack name
@@ -75,7 +75,7 @@
 (* basic operations *)
 
 fun map_space f xname tab =
-  Symtab.update ((xname, f (if_none (Symtab.lookup (tab, xname)) ([], []))), tab);
+  Symtab.update ((xname, f (getOpt (Symtab.lookup (tab, xname), ([], [])))), tab);
 
 fun change f xname (name, tab) =
   map_space (fn (names, names') => (f names name, names')) xname tab;
@@ -100,9 +100,9 @@
 fun extend_aux (name, tab) =
   if is_hidden name then
     error ("Attempt to declare hidden name " ^ quote name)
-  else foldl (fn (tb, xname) => change add xname (name, tb)) (tab, accesses name);
+  else Library.foldl (fn (tb, xname) => change add xname (name, tb)) (tab, accesses name);
 
-fun extend (NameSpace tab, names) = NameSpace (foldr extend_aux (names, tab));
+fun extend (NameSpace tab, names) = NameSpace (Library.foldr extend_aux (names, tab));
 
 
 (* merge *)             (*1st preferred over 2nd*)
@@ -123,10 +123,10 @@
   else if is_hidden name then
     error ("Attempt to hide hidden name " ^ quote name)
   else (change' add name (name,
-    foldl (fn (tb, xname) => change del xname (name, tb))
+    Library.foldl (fn (tb, xname) => change del xname (name, tb))
       (tab, if fully then accesses name else [base name])));
 
-fun hide fully (NameSpace tab, names) = NameSpace (foldr (hide_aux fully) (names, tab));
+fun hide fully (NameSpace tab, names) = NameSpace (Library.foldr (hide_aux fully) (names, tab));
 
 
 (* intern / extern names *)
@@ -175,7 +175,7 @@
 
 fun dest (NameSpace tab) =
   map (apsnd (sort (int_ord o pairself size)))
-    (Symtab.dest (Symtab.make_multi (mapfilter dest_entry (Symtab.dest tab))));
+    (Symtab.dest (Symtab.make_multi (List.mapPartial dest_entry (Symtab.dest tab))));
 
 
 end;
--- a/src/Pure/General/path.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/Pure/General/path.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -90,7 +90,7 @@
   | rev_app xs (y :: ys) = rev_app (y :: xs) ys;
 
 fun append (Path xs) (Path ys) = Path (rev_app (rev xs) ys);
-fun appends paths = foldl (uncurry append) (current, paths);
+fun appends paths = Library.foldl (uncurry append) (current, paths);
 val make = appends o map basic;
 fun norm path = rev_app [] path;
 
@@ -142,7 +142,7 @@
 val split_ext = split_path (fn (prfx, s) => apfst (append (Path prfx))
   (case take_suffix (not_equal ".") (explode s) of
     ([], _) => (Path [Basic s], "")
-  | (cs, e) => (Path [Basic (implode (take (length cs - 1, cs)))], implode e)));
+  | (cs, e) => (Path [Basic (implode (Library.take (length cs - 1, cs)))], implode e)));
 
 
 (* evaluate variables *)
@@ -151,7 +151,7 @@
   | eval _ x = [x];
 
 fun evaluate env (Path xs) =
-  Path (norm (flat (map (eval env) xs)));
+  Path (norm (List.concat (map (eval env) xs)));
 
 val expand = evaluate (unpack o getenv);
 
--- a/src/Pure/General/pretty.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/Pure/General/pretty.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -204,7 +204,7 @@
   blk (1, [str "\"", prt, str "\""]);
 
 fun commas prts =
-  flat (separate [str ",", brk 1] (map (fn x => [x]) prts));
+  List.concat (separate [str ",", brk 1] (map (fn x => [x]) prts));
 
 fun breaks prts = separate (brk 1) prts;
 fun fbreaks prts = separate fbrk prts;
--- a/src/Pure/General/scan.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/Pure/General/scan.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -204,7 +204,7 @@
 
 fun trace scan toks =
   let val (x, toks') = scan toks
-  in ((x, take (length toks - length toks', toks)), toks') end;
+  in ((x, Library.take (length toks - length toks', toks)), toks') end;
 
 
 (* state based scanners *)
@@ -247,7 +247,7 @@
   in
     if exists is_stopper input then
       raise ABORT "Stopper may not occur in input of finite scan!"
-    else (force scan --| lift stop) (state, rev_append (rev input) [stopper])
+    else (force scan --| lift stop) (state, List.revAppend (rev input,[stopper]))
   end;
 
 fun finite stopper scan xs =
@@ -264,7 +264,7 @@
 
 fun drain def_prmpt get stopper scan ((state, xs), src) =
   (scan (state, xs), src) handle MORE prmpt =>
-    (case get (if_none prmpt def_prmpt) src of
+    (case get (getOpt (prmpt,def_prmpt)) src of
       ([], _) => (finite' stopper scan (state, xs), src)
     | (xs', src') => drain def_prmpt get stopper scan ((state, xs @ xs'), src'));
 
@@ -274,7 +274,7 @@
 
     fun drain_loop recover inp =
       drain_with (catch scanner) inp handle FAIL msg =>
-        (error_msg (if_none msg "Syntax error."); drain_with recover inp);
+        (error_msg (getOpt (msg,"Syntax error.")); drain_with recover inp);
 
     val ((ys, (state', xs')), src') =
       (case (get def_prmpt src, opt_recover) of
@@ -285,7 +285,7 @@
 
 fun source def_prmpt get unget stopper scan opt_recover src =
   let val (ys, ((), src')) =
-    source' def_prmpt get unget stopper (lift scan) (apsome lift opt_recover) ((), src)
+    source' def_prmpt get unget stopper (lift scan) (Option.map lift opt_recover) ((), src)
   in (ys, src') end;
 
 fun single scan = scan >> (fn x => [x]);
@@ -333,7 +333,7 @@
                   Branch (c, no_literal, Empty, add Empty cs, Empty)
               | add lex [] = lex;
           in add lex chrs end;
-      in foldl ext (lexicon, chrss \\ dest_lex lexicon) end;
+      in Library.foldl ext (lexicon, chrss \\ dest_lex lexicon) end;
 
 val make_lexicon = extend_lexicon empty_lexicon;
 
--- a/src/Pure/General/seq.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/Pure/General/seq.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -71,8 +71,8 @@
 fun single x = cons (x, empty);
 
 (*head and tail -- beware of calling the sequence function twice!!*)
-fun hd xq = #1 (the (pull xq))
-and tl xq = #2 (the (pull xq));
+fun hd xq = #1 (valOf (pull xq))
+and tl xq = #2 (valOf (pull xq));
 
 (*partial function as procedure*)
 fun try f x =
@@ -97,7 +97,7 @@
   | SOME (x, xq') => x :: list_of xq');
 
 (*conversion from list to sequence*)
-fun of_list xs = foldr cons (xs, empty);
+fun of_list xs = Library.foldr cons (xs, empty);
 
 
 (*map the function f over the sequence, making a new sequence*)
@@ -203,8 +203,8 @@
 fun op APPEND (f, g) x =
   append (f x, make (fn () => pull (g x)));
 
-fun EVERY fs = foldr THEN (fs, succeed);
-fun FIRST fs = foldr ORELSE (fs, fail);
+fun EVERY fs = Library.foldr THEN (fs, succeed);
+fun FIRST fs = Library.foldr ORELSE (fs, fail);
 
 fun TRY f = ORELSE (f, succeed);
 
--- a/src/Pure/General/symbol.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/Pure/General/symbol.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -342,7 +342,7 @@
     else if is_ascii_quasi s then Quasi
     else if is_ascii_blank s then Blank
     else if is_char s then Other
-    else if_none (Symtab.lookup (symbol_kinds, s)) Other;
+    else getOpt (Symtab.lookup (symbol_kinds, s), Other);
 end;
 
 fun is_letter s = kind s = Letter;
@@ -417,7 +417,7 @@
 fun sym_explode str =
   let val chs = explode str in
     if no_explode chs then chs
-    else the (Scan.read stopper (Scan.repeat scan) chs)
+    else valOf (Scan.read stopper (Scan.repeat scan) chs)
   end;
 
 val chars_only = not o exists_string (equal "\\");
@@ -486,7 +486,7 @@
   else if s = "\\<spacespace>" then 2
   else 1;
 
-fun sym_length ss = foldl (fn (n, s) => sym_len s + n) (0, ss);
+fun sym_length ss = Library.foldl (fn (n, s) => sym_len s + n) (0, ss);
 
 fun symbol_output str =
   if chars_only str then default_output str
--- a/src/Pure/General/table.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/Pure/General/table.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -90,12 +90,12 @@
 fun exists P tab = foldl_table (fn (false, e) => P e | (b, _) => b) (false, tab);
 
 fun min_key Empty = NONE
-  | min_key (Branch2 (left, (k, _), _)) = SOME (if_none (min_key left) k)
-  | min_key (Branch3 (left, (k, _), _, _, _)) = SOME (if_none (min_key left) k);
+  | min_key (Branch2 (left, (k, _), _)) = SOME (getOpt (min_key left,k))
+  | min_key (Branch3 (left, (k, _), _, _, _)) = SOME (getOpt (min_key left,k));
 
 fun max_key Empty = NONE
-  | max_key (Branch2 (_, (k, _), right)) = SOME (if_none (max_key right) k)
-  | max_key (Branch3 (_, _, _, (k,_), right)) = SOME (if_none (max_key right) k);
+  | max_key (Branch2 (_, (k, _), right)) = SOME (getOpt (max_key right,k))
+  | max_key (Branch3 (_, _, _, (k,_), right)) = SOME (getOpt (max_key right,k));
 
 (* lookup *)
 
@@ -178,7 +178,7 @@
         NONE => (update ((key, x), tab), dups)
       | _ => (tab, key :: dups));
   in
-    (case foldl add ((table, []), pairs) of
+    (case Library.foldl add ((table, []), pairs) of
       (table', []) => table'
     | (_, dups) => raise DUPS (rev dups))
   end;
@@ -201,12 +201,12 @@
   | del NONE (Branch3 (Empty, p, Empty, q, Empty)) =
       (p, (false, Branch2 (Empty, q, Empty)))
   | del k (Branch2 (Empty, p, Empty)) = (case compare' k p of
-      EQUAL => (p, (true, Empty)) | _ => raise UNDEF (the k))
+      EQUAL => (p, (true, Empty)) | _ => raise UNDEF (valOf k))
   | del k (Branch3 (Empty, p, Empty, q, Empty)) = (case compare' k p of
       EQUAL => (p, (false, Branch2 (Empty, q, Empty)))
     | _ => (case compare' k q of
         EQUAL => (q, (false, Branch2 (Empty, p, Empty)))
-      | _ => raise UNDEF (the k)))
+      | _ => raise UNDEF (valOf k)))
   | del k (Branch2 (l, p, r)) = (case compare' k p of
       LESS => (case del k l of
         (p', (false, l')) => (p', (false, Branch2 (l', p, r)))
@@ -284,11 +284,11 @@
 
 (* tables with multiple entries per key (preserving order) *)
 
-fun lookup_multi tab_key = if_none (lookup tab_key) [];
+fun lookup_multi tab_key = getOpt (lookup tab_key,[]);
 fun update_multi ((key, x), tab) = update ((key, x :: lookup_multi (tab, key)), tab);
 
-fun make_multi pairs = foldr update_multi (pairs, empty);
-fun dest_multi tab = flat (map (fn (key, xs) => map (Library.pair key) xs) (dest tab));
+fun make_multi pairs = Library.foldr update_multi (pairs, empty);
+fun dest_multi tab = List.concat (map (fn (key, xs) => map (Library.pair key) xs) (dest tab));
 fun merge_multi eq tabs = join (fn (xs, xs') => SOME (gen_merge_lists eq xs xs')) tabs;
 fun merge_multi' eq tabs = join (fn (xs, xs') => SOME (gen_merge_lists' eq xs xs')) tabs;
 
--- a/src/Pure/General/xml.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/Pure/General/xml.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -134,7 +134,7 @@
         || parse_pi >> K []
         || parse_comment >> K []) --
        Scan.optional ((* scan_whspc |-- *) parse_chars >> (single o Text)) []
-         >> op @) >> flat) >> op @)(* --| scan_whspc*)) xs
+         >> op @) >> List.concat) >> op @)(* --| scan_whspc*)) xs
 
 and parse_elem xs =
   ($$ "<" |-- Symbol.scan_id --
--- a/src/Pure/IsaPlanner/isand.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/Pure/IsaPlanner/isand.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -108,13 +108,13 @@
       fun allify_prem_var (vt as (n,ty),t)  = 
           (Term.all ty) $ (Abs(n,ty,Term.abstract_over (Free vt, t)))
 
-      fun allify_prem Ts p = foldr allify_prem_var (Ts, p)
+      fun allify_prem Ts p = Library.foldr allify_prem_var (Ts, p)
 
       val cTs = map (ctermify o Free) Ts
       val cterm_asms = map (ctermify o allify_prem Ts) premts
       val allifyied_asm_thms = map (Drule.forall_elim_list cTs o Thm.assume) cterm_asms
     in 
-      (foldl (fn (x,y) => y COMP x) (th, allifyied_asm_thms), cterm_asms)
+      (Library.foldl (fn (x,y) => y COMP x) (th, allifyied_asm_thms), cterm_asms)
     end;
 
 fun allify_conditions' Ts th = 
@@ -132,7 +132,7 @@
       val names = Term.add_term_names (prop, [])
 
       val (insts,names2) = 
-          foldl (fn ((insts,names),v as ((n,i),ty)) => 
+          Library.foldl (fn ((insts,names),v as ((n,i),ty)) => 
                     let val n2 = Term.variant names n in
                       ((ctermify (Var v), ctermify (Free(n2,ty))) :: insts, 
                        n2 :: names)
@@ -167,7 +167,7 @@
     in (Term.all ty) $ (Abs(n,ty,Term.abstract_over (vt, t))) end;
 
 fun allify_for_sg_term ctermify vs t =
-    let val t_alls = foldr allify_term (vs,t);
+    let val t_alls = Library.foldr allify_term (vs,t);
         val ct_alls = ctermify t_alls; 
     in 
       (ct_alls, Drule.forall_elim_list vs (Thm.assume ct_alls))
@@ -189,7 +189,7 @@
       val (sgallcts, sgthms) = 
           Library.split_list (map (allify_for_sg_term ctermify vs) sgs);
       val minimal_newth = 
-          (foldl (fn ( newth', sgthm) => 
+          (Library.foldl (fn ( newth', sgthm) => 
                           Drule.compose_single (sgthm, 1, newth'))
                       (newth, sgthms));
       val allified_newth = 
@@ -229,7 +229,7 @@
           Library.split_list (map (allify_for_sg_term ctermify cfrees) sgs);
 
       val minimal_th = 
-          (foldl (fn ( th', sgthm) => 
+          (Library.foldl (fn ( th', sgthm) => 
                           Drule.compose_single (sgthm, 1, th'))
                       (th, sgthms)) RS Drule.rev_triv_goal;
 
@@ -256,7 +256,7 @@
                 |> Drule.forall_intr_list cfvs
     in Drule.compose_single (solth', i, gth) end;
 
-val export_solutions = foldr (uncurry export_solution);
+val export_solutions = Library.foldr (uncurry export_solution);
 
 
 (* fix parameters of a subgoal "i", as free variables, and create an
--- a/src/Pure/IsaPlanner/isaplib.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/Pure/IsaPlanner/isaplib.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -159,7 +159,7 @@
   (* for use with tactics... gives no_tac if element isn't there *)
   fun NTH n f st = 
       let val r = nth_of_seq n (f st) in 
-        if (is_none r) then Seq.empty else (Seq.single (the r))
+        if (is_none r) then Seq.empty else (Seq.single (valOf r))
       end;
  
   (* First result of a tactic... uses NTH, so if there is no elements,
@@ -214,7 +214,7 @@
     else if gr(l,h) then get_ends_of gr (u,h) t
     else get_ends_of gr (u,l) t;
 
-fun flatmap f = flat o map f;
+fun flatmap f = List.concat o map f;
 
   (* quick removal of "rs" elements from "ls" when (eqf (r,l)) is true 
 		 Ignores ordering. *)
--- a/src/Pure/IsaPlanner/rw_inst.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/Pure/IsaPlanner/rw_inst.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -89,7 +89,7 @@
       val prop = Thm.prop_of rule;
       val names = Term.add_term_names (prop, []);
       val (fromnames,tonames,names2,Ts') = 
-          foldl (fn ((rnf,rnt,names, Ts'),(n,ty)) => 
+          Library.foldl (fn ((rnf,rnt,names, Ts'),(n,ty)) => 
                     let val n2 = Term.variant names n in
                       (ctermify (Free(RWTools.mk_fake_bound_name n,
                                       ty)) :: rnf,
@@ -108,7 +108,7 @@
 
       (* using these names create lambda-abstracted version of the rule *)
       val abstractions = rev (Ts' ~~ tonames);
-      val abstract_rule = foldl (fn (th,((n,ty),ct)) => 
+      val abstract_rule = Library.foldl (fn (th,((n,ty),ct)) => 
                                     Thm.abstract_rule n ct th)
                                 (uncond_rule, abstractions);
     in (cprems, abstract_rule) end;
@@ -124,9 +124,9 @@
 fun mk_renamings tgt rule_inst = 
     let
       val rule_conds = Thm.prems_of rule_inst
-      val names = foldr Term.add_term_names (tgt :: rule_conds, []);
+      val names = Library.foldr Term.add_term_names (tgt :: rule_conds, []);
       val (conds_tyvs,cond_vs) = 
-          foldl (fn ((tyvs, vs), t) => 
+          Library.foldl (fn ((tyvs, vs), t) => 
                     (Library.union
                        (Term.term_tvars t, tyvs),
                      Library.union 
@@ -135,7 +135,7 @@
       val termvars = map Term.dest_Var (Term.term_vars tgt); 
       val vars_to_fix = Library.union (termvars, cond_vs);
       val (renamings, names2) = 
-          foldr (fn (((n,i),ty), (vs, names')) => 
+          Library.foldr (fn (((n,i),ty), (vs, names')) => 
                     let val n' = Term.variant names' n in
                       ((((n,i),ty), Free (n', ty)) :: vs, n'::names')
                     end)
@@ -152,12 +152,12 @@
    already instantiated (in ignore_ixs) from the list of terms. *)
 fun mk_fixtvar_tyinsts ignore_ixs ts = 
     let val (tvars, tfreenames) = 
-            foldr (fn (t, (varixs, tfreenames)) => 
+            Library.foldr (fn (t, (varixs, tfreenames)) => 
                       (Term.add_term_tvars (t,varixs),
                        Term.add_term_tfree_names (t,tfreenames)))
                   (ts, ([],[]));
-        val unfixed_tvars = filter (fn (ix,s) => not (ix mem ignore_ixs)) tvars;
-        val (fixtyinsts, _) = foldr new_tfree (unfixed_tvars, ([], tfreenames))
+        val unfixed_tvars = List.filter (fn (ix,s) => not (ix mem ignore_ixs)) tvars;
+        val (fixtyinsts, _) = Library.foldr new_tfree (unfixed_tvars, ([], tfreenames))
     in (fixtyinsts, tfreenames) end;
 
 
@@ -222,7 +222,7 @@
           Term.subst_vars (typinsts,[]) outerterm;
 
       (* type-instantiate the var instantiations *)
-      val insts_tyinst = foldr (fn ((ix,t),insts_tyinst) => 
+      val insts_tyinst = Library.foldr (fn ((ix,t),insts_tyinst) => 
                             (ix, Term.subst_vars (typinsts,[]) t)
                             :: insts_tyinst)
                         (unprepinsts,[]);
--- a/src/Pure/IsaPlanner/rw_tools.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/Pure/IsaPlanner/rw_tools.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -130,7 +130,7 @@
 fun fake_concl_of_goal gt i = 
     let 
       val prems = Logic.strip_imp_prems gt
-      val sgt = nth_elem (i - 1, prems)
+      val sgt = List.nth (prems, i - 1)
 
       val tbody = Logic.strip_imp_concl (Term.strip_all_body sgt)
       val tparams = Term.strip_all_vars sgt
@@ -148,7 +148,7 @@
 fun fake_goal gt i = 
     let 
       val prems = Logic.strip_imp_prems gt
-      val sgt = nth_elem (i - 1, prems)
+      val sgt = List.nth (prems, i - 1)
 
       val tbody = Term.strip_all_body sgt
       val tparams = Term.strip_all_vars sgt
--- a/src/Pure/IsaPlanner/term_lib.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/Pure/IsaPlanner/term_lib.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -163,20 +163,20 @@
       case typs_unify of
         SOME (typinsttab, ix2) =>
         let 
-      (* is it right to throw away teh flexes? 
+      (* is it right to throw away the flexes? 
          or should I be using them somehow? *)
           fun mk_insts (env,flexflexes) = 
               (Vartab.dest (Envir.type_env env),  Envir.alist_of env);
           val initenv = Envir.Envir {asol = Vartab.empty, 
                                      iTs = typinsttab, maxidx = ix2};
           val useq = (Unify.unifiers (sgn,initenv,[a]))
-              handle Library.LIST _ => Seq.empty
-                   | Term.TERM _ => Seq.empty;
+	      handle UnequalLengths => Seq.empty
+		   | Term.TERM _ => Seq.empty;
           fun clean_unify' useq () = 
               (case (Seq.pull useq) of 
                  NONE => NONE
                | SOME (h,t) => SOME (mk_insts h, Seq.make (clean_unify' t)))
-              handle Library.LIST _ => NONE
+	      handle UnequalLengths => NONE
                    | Term.TERM _ => NONE;
         in
           (Seq.make (clean_unify' useq))
@@ -325,7 +325,7 @@
 
 (* cunning version *)
 
-(* This version avoids name conflicts that might be intorduced by
+(* This version avoids name conflicts that might be introduced by
 unskolemisation, and returns a list of (string * Term.typ) * string,
 where the outer string is the original name, and the inner string is
 the new name, and the type is the type of the free variable that was
@@ -340,7 +340,7 @@
                         renamedn :: names)) end
         | (SOME ((renamedn, _), _)) => (renamedn, L)
       end
-      handle LIST _ => (n, L);
+      handle Fail _ => (n, L);
 
   fun unsk (L,f) (t1 $ t2) = 
       let val (L', t1') = unsk (L, I) t1 
@@ -365,7 +365,7 @@
               let (n,ty) = (Term.dest_Free fv) in 
                 SOME (fv, Free (Syntax.dest_skolem n, ty)) handle LIST _ => NONE
               end
-          val substfrees = mapfilter fmap (Term.term_frees t)
+          val substfrees = List.mapPartial fmap (Term.term_frees t)
         in
           Term.subst_free substfrees t
         end; *)
@@ -379,7 +379,7 @@
 
 (* get the frees in a term that are of atomic type, ie non-functions *)
 val atomic_frees_of_term =
-     filter (is_atomic_typ o snd) 
+     List.filter (is_atomic_typ o snd) 
      o map Term.dest_Free 
      o Term.term_frees;
 
@@ -408,8 +408,8 @@
     let 
       val lopt = (term_name_eq ah bh l)
     in
-      if is_some lopt then 
-	term_name_eq at bt (the lopt)
+      if isSome lopt then 
+	term_name_eq at bt (valOf lopt)
       else
         NONE
     end
@@ -438,12 +438,12 @@
  (* checks to see if the term in a name-equivalent member of the list of terms. *)
   fun get_name_eq_member a [] = NONE
     | get_name_eq_member a (h :: t) = 
-        if is_some (term_name_eq a h []) then SOME h 
+        if isSome (term_name_eq a h []) then SOME h 
 				else get_name_eq_member a t;
 
   fun name_eq_member a [] = false
     | name_eq_member a (h :: t) = 
-        if is_some (term_name_eq a h []) then true 
+        if isSome (term_name_eq a h []) then true 
 				else name_eq_member a t;
 
   (* true if term is a variable *)
@@ -485,7 +485,7 @@
   | term_contains1 T (ah $ at) (bh $ bt) =
     (term_contains1 T ah (bh $ bt)) @ 
     (term_contains1 T at (bh $ bt)) @
-    (flat (map (fn inT => (term_contains1 inT at bt)) 
+    (List.concat (map (fn inT => (term_contains1 inT at bt)) 
                (term_contains1 T ah bh)))
 
   | term_contains1 T a (bh $ bt) = []
@@ -662,7 +662,7 @@
     | SOME _ => nt)
   | bounds_to_frees_aux T (nt as (ntab, Bound i)) = 
     let 
-      val (s,ty) = Library.nth_elem (i,T) 
+      val (s,ty) = List.nth (T,i) 
     in
       (ntab, Free (s,ty))
     end;
@@ -683,7 +683,7 @@
     (loose_bnds_to_frees_aux (bnds,vars) a) 
       $ (loose_bnds_to_frees_aux (bnds,vars) b)
   | loose_bnds_to_frees_aux (bnds,vars) (t as (Bound i)) = 
-    if (bnds <= i) then Free (Library.nth_elem (i - bnds,vars))
+    if (bnds <= i) then Free (List.nth (vars,i - bnds))
     else t
   | loose_bnds_to_frees_aux (bnds,vars) t = t;
 
@@ -705,7 +705,7 @@
 
 fun thms_of_prems_in_goal i tm= 
     let 
-      val goal = (nth_elem (i-1,Thm.prems_of tm))
+      val goal = (List.nth (Thm.prems_of tm,i-1))
       val vars = rev (strip_all_vars goal)
       val prems = Logic.strip_assums_hyp (strip_all_body goal)
       val simp_prem_thms = 
--- a/src/Pure/Isar/args.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/Pure/Isar/args.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -149,7 +149,7 @@
 val int = Scan.optional ($$$ "-" >> K ~1) 1 -- nat >> op *;
 
 (*read variable name; leading '?' may be omitted if name contains no dot*)
-val var = kind (apsome #1 o (fn s =>
+val var = kind (Option.map #1 o (fn s =>
   SOME (Term.dest_Var (Syntax.read_var s))
     handle _ => SOME (Term.dest_Var (Syntax.read_var ("?" ^ s)))
     handle _ => NONE));
@@ -214,7 +214,7 @@
   ((Scan.repeat1
     (Scan.repeat1 (atom_arg blk) ||
       paren_args "(" ")" args ||
-      paren_args "[" "]" args)) >> flat) x;
+      paren_args "[" "]" args)) >> List.concat) x;
 
 
 
--- a/src/Pure/Isar/attrib.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/Pure/Isar/attrib.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -135,7 +135,7 @@
 
 val thm_sel = Args.parens (Scan.pass () (Args.enum1 "," (Scan.lift
   (   Args.nat --| Args.$$$ "-" -- Args.nat >> op upto
-   || Args.nat >> single)) >> flat));
+   || Args.nat >> single)) >> List.concat));
 
 fun gen_thm get attrib app =
   Scan.depend (fn st => Args.name -- Scan.option thm_sel -- Args.opt_attribs >>
@@ -143,11 +143,11 @@
 
 val global_thm = gen_thm PureThy.get_thm global_attribute Thm.apply_attributes;
 val global_thms = gen_thm PureThy.get_thms global_attribute Thm.applys_attributes;
-val global_thmss = Scan.repeat global_thms >> flat;
+val global_thmss = Scan.repeat global_thms >> List.concat;
 
 val local_thm = gen_thm ProofContext.get_thm local_attribute' Thm.apply_attributes;
 val local_thms = gen_thm ProofContext.get_thms local_attribute' Thm.applys_attributes;
-val local_thmss = Scan.repeat local_thms >> flat;
+val local_thmss = Scan.repeat local_thms >> List.concat;
 
 
 
@@ -218,7 +218,7 @@
                 "Type instantiations must occur before term instantiations."
               else ();
 
-        val Tinsts = filter has_type_var insts;
+        val Tinsts = List.filter has_type_var insts;
         val tinsts = filter_out has_type_var insts;
 
         (* Type instantiations first *)
--- a/src/Pure/Isar/calculation.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/Pure/Isar/calculation.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -178,7 +178,7 @@
       | SOME calc => (false, Seq.map single (combine (calc @ facts))));
   in
     err_if state (initial andalso final) "No calculation yet";
-    err_if state (initial andalso is_some opt_rules) "Initial calculation -- no rules to be given";
+    err_if state (initial andalso isSome opt_rules) "Initial calculation -- no rules to be given";
     calculations |> Seq.map (fn calc => (print (Proof.context_of state) calc;
         state |> maintain_calculation final calc))
   end;
--- a/src/Pure/Isar/constdefs.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/Pure/Isar/constdefs.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -40,12 +40,12 @@
 
     val ctxt =
       ProofContext.init thy |> ProofContext.add_fixes
-        (flat (map (fn (As, T) => map (fn A => (A, T, NONE)) As) structs));
+        (List.concat (map (fn (As, T) => map (fn A => (A, T, NONE)) As) structs));
     val (ctxt', d, mx) =
       (case decl of NONE => (ctxt, NONE, Syntax.NoSyn) | SOME (x, raw_T, mx) =>
         let
           val x' = Syntax.const_name x mx and mx' = Syntax.fix_mixfix x mx;
-          val T = apsome (prep_typ ctxt) raw_T;
+          val T = Option.map (prep_typ ctxt) raw_T;
         in (ProofContext.add_fixes_liberal [(x', T, SOME mx')] ctxt, SOME x', mx') end);
 
     val prop = prep_term ctxt' raw_prop;
--- a/src/Pure/Isar/context_rules.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/Pure/Isar/context_rules.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -112,8 +112,8 @@
 fun print_rules prt x (Rules {rules, ...}) =
   let
     fun prt_kind (i, b) =
-      Pretty.big_list (the (assoc (kind_names, (i, b))) ^ ":")
-        (mapfilter (fn (_, (k, th)) => if k = (i, b) then SOME (prt x th) else NONE)
+      Pretty.big_list (valOf (assoc (kind_names, (i, b))) ^ ":")
+        (List.mapPartial (fn (_, (k, th)) => if k = (i, b) then SOME (prt x th) else NONE)
           (sort (Int.compare o pairself fst) rules));
   in Pretty.writeln (Pretty.chunks (map prt_kind rule_kinds)) end;
 
@@ -136,7 +136,7 @@
       val rules = gen_merge_lists' (fn ((_, (k1, th1)), (_, (k2, th2))) =>
           k1 = k2 andalso Drule.eq_thm_prop (th1, th2)) rules1 rules2;
       val next = ~ (length rules);
-      val netpairs = foldl (fn (nps, (n, (w, ((i, b), th)))) =>
+      val netpairs = Library.foldl (fn (nps, (n, (w, ((i, b), th)))) =>
           map_nth_elem i (curry insert_tagged_brl ((w, n), (b, th))) nps)
         (empty_netpairs, next upto ~1 ~~ rules);
     in make_rules (next - 1) rules netpairs wrappers end;
@@ -203,7 +203,7 @@
 
 fun gen_wrap which ctxt =
   let val Rules {wrappers, ...} = LocalRules.get ctxt
-  in fn tac => foldr (fn ((w, _), t) => w t) (which wrappers, tac) end;
+  in fn tac => Library.foldr (fn ((w, _), t) => w t) (which wrappers, tac) end;
 
 val Swrap = gen_wrap #1;
 val wrap = gen_wrap #2;
--- a/src/Pure/Isar/induct_attrib.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/Pure/Isar/induct_attrib.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -66,10 +66,10 @@
 
 val vars_of = rev o rev_vars_of;
 
-fun first_var thm = mk_var (hd (vars_of (hd (Thm.prems_of thm)))) handle LIST _ =>
+fun first_var thm = mk_var (hd (vars_of (hd (Thm.prems_of thm)))) handle Empty =>
   raise THM ("No variables in first premise of rule", 0, [thm]);
 
-fun last_var thm = mk_var (hd (rev_vars_of (Thm.concl_of thm))) handle LIST _ =>
+fun last_var thm = mk_var (hd (rev_vars_of (Thm.concl_of thm))) handle Empty =>
   raise THM ("No variables in conclusion of rule", 0, [thm]);
 
 end;
--- a/src/Pure/Isar/isar_output.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/Pure/Isar/isar_output.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -66,7 +66,7 @@
   else warning ("Redefined antiquotation output " ^ kind ^ ": " ^ quote name);
   Symtab.update ((name, x), tab));
 
-fun add_items kind xs tab = foldl (add_item kind) (tab, xs);
+fun add_items kind xs tab = Library.foldl (add_item kind) (tab, xs);
 
 in
 
@@ -200,7 +200,7 @@
       T.is_kind T.Command tk andalso T.val_of tk mem !hidden_commands
   | is_hidden _ = false;
 
-fun filter_newlines toks = (case mapfilter
+fun filter_newlines toks = (case List.mapPartial
     (fn (tk, i) => if is_newline tk then SOME tk else NONE) toks of
   [] => [] | [tk] => [tk] | _ :: toks' => toks');
 
@@ -209,7 +209,7 @@
    ((if !hide_commands andalso exists (is_hidden o fst) toks then []
      else if !hide_commands andalso is_proof state then
        if is_proof state' then [] else filter_newlines toks
-     else mapfilter (fn (tk, i) =>
+     else List.mapPartial (fn (tk, i) =>
        if i > ! interest_level then NONE else SOME tk) toks)
     |> map (apsnd (eval_antiquote lex state'))
     |> Latex.output_tokens
--- a/src/Pure/Isar/isar_syn.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/Pure/Isar/isar_syn.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -214,7 +214,7 @@
 
 val declareP =
   OuterSyntax.command "declare" "declare theorems (improper)" K.thy_script
-    (P.locale_target -- (P.and_list1 P.xthms1 >> flat)
+    (P.locale_target -- (P.and_list1 P.xthms1 >> List.concat)
       >> (Toplevel.theory o uncurry IsarThy.declare_theorems));
 
 
--- a/src/Pure/Isar/isar_thy.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/Pure/Isar/isar_thy.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -247,8 +247,8 @@
 
 fun declare_theorems opt_loc args = #1 o smart_theorems "" opt_loc [(("", []), args)];
 
-fun apply_theorems args = apsnd (flat o map snd) o theorems "" [(("", []), args)];
-fun apply_theorems_i args = apsnd (flat o map snd) o theorems_i "" [(("", []), args)];
+fun apply_theorems args = apsnd (List.concat o map snd) o theorems "" [(("", []), args)];
+fun apply_theorems_i args = apsnd (List.concat o map snd) o theorems_i "" [(("", []), args)];
 
 end;
 
@@ -304,7 +304,7 @@
 local
 
 fun prt_facts ctxt =
-  flat o (separate [Pretty.fbrk, Pretty.str "and "]) o
+  List.concat o (separate [Pretty.fbrk, Pretty.str "and "]) o
     map (single o ProofContext.pretty_fact ctxt);
 
 fun pretty_results ctxt ((kind, ""), facts) =
@@ -503,7 +503,7 @@
 fun proof''' f = Toplevel.proof' (f o cond_print_calc);
 
 fun gen_calc get f args prt state =
-  f (apsome (fn srcs => get srcs state) args) prt state;
+  f (Option.map (fn srcs => get srcs state) args) prt state;
 
 in
 
--- a/src/Pure/Isar/locale.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/Pure/Isar/locale.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -194,7 +194,7 @@
     val sign = ProofContext.sign_of ctxt;
     fun prt_id (name, parms) =
       [Pretty.block (Pretty.breaks (map Pretty.str (cond_extern sign name :: parms)))];
-    val prt_ids = flat (separate [Pretty.str " +", Pretty.brk 1] (map prt_id ids));
+    val prt_ids = List.concat (separate [Pretty.str " +", Pretty.brk 1] (map prt_id ids));
     val err_msg =
       if forall (equal "" o #1) ids then msg
       else msg ^ "\n" ^ Pretty.string_of (Pretty.block
@@ -210,7 +210,7 @@
 
 (* renaming *)
 
-fun rename ren x = if_none (assoc_string (ren, x)) x;
+fun rename ren x = getOpt (assoc_string (ren, x), x);
 
 fun rename_term ren (Free (x, T)) = Free (rename ren x, T)
   | rename_term ren (t $ u) = rename_term ren t $ rename_term ren u
@@ -221,7 +221,7 @@
   let
     val {sign, hyps, prop, maxidx, ...} = Thm.rep_thm th;
     val cert = Thm.cterm_of sign;
-    val (xs, Ts) = Library.split_list (foldl Term.add_frees ([], prop :: hyps));
+    val (xs, Ts) = Library.split_list (Library.foldl Term.add_frees ([], prop :: hyps));
     val xs' = map (rename ren) xs;
     fun cert_frees names = map (cert o Free) (names ~~ Ts);
     fun cert_vars names = map (cert o Var o apfst (rpair (maxidx + 1))) (names ~~ Ts);
@@ -264,7 +264,7 @@
 (* type instantiation *)
 
 fun inst_type [] T = T
-  | inst_type env T = Term.map_type_tfree (fn v => if_none (assoc (env, v)) (TFree v)) T;
+  | inst_type env T = Term.map_type_tfree (fn v => getOpt (assoc (env, v), TFree v)) T;
 
 fun inst_term [] t = t
   | inst_term env t = Term.map_term_types (inst_type env) t;
@@ -276,8 +276,8 @@
         val cert = Thm.cterm_of sign;
         val certT = Thm.ctyp_of sign;
         val {hyps, prop, maxidx, ...} = Thm.rep_thm th;
-        val tfrees = foldr Term.add_term_tfree_names (prop :: hyps, []);
-        val env' = filter (fn ((a, _), _) => a mem_string tfrees) env;
+        val tfrees = Library.foldr Term.add_term_tfree_names (prop :: hyps, []);
+        val env' = List.filter (fn ((a, _), _) => a mem_string tfrees) env;
       in
         if null env' then th
         else
@@ -285,13 +285,13 @@
           |> Drule.implies_intr_list (map cert hyps)
           |> Drule.tvars_intr_list (map (#1 o #1) env')
           |> (fn (th', al) => th' |>
-            Thm.instantiate ((map (fn ((a, _), T) => (the (assoc (al, a)), certT T)) env'), []))
+            Thm.instantiate ((map (fn ((a, _), T) => (valOf (assoc (al, a)), certT T)) env'), []))
           |> (fn th'' => Drule.implies_elim_list th''
               (map (Thm.assume o cert o inst_term env') hyps))
       end;
 
 fun inst_elem _ env (Fixes fixes) =
-      Fixes (map (fn (x, T, mx) => (x, apsome (inst_type env) T, mx)) fixes)
+      Fixes (map (fn (x, T, mx) => (x, Option.map (inst_type env) T, mx)) fixes)
   | inst_elem _ env (Assumes asms) = Assumes (map (apsnd (map (fn (t, (ps, qs)) =>
       (inst_term env t, (map (inst_term env) ps, map (inst_term env) qs))))) asms)
   | inst_elem _ env (Defines defs) = Defines (map (apsnd (fn (t, ps) =>
@@ -310,7 +310,7 @@
 
 fun frozen_tvars ctxt Ts =
   let
-    val tvars = rev (foldl Term.add_tvarsT ([], Ts));
+    val tvars = rev (Library.foldl Term.add_tvarsT ([], Ts));
     val tfrees = map TFree
       (Term.invent_names (ProofContext.used_types ctxt) "'a" (length tvars) ~~ map #2 tvars);
   in map #1 tvars ~~ tfrees end;
@@ -328,17 +328,17 @@
           handle Type.TUNIFY =>
             raise TYPE ("unify_frozen: failed to unify types", [U, T], []))
       | unify (env, _) = env;
-    val (unifier, _) = foldl unify ((Vartab.empty, maxidx''), Ts' ~~ Us');
-    val Vs = map (apsome (Envir.norm_type unifier)) Us';
-    val unifier' = Vartab.extend (unifier, frozen_tvars ctxt (mapfilter I Vs));
-  in map (apsome (Envir.norm_type unifier')) Vs end;
+    val (unifier, _) = Library.foldl unify ((Vartab.empty, maxidx''), Ts' ~~ Us');
+    val Vs = map (Option.map (Envir.norm_type unifier)) Us';
+    val unifier' = Vartab.extend (unifier, frozen_tvars ctxt (List.mapPartial I Vs));
+  in map (Option.map (Envir.norm_type unifier')) Vs end;
 
-fun params_of elemss = gen_distinct eq_fst (flat (map (snd o fst) elemss));
-fun params_of' elemss = gen_distinct eq_fst (flat (map (snd o fst o fst) elemss));
+fun params_of elemss = gen_distinct eq_fst (List.concat (map (snd o fst) elemss));
+fun params_of' elemss = gen_distinct eq_fst (List.concat (map (snd o fst o fst) elemss));
 
 (* CB: param_types has the following type:
   ('a * 'b option) list -> ('a * 'b) list *)
-fun param_types ps = mapfilter (fn (_, NONE) => NONE | (x, SOME T) => SOME (x, T)) ps;
+fun param_types ps = List.mapPartial (fn (_, NONE) => NONE | (x, SOME T) => SOME (x, T)) ps;
 
 
 (* flatten expressions *)
@@ -353,7 +353,7 @@
 fun unique_parms ctxt elemss =
   let
     val param_decls =
-      flat (map (fn (((name, (ps, qs)), _), _) => map (rpair (name, ps)) qs) elemss)
+      List.concat (map (fn (((name, (ps, qs)), _), _) => map (rpair (name, ps)) qs) elemss)
       |> Symtab.make_multi |> Symtab.dest;
   in
     (case find_first (fn (_, ids) => length ids > 1) param_decls of
@@ -377,7 +377,7 @@
 
     fun varify i = Term.map_type_tfree (fn (a, S) => TVar ((a, i), S));
     fun varify_parms (i, ps) = map (apsnd (varify i)) (param_types ps);
-    val parms = fixed_parms @ flat (map varify_parms idx_parmss);
+    val parms = fixed_parms @ List.concat (map varify_parms idx_parmss);
 
     fun unify T ((env, maxidx), U) =
       Type.unify tsig (env, maxidx) (U, T)
@@ -386,17 +386,17 @@
         in raise TYPE ("unify_parms: failed to unify types " ^
           prt U ^ " and " ^ prt T, [U, T], [])
         end
-    fun unify_list (envir, T :: Us) = foldl (unify T) (envir, Us)
+    fun unify_list (envir, T :: Us) = Library.foldl (unify T) (envir, Us)
       | unify_list (envir, []) = envir;
-    val (unifier, _) = foldl unify_list
+    val (unifier, _) = Library.foldl unify_list
       ((Vartab.empty, maxidx), map #2 (Symtab.dest (Symtab.make_multi parms)));
 
     val parms' = map (apsnd (Envir.norm_type unifier)) (gen_distinct eq_fst parms);
     val unifier' = Vartab.extend (unifier, frozen_tvars ctxt (map #2 parms'));
 
     fun inst_parms (i, ps) =
-      foldr Term.add_typ_tfrees (mapfilter snd ps, [])
-      |> mapfilter (fn (a, S) =>
+      Library.foldr Term.add_typ_tfrees (List.mapPartial snd ps, [])
+      |> List.mapPartial (fn (a, S) =>
           let val T = Envir.norm_type unifier' (TVar ((a, i), S))
           in if T = TFree (a, S) then NONE else SOME ((a, S), T) end)
   in map inst_parms idx_parmss end;
@@ -411,7 +411,7 @@
       let
         val envs = unify_parms ctxt fixed_parms (map (#2 o #1 o #1) elemss);
         fun inst ((((name, ps), axs), elems), env) =
-          (((name, map (apsnd (apsome (inst_type env))) ps),  axs),
+          (((name, map (apsnd (Option.map (inst_type env))) ps),  axs),
            map (inst_elem ctxt env) elems);
       in map inst (elemss ~~ envs) end;
 
@@ -421,7 +421,7 @@
       let
         val envs = unify_parms ctxt fixed_parms (map (#2 o #1 o #1) elemss);
         fun inst ((((name, ps), axs), elems), env) =
-          (((name, map (apsnd (apsome (inst_type env))) ps), 
+          (((name, map (apsnd (Option.map (inst_type env))) ps), 
             map (inst_thm ctxt env) axs), map (inst_elem ctxt env) elems);
       in map inst (elemss ~~ envs) end;
 
@@ -459,8 +459,8 @@
             val ids_ax = if top then snd
                  (foldl_map (fn (axs, ((name, parms), _)) => let
                    val {elems, ...} = the_locale thy name;
-                   val ts = flat (mapfilter (fn (Assumes asms, _) =>
-                     SOME (flat (map (map #1 o #2) asms)) | _ => NONE) elems);
+                   val ts = List.concat (List.mapPartial (fn (Assumes asms, _) =>
+                     SOME (List.concat (map (map #1 o #2) asms)) | _ => NONE) elems);
                    val (axs1, axs2) = splitAt (length ts, axs);
                  in (axs2, ((name, parms), (ps, axs1))) end) (axioms, ids''))
                else ids'';
@@ -471,10 +471,10 @@
             val ren = renaming xs parms'
               handle ERROR_MESSAGE msg => err_in_locale' ctxt msg ids';
             val ids'' = gen_distinct eq_fst (map (rename_parms top ren) ids');
-            val parms'' = distinct (flat (map (#2 o #1) ids''));
+            val parms'' = distinct (List.concat (map (#2 o #1) ids''));
           in (ids'', parms'') end
       | identify top (Merge es) =
-          foldl (fn ((ids, parms), e) => let
+          Library.foldl (fn ((ids, parms), e) => let
                      val (ids', parms') = identify top e
                    in (gen_merge_lists eq_fst ids ids',
                        merge_lists parms parms') end)
@@ -508,7 +508,7 @@
          elemss;
     fun inst_ax th = let
          val {hyps, prop, ...} = Thm.rep_thm th;
-         val ps = map (apsnd SOME) (foldl Term.add_frees ([], prop :: hyps));
+         val ps = map (apsnd SOME) (Library.foldl Term.add_frees ([], prop :: hyps));
          val [env] = unify_parms ctxt all_params [ps];
          val th' = inst_thm ctxt env th;
        in th' end;
@@ -534,7 +534,7 @@
       ((ctxt |> ProofContext.add_fixes fixes, axs), [])
   | activate_elem _ ((ctxt, axs), Assumes asms) =
       let
-        val ts = flat (map (map #1 o #2) asms);
+        val ts = List.concat (map (map #1 o #2) asms);
         val (ps,qs) = splitAt (length ts, axs);
         val (ctxt', _) =
           ctxt |> ProofContext.fix_frees ts
@@ -560,7 +560,7 @@
 fun activate_elemss prep_facts = foldl_map (fn (ctxt, (((name, ps), axs), raw_elems)) =>
   let
     val elems = map (prep_facts ctxt) raw_elems;
-    val (ctxt', res) = apsnd flat (activate_elems (((name, ps), axs), elems) ctxt);
+    val (ctxt', res) = apsnd List.concat (activate_elems (((name, ps), axs), elems) ctxt);
   in (ctxt', (((name, ps), elems), res)) end);
 
 in
@@ -577,7 +577,7 @@
    the internal/external markers from elemss. *)
 
 fun activate_facts prep_facts arg =
-  apsnd (apsnd flat o Library.split_list) (activate_elemss prep_facts arg);
+  apsnd (apsnd List.concat o Library.split_list) (activate_elemss prep_facts arg);
 
 end;
 
@@ -670,7 +670,7 @@
 
 fun declare_int_elem (ctxt, Fixes fixes) =
       (ctxt |> ProofContext.add_fixes (map (fn (x, T, mx) =>
-        (x, apsome (Term.map_type_tfree (TypeInfer.param 0)) T, mx)) fixes), [])
+        (x, Option.map (Term.map_type_tfree (TypeInfer.param 0)) T, mx)) fixes), [])
   | declare_int_elem (ctxt, _) = (ctxt, []);
 
 fun declare_ext_elem prep_fixes (ctxt, Fixes fixes) =
@@ -700,7 +700,7 @@
       ProofContext.declare_terms (map Free fixed_params) ctxt;
     val int_elemss =
       raw_elemss
-      |> mapfilter (fn (id, Int es) => SOME (id, es) | _ => NONE)
+      |> List.mapPartial (fn (id, Int es) => SOME (id, es) | _ => NONE)
       |> unify_elemss ctxt_with_fixed fixed_params;
     val (_, raw_elemss') =
       foldl_map (fn ((_, es) :: elemss, (id, Int _)) => (elemss, (id, Int es)) | x => x)
@@ -747,14 +747,14 @@
 fun eval_text _ _ _ (text, Fixes _) = text
   | eval_text _ _ is_ext ((((exts, exts'), (ints, ints')), (xs, env, defs)), Assumes asms) =
       let
-        val ts = flat (map (map #1 o #2) asms);
+        val ts = List.concat (map (map #1 o #2) asms);
         val ts' = map (norm_term env) ts;
         val spec' =
           if is_ext then ((exts @ ts, exts' @ ts'), (ints, ints'))
           else ((exts, exts'), (ints @ ts, ints' @ ts'));
-      in (spec', (foldl Term.add_frees (xs, ts'), env, defs)) end
+      in (spec', (Library.foldl Term.add_frees (xs, ts'), env, defs)) end
   | eval_text ctxt (id, _) _ ((spec, binds), Defines defs) =
-      (spec, foldl (bind_def ctxt id) (binds, map (#1 o #2) defs))
+      (spec, Library.foldl (bind_def ctxt id) (binds, map (#1 o #2) defs))
   | eval_text _ _ _ (text, Notes _) = text;
 
 (* CB: for finish_elems (Ext) *)
@@ -798,7 +798,7 @@
 fun finish_elems ctxt parms _ (text, ((id, Int e), _)) =
       let
         val [(id', es)] = unify_elemss ctxt parms [(id, e)];
-        val text' = foldl (eval_text ctxt id' false) (text, es);
+        val text' = Library.foldl (eval_text ctxt id' false) (text, es);
       in (text', (id', map Int es)) end
   | finish_elems ctxt parms do_close (text, ((id, Ext e), [propp])) =
       let
@@ -830,8 +830,8 @@
        the fixes elements in raw_elemss,
        raw_proppss contains assumptions and definitions from the
        external elements in raw_elemss. *)
-    val raw_propps = map flat raw_proppss;
-    val raw_propp = flat raw_propps;
+    val raw_propps = map List.concat raw_proppss;
+    val raw_propp = List.concat raw_propps;
 
     (* CB: add type information from fixed_params to context (declare_terms) *)
     (* CB: process patterns (conclusion and external elements only) *)
@@ -840,7 +840,7 @@
     
     (* CB: add type information from conclusion and external elements
        to context *)
-    val ctxt = ProofContext.declare_terms (flat (map (map fst) all_propp)) ctxt;
+    val ctxt = ProofContext.declare_terms (List.concat (map (map fst) all_propp)) ctxt;
 
     (* CB: resolve schematic variables (patterns) in conclusion and external
        elements. *)
@@ -929,7 +929,7 @@
 
     val (import_ids, raw_import_elemss) = flatten (context, prep_expr sign) ([], Expr import);
     (* CB: normalise "includes" among elements *)
-    val raw_elemss = flat (#2 ((foldl_map (flatten (context, prep_expr sign))
+    val raw_elemss = List.concat (#2 ((foldl_map (flatten (context, prep_expr sign))
       (import_ids, elements))));
     (* CB: raw_import_elemss @ raw_elemss is the normalised list of
        context elements obtained from import and elements. *)
@@ -943,8 +943,8 @@
     val (ctxt, (elemss, _)) =
       activate_facts prep_facts (import_ctxt, qs);
     val stmt = gen_distinct Term.aconv
-       (flat (map (fn ((_, axs), _) =>
-         flat (map (#hyps o Thm.rep_thm) axs)) qs));
+       (List.concat (map (fn ((_, axs), _) =>
+         List.concat (map (#hyps o Thm.rep_thm) axs)) qs));
     val cstmt = map (cterm_of sign) stmt;
   in
     ((((import_ctxt, import_elemss), (ctxt, elemss)), (parms, spec, defs)), (cstmt, concl))
@@ -956,7 +956,7 @@
 fun gen_statement prep_locale prep_ctxt raw_locale elems concl ctxt =
   let
     val thy = ProofContext.theory_of ctxt;
-    val locale = apsome (prep_locale (Theory.sign_of thy)) raw_locale;
+    val locale = Option.map (prep_locale (Theory.sign_of thy)) raw_locale;
     val (target_stmt, fixed_params, import) =
       (case locale of NONE => ([], [], empty)
       | SOME name =>
@@ -1036,7 +1036,7 @@
     (* process parameters: match their types with those of arguments *)
 
     val def_names = map (fn (Free (s, _), _) => s) env;
-    val (defined, assumed) = partition
+    val (defined, assumed) = List.partition
           (fn (s, _) => s mem def_names) fixed_params;
     val cassumed = map (cert o Free) assumed;
     val cdefined = map (cert o Free) defined;
@@ -1044,21 +1044,21 @@
     val param_types = map snd assumed;
     val v_param_types = map Type.varifyT param_types;
     val arg_types = map Term.fastype_of args;
-    val Tenv = foldl (Type.typ_match tsig)
+    val Tenv = Library.foldl (Type.typ_match tsig)
           (Vartab.empty, v_param_types ~~ arg_types)
-          handle Library.LIST "~~" => error "Number of parameters does not \
+          handle UnequalLengths => error "Number of parameters does not \
             \match number of arguments of chained fact";
     (* get their sorts *)
-    val tfrees = foldr Term.add_typ_tfrees (param_types, []);
+    val tfrees = Library.foldr Term.add_typ_tfrees (param_types, []);
     val Tenv' = map
-          (fn ((a, i), T) => ((a, the (assoc_string (tfrees, a))), T))
+          (fn ((a, i), T) => ((a, valOf (assoc_string (tfrees, a))), T))
           (Vartab.dest Tenv);
 
     (* process (internal) elements *)
 
     fun inst_type [] T = T
       | inst_type env T =
-          Term.map_type_tfree (fn v => if_none (assoc (env, v)) (TFree v)) T;
+          Term.map_type_tfree (fn v => getOpt (assoc (env, v), TFree v)) T;
 
     fun inst_term [] t = t
       | inst_term env t = Term.map_term_types (inst_type env) t;
@@ -1076,8 +1076,8 @@
 	    val cert = Thm.cterm_of sign;
 	    val certT = Thm.ctyp_of sign;
 	    val {hyps, prop, maxidx, ...} = Thm.rep_thm th;
-	    val tfrees = foldr Term.add_term_tfree_names (prop :: hyps, []);
-	    val Tenv' = filter (fn ((a, _), _) => a mem_string tfrees) Tenv;
+	    val tfrees = Library.foldr Term.add_term_tfree_names (prop :: hyps, []);
+	    val Tenv' = List.filter (fn ((a, _), _) => a mem_string tfrees) Tenv;
 	  in
 	    if null Tenv' then th
 	    else
@@ -1086,7 +1086,7 @@
 	      |> Drule.tvars_intr_list (map (#1 o #1) Tenv')
 	      |> (fn (th', al) => th' |>
 		Thm.instantiate ((map (fn ((a, _), T) =>
-                  (the (assoc (al, a)), certT T)) Tenv'), []))
+                  (valOf (assoc (al, a)), certT T)) Tenv'), []))
 	      |> (fn th'' => Drule.implies_elim_list th''
 		  (map (Thm.assume o cert o inst_term Tenv') hyps))
 	  end;
@@ -1096,7 +1096,7 @@
         (* not all axs are normally applicable *)
         val hyps = #hyps (rep_thm thm);
         val ass = map (fn ax => (prop_of ax, ax)) axioms;
-        val axs' = foldl (fn (axs, hyp) => 
+        val axs' = Library.foldl (fn (axs, hyp) => 
               (case gen_assoc (op aconv) (ass, hyp) of NONE => axs
                  | SOME ax => axs @ [ax])) ([], hyps);
         val thm' = Drule.satisfy_hyps axs' thm;
@@ -1142,9 +1142,9 @@
           end
       | inst_elem (ctxt, (Int _)) = ctxt;
 
-    fun inst_elems (ctxt, (id, elems)) = foldl inst_elem (ctxt, elems);
+    fun inst_elems (ctxt, (id, elems)) = Library.foldl inst_elem (ctxt, elems);
 
-    fun inst_elemss ctxt elemss = foldl inst_elems (ctxt, elemss);
+    fun inst_elemss ctxt elemss = Library.foldl inst_elems (ctxt, elemss);
 
     (* main part *)
 
@@ -1161,7 +1161,7 @@
   let
     val thy_ctxt = ProofContext.init thy;
     val (((_, import_elemss), (ctxt, elemss)), _) = read_context import body thy_ctxt;
-    val all_elems = flat (map #2 (import_elemss @ elemss));
+    val all_elems = List.concat (map #2 (import_elemss @ elemss));
 
     val prt_typ = Pretty.quote o ProofContext.pretty_typ ctxt;
     val prt_term = Pretty.quote o ProofContext.pretty_term ctxt;
@@ -1179,7 +1179,7 @@
     fun prt_asm ((a, _), ts) = Pretty.block (prt_name a @ Pretty.breaks (map (prt_term o fst) ts));
     fun prt_def ((a, _), (t, _)) = Pretty.block (prt_name a @ [prt_term t]);
     fun prt_fact ((a, _), ths) = Pretty.block
-      (prt_name a @ Pretty.breaks (map prt_thm (flat (map fst ths))));
+      (prt_name a @ Pretty.breaks (map prt_thm (List.concat (map fst ths))));
 
     fun items _ [] = []
       | items prfx (x :: xs) = Pretty.block [Pretty.str prfx, Pretty.brk 1, x] :: items "  and" xs;
@@ -1306,9 +1306,9 @@
 
     val (body, bodyT, body_eq) = atomize_spec sign norm_ts;
     val env = Term.add_term_free_names (body, []);
-    val xs = filter (fn (x, _) => x mem_string env) parms;
+    val xs = List.filter (fn (x, _) => x mem_string env) parms;
     val Ts = map #2 xs;
-    val extraTs = (Term.term_tfrees body \\ foldr Term.add_typ_tfrees (Ts, []))
+    val extraTs = (Term.term_tfrees body \\ Library.foldr Term.add_typ_tfrees (Ts, []))
       |> Library.sort_wrt #1 |> map TFree;
     val predT = map Term.itselfT extraTs ---> Ts ---> bodyT;
 
@@ -1408,7 +1408,7 @@
   let
     val sign = Theory.sign_of thy;
     val name = Sign.full_name sign bname;
-    val _ = conditional (is_some (get_locale thy name)) (fn () =>
+    val _ = conditional (isSome (get_locale thy name)) (fn () =>
       error ("Duplicate definition of locale " ^ quote name));
 
     val thy_ctxt = ProofContext.init thy;
@@ -1423,8 +1423,8 @@
 
     fun axiomify axioms elemss = 
       (axioms, elemss) |> foldl_map (fn (axs, (id, elems)) => let
-                   val ts = flat (mapfilter (fn (Assumes asms) =>
-                     SOME (flat (map (map #1 o #2) asms)) | _ => NONE) elems);
+                   val ts = List.concat (List.mapPartial (fn (Assumes asms) =>
+                     SOME (List.concat (map (map #1 o #2) asms)) | _ => NONE) elems);
                    val (axs1, axs2) = splitAt (length ts, axs);
                  in (axs2, ((id, axs1), elems)) end)
         |> snd;
@@ -1437,7 +1437,7 @@
     |> note_thmss_qualified "" name facts' |> #1
     |> declare_locale name
     |> put_locale name {predicate = predicate, import = prep_expr sign raw_import,
-        elems = map (fn e => (e, stamp ())) (flat (map #2 (filter (equal "" o #1 o #1) elemss'))),
+        elems = map (fn e => (e, stamp ())) (List.concat (map #2 (List.filter (equal "" o #1 o #1) elemss'))),
         params = (params_of elemss', map #1 (params_of body_elemss))}
   end;
 
--- a/src/Pure/Isar/method.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/Pure/Isar/method.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -152,7 +152,7 @@
 (* shuffle *)
 
 fun prefer i = METHOD (K (Tactic.defer_tac i THEN PRIMITIVE (Thm.permute_prems 0 ~1)));
-fun defer opt_i = METHOD (K (Tactic.defer_tac (if_none opt_i 1)));
+fun defer opt_i = METHOD (K (Tactic.defer_tac (getOpt (opt_i,1))));
 
 
 (* insert *)
@@ -261,7 +261,7 @@
 in
 
 fun rules_tac ctxt opt_lim =
-  SELECT_GOAL (DEEPEN (2, if_none opt_lim 20) (intpr_tac ctxt [] 0) 4 1);
+  SELECT_GOAL (DEEPEN (2, getOpt (opt_lim,20)) (intpr_tac ctxt [] 0) 4 1);
 
 end;
 
@@ -281,7 +281,7 @@
   let
     val rules =
       if not (null arg_rules) then arg_rules
-      else flat (ContextRules.find_rules false facts goal ctxt)
+      else List.concat (ContextRules.find_rules false facts goal ctxt)
   in trace ctxt rules; tac rules facts i end);
 
 fun meth tac x = METHOD (HEADGOAL o tac x);
@@ -309,7 +309,7 @@
 (* assumption *)
 
 fun asm_tac ths =
-  foldr (op APPEND') (map (fn th => Tactic.rtac th THEN_ALL_NEW assume_tac) ths, K no_tac);
+  Library.foldr (op APPEND') (map (fn th => Tactic.rtac th THEN_ALL_NEW assume_tac) ths, K no_tac);
 
 fun assm_tac ctxt =
   assume_tac APPEND'
@@ -334,7 +334,7 @@
     (* Separate type and term insts *)
     fun has_type_var ((x, _), _) = (case Symbol.explode x of
           "'"::cs => true | cs => false);
-    val Tinsts = filter has_type_var insts;
+    val Tinsts = List.filter has_type_var insts;
     val tinsts = filter_out has_type_var insts;
     (* Tactic *)
     fun tac i st =
@@ -373,7 +373,7 @@
                 NONE => types (a, ~1)
               | some => some)
           | types' xi = types xi;
-        fun internal x = is_some (types' (x, ~1));
+        fun internal x = isSome (types' (x, ~1));
         val used = Term.add_term_tvarnames (Thm.prop_of st $ Thm.prop_of thm, []);
         val (ts, envT) =
           ProofContext.read_termTs_schematic ctxt internal types' sorts used (ss ~~ Ts);
@@ -596,7 +596,7 @@
 
 fun sect ss = Scan.first (map Scan.lift ss);
 fun thms ss = Scan.unless (sect ss) Attrib.local_thms;
-fun thmss ss = Scan.repeat (thms ss) >> flat;
+fun thmss ss = Scan.repeat (thms ss) >> List.concat;
 
 fun apply (f, att) (ctxt, ths) = Thm.applys_attributes ((f ctxt, ths), [att]);
 
@@ -732,7 +732,7 @@
 fun proof opt_text state =
   state
   |> Proof.assert_backward
-  |> refine (if_none opt_text default_text)
+  |> refine (getOpt (opt_text,default_text))
   |> Seq.map (Proof.goal_facts (K []))
   |> Seq.map Proof.enter_forward;
 
--- a/src/Pure/Isar/net_rules.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/Pure/Isar/net_rules.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -51,7 +51,7 @@
 
 fun merge (Rules {eq, index, rules = rules1, ...}, Rules {rules = rules2, ...}) =
   let val rules = Library.gen_merge_lists' eq rules1 rules2
-  in foldr (uncurry add) (rules, init eq index) end;
+  in Library.foldr (uncurry add) (rules, init eq index) end;
 
 fun delete rule (rs as Rules {eq, index, rules, next, net}) =
   if not (Library.gen_mem eq (rule, rules)) then rs
--- a/src/Pure/Isar/object_logic.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/Pure/Isar/object_logic.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -48,7 +48,7 @@
 
   fun merge_judgment (SOME x, SOME y) =
         if x = y then SOME x else error "Attempt to merge different object-logics"
-    | merge_judgment (j1, j2) = if is_some j1 then j1 else j2;
+    | merge_judgment (j1, j2) = if isSome j1 then j1 else j2;
 
   fun merge ((judgment1, (atomize1, rulify1)), (judgment2, (atomize2, rulify2))) =
     (merge_judgment (judgment1, judgment2),
@@ -116,7 +116,7 @@
     val c = judgment_name sg;
     val aT = TFree ("'a", []);
     val T =
-      if_none (Sign.const_type sg c) (aT --> propT)
+      getOpt (Sign.const_type sg c, aT --> propT)
       |> Term.map_type_tvar (fn ((x, _), S) => TFree (x, S));
     val U = Term.domain_type T handle Match => aT;
   in Const (c, T) $ Free (x, U) end;
--- a/src/Pure/Isar/obtain.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/Pure/Isar/obtain.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -72,12 +72,12 @@
 
     (*obtain vars*)
     val (vars_ctxt, vars) = foldl_map prep_vars (Proof.context_of state, raw_vars);
-    val xs = flat (map fst vars);
+    val xs = List.concat (map fst vars);
     val fix_ctxt = vars_ctxt |> ProofContext.fix_i vars;
 
     (*obtain asms*)
     val (asms_ctxt, proppss) = prep_propp (fix_ctxt, map snd raw_asms);
-    val asm_props = flat (map (map fst) proppss);
+    val asm_props = List.concat (map (map fst) proppss);
     val asms = map fst raw_asms ~~ proppss;
 
     val _ = ProofContext.warn_extra_tfrees fix_ctxt asms_ctxt;
@@ -95,9 +95,9 @@
     fun occs_var x = Library.get_first (fn t =>
       ProofContext.find_free t (ProofContext.get_skolem fix_ctxt x)) asm_props;
     val raw_parms = map occs_var xs;
-    val parms = mapfilter I raw_parms;
+    val parms = List.mapPartial I raw_parms;
     val parm_names =
-      mapfilter (fn (SOME (Free a), x) => SOME (a, x) | _ => NONE) (raw_parms ~~ xs);
+      List.mapPartial (fn (SOME (Free a), x) => SOME (a, x) | _ => NONE) (raw_parms ~~ xs);
 
     val that_prop =
       Term.list_all_free (map #1 parm_names, Logic.list_implies (asm_props, bound_thesis))
--- a/src/Pure/Isar/outer_parse.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/Pure/Isar/outer_parse.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -278,7 +278,7 @@
   ((Scan.repeat1
     (Scan.repeat1 (atom_arg is_symid blk) ||
       paren_args "(" ")" (args is_symid) ||
-      paren_args "[" "]" (args is_symid))) >> flat) x;
+      paren_args "[" "]" (args is_symid))) >> List.concat) x;
 
 val arguments = args T.is_sid false;
 
@@ -298,7 +298,7 @@
 
 val thm_sel = $$$ "(" |-- list1
   (   nat --| minus -- nat >> op upto
-   || nat >> single) --| $$$ ")" >> flat;
+   || nat >> single) --| $$$ ")" >> List.concat;
 
 val xthm = xname -- Scan.option thm_sel -- opt_attribs;
 val xthms1 = Scan.repeat1 xthm;
--- a/src/Pure/Isar/outer_syntax.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/Pure/Isar/outer_syntax.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -183,7 +183,7 @@
 
 fun get_lexicons () = ! global_lexicons;
 fun get_parsers () = ! global_parsers;
-fun get_parser () = apsome (#2 o #1) o curry Symtab.lookup (! global_parsers);
+fun get_parser () = Option.map (#2 o #1) o curry Symtab.lookup (! global_parsers);
 
 fun is_markup kind name =
   (case assoc (! global_markups, name) of SOME k => k = kind | NONE => false);
@@ -201,7 +201,7 @@
   Symtab.update ((name, (((comment, kind), (int_only, parse)), markup)), tab));
 
 fun add_parsers parsers =
-  (change_parsers (fn tab => foldl add_parser (tab, parsers));
+  (change_parsers (fn tab => Library.foldl add_parser (tab, parsers));
     change_lexicons (apsnd (fn lex => Scan.extend_lexicon lex
       (map (fn Parser (name, _, _, _) => Symbol.explode name) parsers))));
 
@@ -221,7 +221,7 @@
   let
     fun pretty_cmd (name, comment, _, _) =
       Pretty.block [Pretty.str (name ^ ":"), Pretty.brk 2, Pretty.str comment];
-    val (int_cmds, cmds) = partition #4 (dest_parsers ());
+    val (int_cmds, cmds) = List.partition #4 (dest_parsers ());
   in
     [Pretty.strs ("syntax keywords:" :: map quote (dest_keywords ())),
       Pretty.big_list "proper commands:" (map pretty_cmd cmds),
@@ -277,7 +277,7 @@
   Source.of_list toks
   |> toplevel_source false true true get_parser
   |> Source.exhaust
-  |> map (fn tr => (Toplevel.name_of tr, the (Toplevel.source_of tr), tr));
+  |> map (fn tr => (Toplevel.name_of tr, valOf (Toplevel.source_of tr), tr));
 
 
 (** read theory **)
@@ -296,7 +296,7 @@
     val pos = Path.position path;
     val (name', parents, files) = ThyHeader.scan (src, pos);
     val ml_path = ThyLoad.ml_path name;
-    val ml_file = if ml andalso is_some (ThyLoad.check_file NONE ml_path) then [ml_path] else [];
+    val ml_file = if ml andalso isSome (ThyLoad.check_file NONE ml_path) then [ml_path] else [];
   in
     if name <> name' then
       error ("Filename " ^ quote (Path.pack path) ^
--- a/src/Pure/Isar/proof.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/Pure/Isar/proof.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -269,7 +269,7 @@
 val reset_facts = put_facts NONE;
 
 fun these_factss (state, named_factss) =
-  state |> put_facts (SOME (flat (map snd named_factss)));
+  state |> put_facts (SOME (List.concat (map snd named_factss)));
 
 
 (* goal *)
@@ -414,7 +414,7 @@
 
     fun prt_names names =
       (case filter_out (equal "") names of [] => ""
-      | nms => " " ^ enclose "(" ")" (space_implode " and " (take (7, nms) @
+      | nms => " " ^ enclose "(" ")" (space_implode " and " (Library.take (7, nms) @
           (if length nms > 7 then ["..."] else []))));
 
     fun prt_goal (_, (i, (((kind, names, _), (goal_facts, thm)), _))) =
@@ -546,7 +546,7 @@
 
     val {hyps, sign, ...} = Thm.rep_thm raw_th;
     val tsig = Sign.tsig_of sign;
-    val casms = flat (map #1 (ProofContext.assumptions_of (context_of state)));
+    val casms = List.concat (map #1 (ProofContext.assumptions_of (context_of state)));
     val bad_hyps = Library.gen_rems Term.aconv (hyps, map Thm.term_of casms);
 
     val th = raw_th RS Drule.rev_triv_goal;
@@ -626,7 +626,7 @@
   |> map_context_result (f (map (pair ("", [])) args))
   |> (fn (st, named_facts) =>
     let val (_, (_, ((result, (facts, thm)), x))) = find_goal st;
-    in st |> map_goal I (K ((result, (facts @ flat (map snd named_facts), thm)), x)) end);
+    in st |> map_goal I (K ((result, (facts @ List.concat (map snd named_facts), thm)), x)) end);
 
 in
 
@@ -754,12 +754,12 @@
       |> map_context_result (fn ctxt => prepp (ctxt, raw_propp));
     val sign' = sign_of state';
 
-    val props = flat propss;
+    val props = List.concat propss;
     val cprop = Thm.cterm_of sign' (Logic.mk_conjunction_list props);
     val goal = Drule.mk_triv_goal cprop;
 
-    val tvars = foldr Term.add_term_tvars (props, []);
-    val vars = foldr Term.add_term_vars (props, []);
+    val tvars = Library.foldr Term.add_term_tvars (props, []);
+    val vars = Library.foldr Term.add_term_vars (props, []);
   in
     if null tvars then ()
     else raise STATE ("Goal statement contains illegal schematic type variable(s): " ^
@@ -786,7 +786,7 @@
   let
     val init = init_state thy;
     val (opt_name, view, locale_ctxt, elems_ctxt, propp) =
-      prep (apsome fst raw_locale) elems (map snd concl) (context_of init);
+      prep (Option.map fst raw_locale) elems (map snd concl) (context_of init);
   in
     init
     |> open_block
@@ -798,7 +798,7 @@
     |> setup_goal I ProofContext.bind_propp_schematic_i ProofContext.fix_frees
       (Theorem {kind = kind,
         theory_spec = (a, map (snd o fst) concl),
-        locale_spec = (case raw_locale of NONE => NONE | SOME (_, x) => SOME (the opt_name, x)),
+        locale_spec = (case raw_locale of NONE => NONE | SOME (_, x) => SOME (valOf opt_name, x)),
         view = view})
       Seq.single true (map (fst o fst) concl) propp
   end;
@@ -863,7 +863,7 @@
     val outer_state = state |> close_block;
     val outer_ctxt = context_of outer_state;
 
-    val ts = flat tss;
+    val ts = List.concat tss;
     val results = prep_result state ts raw_thm;
     val resultq =
       results |> map (ProofContext.export false goal_ctxt outer_ctxt)
@@ -903,7 +903,7 @@
     val {kind = k, theory_spec = ((name, atts), attss), locale_spec, view = (target_view, elems_view)} =
       (case kind of Theorem x => x | _ => err_malformed "finish_global" state);
 
-    val ts = flat tss;
+    val ts = List.concat tss;
     val locale_results = map (ProofContext.export_standard elems_view goal_ctxt locale_ctxt)
       (prep_result state ts raw_thm);
 
@@ -920,12 +920,12 @@
           |> (fn ((thy', ctxt'), res) =>
             if name = "" andalso null loc_atts then thy'
             else (thy', ctxt')
-              |> (#1 o #1 o Locale.add_thmss loc [((name, flat (map #2 res)), loc_atts)])))
+              |> (#1 o #1 o Locale.add_thmss loc [((name, List.concat (map #2 res)), loc_atts)])))
       |> Locale.smart_note_thmss k locale_spec
         ((names ~~ attss) ~~ map (single o Thm.no_attributes) (Library.unflat tss results))
       |> (fn (thy, res) => (thy, res)
           |>> (#1 o Locale.smart_note_thmss k locale_spec
-            [((name, atts), [(flat (map #2 res), [])])]));
+            [((name, atts), [(List.concat (map #2 res), [])])]));
   in (theory', ((k, name), results')) end;
 
 
--- a/src/Pure/Isar/proof_context.ML	Thu Mar 03 09:22:35 2005 +0100
+++ b/src/Pure/Isar/proof_context.ML	Thu Mar 03 12:43:01 2005 +0100
@@ -221,11 +221,11 @@
 val fixed_names_of = map #2 o fixes_of;
 fun is_fixed ctxt x = exists (equal x o #2) (fixes_of ctxt);
 fun is_known (ctxt as Context {defs = (types, _, _, _), ...}) x =
-  is_some (Vartab.lookup (types, (x, ~1))) orelse is_fixed ctxt x;
+  isSome (Vartab.lookup (types, (x, ~1))) orelse is_fixed ctxt x;
 fun type_occs (Context {defs = (_, _, _, tab), ...}) = tab;
 
 fun assumptions_of (Context {asms = ((asms, _), _), ...}) = asms;
-fun prems_of (Context {asms = ((_, prems), _), ...}) = flat (map #2 prems);
+fun prems_of (Context {asms = ((_, prems), _), ...}) = List.concat (map #2 prems);
 
 
 
@@ -398,9 +398,9 @@
   map_context (fn (thy, (syn, structs, mixfixed), data, asms, binds, thms, cases, defs, delta, delta_count) =>
     let
       val is_logtype = Sign.is_logtype (Theory.sign_of thy);
-      val structs' = structs @ mapfilter prep_struct decls;
-      val mxs = mapfilter prep_mixfix decls;
-      val (fixed, mxs_output) = Library.split_list (mapfilter prep_mixfix' decls);
+      val structs' = structs @ List.mapPartial prep_struct decls;
+      val mxs = List.mapPartial prep_mixfix decls;
+      val (fixed, mxs_output) = Library.split_list (List.mapPartial prep_mixfix' decls);
       val trs = map fixed_tr fixed;
       val syn' = syn
         |> Syntax.extend_const_gram is_logtype ("", false) mxs_output
@@ -489,7 +489,7 @@
 (* internalize Skolem constants *)
 
 fun lookup_skolem ctxt x = assoc (fixes_of ctxt, x);
-fun get_skolem ctxt x = if_none (lookup_skolem ctxt x) x;
+fun get_skolem ctxt x = getOpt (lookup_skolem ctxt x, x);
 
 fun no_skolem internal ctxt x =
   if can Syntax.dest_skolem x then
@@ -697,7 +697,7 @@
 val ins_occs = foldl_term_types (fn t => foldl_atyps
   (fn (tab, TFree (x, _)) => Symtab.update_multi ((x, t), tab) | (tab, _) => tab));
 
-fun ins_skolem def_ty = foldr
+fun ins_skolem def_ty = Library.foldr
   (fn ((x, x'), types) =>
     (case def_ty x' of
       SOME T => Vartab.update (((x, ~1), T), types)
@@ -721,8 +721,8 @@
 in
 
 fun declare_term t ctxt = declare_occ (ctxt, t);
-fun declare_terms ts ctxt = foldl declare_occ (ctxt, ts);
-fun declare_terms_syntax ts ctxt = foldl declare_syn (ctxt, ts);
+fun declare_terms ts ctxt = Library.foldl declare_occ (ctxt, ts);
+fun declare_terms_syntax ts ctxt = Library.foldl declare_syn (ctxt, ts);
 
 end;
 
@@ -742,8 +742,8 @@
 
     val extras =
       Library.gen_rems Library.eq_fst (Symtab.dest occ2, Symtab.dest occ1)
-      |> map (fn (a, ts) => map (pair a) (mapfilter (try (#1 o Term.dest_Free)) ts)) |> flat
-      |> mapfilter (fn (a, x) =>
+      |> map (fn (a, ts) => map (pair a) (List.mapPartial (try (#1 o Term.dest_Free)) ts)) |> List.concat
+      |> List.mapPartial (fn (a, x) =>
           (case def_type ctxt1 false (x, ~1) of NONE => SOME (a, x)
           | SOME T => if known_tfree a T then NONE else SOME (a, x)));
     val tfrees = map #1 extras |> Library.sort_strings |> Library.unique_strings;
@@ -766,14 +766,14 @@
     val occs_inner = type_occs inner;
     val occs_outer = type_occs outer;
     fun add (gen, a) =
-      if is_some (Symtab.lookup (occs_outer, a)) orelse
+      if isSome (Symtab.lookup (occs_outer, a)) orelse
         exists still_fixed (Symtab.lookup_multi (occs_inner, a))
       then gen else a :: gen;
-  in fn tfrees => foldl add ([], tfrees) end;
+  in fn tfrees => Library.foldl add ([], tfrees) end;
 
 fun generalize inner outer ts =
   let
-    val tfrees = generalize_tfrees inner outer (foldr Term.add_term_tfree_names (ts, []));
+    val tfrees = generalize_tfrees inner outer (Library.foldr Term.add_term_tfree_names (ts, []));
     fun gen (x, S) = if x mem_string tfrees then TVar ((x, 0), S) else TFree (x, S);
   in map (Term.map_term_types (Term.map_type_tfree gen)) ts end;
 
@@ -799,7 +799,7 @@
     |> Seq.map (fn rule =>
       let
         val {sign, prop, ...} = Thm.rep_thm rule;
-        val frees = map (Thm.cterm_of sign) (mapfilter (find_free prop) fixes);
+        val frees = map (Thm.cterm_of sign) (List.mapPartial (find_free prop) fixes);
         val tfrees = gen (Term.add_term_tfree_names (prop, []));
       in
         rule
@@ -846,8 +846,8 @@
 fun del_upd_bind (ctxt, (xi, NONE)) = del_bind (ctxt, xi)
   | del_upd_bind (ctxt, (xi, SOME t)) = upd_bind (ctxt, (xi, t));
 
-fun update_binds bs ctxt = foldl upd_bind (ctxt, bs);
-fun delete_update_binds bs ctxt = foldl del_upd_bind (ctxt, bs);
+fun update_binds bs ctxt = Library.foldl upd_bind (ctxt, bs);
+fun delete_update_binds bs ctxt = Library.foldl del_upd_bind (ctxt, bs);
 
 
 (* simult_matches *)
@@ -857,7 +857,7 @@
       let
         fun fail () = raise CONTEXT ("Pattern match failed!", ctxt);
 
-        val maxidx = foldl (fn (i, (t1, t2)) =>
+        val maxidx = Library.foldl (fn (i, (t1, t2)) =>
           Int.max (i, Int.max (Term.maxidx_of_term t1, Term.maxidx_of_term t2))) (~1, pairs);
         val envs = Unify.smash_unifiers (sign_of ctxt, Envir.empty maxidx,
           map swap pairs);    (*prefer assignment of variables from patterns*)
@@ -871,7 +871,7 @@
           if null (map #1 (Envir.alist_of env) inter (map #1 (Drule.vars_of_terms (map #2 pairs))))
           then () else fail ();
         fun norm_bind (xi, t) = if xi mem domain then SOME (xi, Envir.norm_term env t) else NONE;
-      in mapfilter norm_bind (Envir.alist_of env) end;
+      in List.mapPartial norm_bind (Envir.alist_of env) end;
 
 
 (* add_binds(_i) *)
@@ -879,9 +879,9 @@
 local
 
 fun gen_bind prep (ctxt, (xi as (x, _), raw_t)) =
-  ctxt |> delete_update_binds [(xi, apsome (prep ctxt) raw_t)];
+  ctxt |> delete_update_binds [(xi, Option.map (prep ctxt) raw_t)];
 
-fun gen_binds prep binds ctxt = foldl (gen_bind prep) (ctxt, binds);
+fun gen_binds prep binds ctxt = Library.foldl (gen_bind prep) (ctxt, binds);
 
 in
 
@@ -913,7 +913,7 @@
   let
     val ts = prep_terms ctxt (map snd raw_binds);
     val (ctxt', binds) =
-      apsnd flat (foldl_map (prep_bind prep_pats) (ctxt, map fst raw_binds ~~ ts));
+      apsnd List.concat (foldl_map (prep_bind prep_pats) (ctxt, map fst raw_binds ~~ ts));
     val binds' =
       if gen then map #1 binds ~~ generalize ctxt' ctxt (map #2 binds)
       else binds;
@@ -945,7 +945,7 @@
           in ((ctxt', props), (prop, splitAt(length raw_pats1, pats))) end
       | prep _ = sys_error "prep_propp";
     val ((context', _), propp) = foldl_map (foldl_map prep)
-        ((context, prep_props schematic context (flat (map (map fst) args))), args);