merged
authorchaieb
Tue, 02 Jun 2009 12:18:08 +0200
changeset 31370 a551bbe49659
parent 31354 2ad53771c30f (diff)
parent 31369 8b460fd12100 (current diff)
child 31371 75f38cfcf9d6
merged
src/HOL/Library/Formal_Power_Series.thy
--- a/Admin/CHECKLIST	Mon Jun 01 09:26:28 2009 +0200
+++ b/Admin/CHECKLIST	Tue Jun 02 12:18:08 2009 +0200
@@ -1,8 +1,9 @@
 Checklist for official releases
 ===============================
 
-- test mosml, polyml-5.2, polyml-5.1, polyml-5.0, polyml-4.1.3, polyml-4.1.4, polyml-4.2.0,
-  sparc-solaris, x86-solaris;
+- test mosml, polyml-5.2, polyml-5.1, polyml-5.0;
+
+- test sparc-solaris, x86-solaris;
 
 - test ProofGeneral;
 
--- a/Admin/isatest/isatest-settings	Mon Jun 01 09:26:28 2009 +0200
+++ b/Admin/isatest/isatest-settings	Tue Jun 02 12:18:08 2009 +0200
@@ -1,4 +1,4 @@
-# -*- shell-script -*-
+# -*- shell-script -*- :mode=shellscript:
 # $Id$
 # Author: Gerwin Klein, NICTA
 #
--- a/Admin/isatest/settings/annomaly	Mon Jun 01 09:26:28 2009 +0200
+++ b/Admin/isatest/settings/annomaly	Tue Jun 02 12:18:08 2009 +0200
@@ -1,3 +1,5 @@
+# -*- shell-script -*- :mode=shellscript:
+
 ML_SYSTEM=annomaly
 ML_HOME="$SMLNJ_HOME/bin"
 ML_OPTIONS="-m $SMLNJ_HOME/annomaly/annomaly.cm @SMLdebug=/dev/null"
--- a/Admin/isatest/settings/at-mac-poly-5.1-para	Mon Jun 01 09:26:28 2009 +0200
+++ b/Admin/isatest/settings/at-mac-poly-5.1-para	Tue Jun 02 12:18:08 2009 +0200
@@ -1,7 +1,7 @@
-# -*- shell-script -*-
+# -*- shell-script -*- :mode=shellscript:
 
-  POLYML_HOME="/home/polyml/polyml-5.2.1"
-  ML_SYSTEM="polyml-5.2.1"
+  POLYML_HOME="/home/polyml/polyml-svn"
+  ML_SYSTEM="polyml-experimental"
   ML_PLATFORM="x86-darwin"
   ML_HOME="$POLYML_HOME/$ML_PLATFORM"
   ML_OPTIONS="--mutable 800 --immutable 2000"
--- a/Admin/isatest/settings/at-poly	Mon Jun 01 09:26:28 2009 +0200
+++ b/Admin/isatest/settings/at-poly	Tue Jun 02 12:18:08 2009 +0200
@@ -1,4 +1,4 @@
-# -*- shell-script -*-
+# -*- shell-script -*- :mode=shellscript:
 
   POLYML_HOME="/home/polyml/polyml-5.2"
   ML_SYSTEM="polyml-5.2"
--- a/Admin/isatest/settings/at-poly-4.1.3	Mon Jun 01 09:26:28 2009 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,27 +0,0 @@
-# -*- shell-script -*-
-
-  POLYML_HOME="/home/polyml/polyml-4.1.3"
-  ML_SYSTEM="polyml-4.1.3"
-  ML_PLATFORM="x86-linux"
-  ML_HOME="$POLYML_HOME/$ML_PLATFORM"
-  ML_OPTIONS="-h 30000"
-
-ISABELLE_HOME_USER=~/isabelle-at-poly-4.1.3
-
-# Where to look for isabelle tools (multiple dirs separated by ':').
-ISABELLE_TOOLS="$ISABELLE_HOME/lib/Tools"
-
-# Location for temporary files (should be on a local file system).
-ISABELLE_TMP_PREFIX="/tmp/isabelle-$USER"
-
-
-# Heap input locations. ML system identifier is included in lookup.
-ISABELLE_PATH="$ISABELLE_HOME_USER/heaps:$ISABELLE_HOME/heaps"
-
-# Heap output location. ML system identifier is appended automatically later on.
-ISABELLE_OUTPUT="$ISABELLE_HOME_USER/heaps"
-ISABELLE_BROWSER_INFO="$ISABELLE_HOME_USER/browser_info"
-
-ISABELLE_USEDIR_OPTIONS="-i true -d pdf -v true"
-
-HOL_USEDIR_OPTIONS="-p 2"
--- a/Admin/isatest/settings/at-poly-5.1-para-e	Mon Jun 01 09:26:28 2009 +0200
+++ b/Admin/isatest/settings/at-poly-5.1-para-e	Tue Jun 02 12:18:08 2009 +0200
@@ -1,4 +1,4 @@
-# -*- shell-script -*-
+# -*- shell-script -*- :mode=shellscript:
 
   POLYML_HOME="/home/polyml/polyml-5.2.1"
   ML_SYSTEM="polyml-5.2.1"
--- a/Admin/isatest/settings/at-poly-dev-e	Mon Jun 01 09:26:28 2009 +0200
+++ b/Admin/isatest/settings/at-poly-dev-e	Tue Jun 02 12:18:08 2009 +0200
@@ -1,4 +1,4 @@
-# -*- shell-script -*-
+# -*- shell-script -*- :mode=shellscript:
 
   POLYML_HOME="/home/polyml/polyml-5.2"
   ML_SYSTEM="polyml-5.2"
--- a/Admin/isatest/settings/at-poly-e	Mon Jun 01 09:26:28 2009 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,27 +0,0 @@
-# -*- shell-script -*-
-
-  POLYML_HOME="/home/polyml/polyml-4.2.0"
-  ML_SYSTEM="polyml-4.2.0"
-  ML_PLATFORM="x86-linux"
-  ML_HOME="$POLYML_HOME/$ML_PLATFORM"
-  ML_OPTIONS="-h 30000"
-
-ISABELLE_HOME_USER=~/isabelle-at-poly-e
-
-# Where to look for isabelle tools (multiple dirs separated by ':').
-ISABELLE_TOOLS="$ISABELLE_HOME/lib/Tools"
-
-# Location for temporary files (should be on a local file system).
-ISABELLE_TMP_PREFIX="/tmp/isabelle-$USER"
-
-
-# Heap input locations. ML system identifier is included in lookup.
-ISABELLE_PATH="$ISABELLE_HOME_USER/heaps:$ISABELLE_HOME/heaps"
-
-# Heap output location. ML system identifier is appended automatically later on.
-ISABELLE_OUTPUT="$ISABELLE_HOME_USER/heaps"
-ISABELLE_BROWSER_INFO="$ISABELLE_HOME_USER/browser_info"
-
-ISABELLE_USEDIR_OPTIONS="-i true -d pdf -v true"
-
-HOL_USEDIR_OPTIONS="-p 2"
--- a/Admin/isatest/settings/at-sml	Mon Jun 01 09:26:28 2009 +0200
+++ b/Admin/isatest/settings/at-sml	Tue Jun 02 12:18:08 2009 +0200
@@ -1,4 +1,4 @@
-# -*- shell-script -*-
+# -*- shell-script -*- :mode=shellscript:
 
 # Standard ML of New Jersey 110 or later
 ML_SYSTEM=smlnj-110.0.7
--- a/Admin/isatest/settings/at-sml-dev-e	Mon Jun 01 09:26:28 2009 +0200
+++ b/Admin/isatest/settings/at-sml-dev-e	Tue Jun 02 12:18:08 2009 +0200
@@ -1,4 +1,4 @@
-# -*- shell-script -*-
+# -*- shell-script -*- :mode=shellscript:
 
 # Standard ML of New Jersey 110 or later
 ML_SYSTEM=smlnj
--- a/Admin/isatest/settings/at-sml-dev-p	Mon Jun 01 09:26:28 2009 +0200
+++ b/Admin/isatest/settings/at-sml-dev-p	Tue Jun 02 12:18:08 2009 +0200
@@ -1,4 +1,4 @@
-# -*- shell-script -*-
+# -*- shell-script -*- :mode=shellscript:
 
 # Standard ML of New Jersey 110 or later
 ML_SYSTEM=smlnj
--- a/Admin/isatest/settings/at64-poly	Mon Jun 01 09:26:28 2009 +0200
+++ b/Admin/isatest/settings/at64-poly	Tue Jun 02 12:18:08 2009 +0200
@@ -1,4 +1,4 @@
-# -*- shell-script -*-
+# -*- shell-script -*- :mode=shellscript:
 
   POLYML_HOME="/home/polyml/polyml-5.2"
   ML_SYSTEM="polyml-5.2"
--- a/Admin/isatest/settings/at64-poly-5.1-para	Mon Jun 01 09:26:28 2009 +0200
+++ b/Admin/isatest/settings/at64-poly-5.1-para	Tue Jun 02 12:18:08 2009 +0200
@@ -1,4 +1,4 @@
-# -*- shell-script -*-
+# -*- shell-script -*- :mode=shellscript:
 
   POLYML_HOME="/home/polyml/polyml-5.2.1"
   ML_SYSTEM="polyml-5.2.1"
--- a/Admin/isatest/settings/at64-sml-dev	Mon Jun 01 09:26:28 2009 +0200
+++ b/Admin/isatest/settings/at64-sml-dev	Tue Jun 02 12:18:08 2009 +0200
@@ -1,4 +1,4 @@
-# -*- shell-script -*-
+# -*- shell-script -*- :mode=shellscript:
 
 # Standard ML of New Jersey 110 or later
 ML_SYSTEM=smlnj
--- a/Admin/isatest/settings/mac-poly	Mon Jun 01 09:26:28 2009 +0200
+++ b/Admin/isatest/settings/mac-poly	Tue Jun 02 12:18:08 2009 +0200
@@ -1,4 +1,4 @@
-# -*- shell-script -*-
+# -*- shell-script -*- :mode=shellscript:
 
   POLYML_HOME="/home/polyml/polyml-5.2"
   ML_SYSTEM="polyml-5.2"
--- a/Admin/isatest/settings/mac-sml-dev	Mon Jun 01 09:26:28 2009 +0200
+++ b/Admin/isatest/settings/mac-sml-dev	Tue Jun 02 12:18:08 2009 +0200
@@ -1,4 +1,4 @@
-# -*- shell-script -*-
+# -*- shell-script -*- :mode=shellscript:
 
 # Standard ML of New Jersey 110 or later
 ML_SYSTEM=smlnj
--- a/Admin/isatest/settings/sun-poly	Mon Jun 01 09:26:28 2009 +0200
+++ b/Admin/isatest/settings/sun-poly	Tue Jun 02 12:18:08 2009 +0200
@@ -1,4 +1,4 @@
-# -*- shell-script -*-
+# -*- shell-script -*- :mode=shellscript:
 
   POLYML_HOME="/home/polyml/polyml-5.1"
   ML_SYSTEM="polyml-5.1"
--- a/Admin/isatest/settings/sun-sml	Mon Jun 01 09:26:28 2009 +0200
+++ b/Admin/isatest/settings/sun-sml	Tue Jun 02 12:18:08 2009 +0200
@@ -1,4 +1,4 @@
-# -*- shell-script -*-
+# -*- shell-script -*- :mode=shellscript:
 
 # Standard ML of New Jersey 110.0.7 (stable version)
 ML_SYSTEM=smlnj-110.0.7
--- a/Admin/isatest/settings/sun-sml-dev	Mon Jun 01 09:26:28 2009 +0200
+++ b/Admin/isatest/settings/sun-sml-dev	Tue Jun 02 12:18:08 2009 +0200
@@ -1,4 +1,4 @@
-# -*- shell-script -*-
+# -*- shell-script -*- :mode=shellscript:
 
 # Standard ML of New Jersey 110 or later
 ML_SYSTEM=smlnj-110
--- a/NEWS	Mon Jun 01 09:26:28 2009 +0200
+++ b/NEWS	Tue Jun 02 12:18:08 2009 +0200
@@ -26,6 +26,22 @@
 by the code generator; see Predicate.thy for an example.
 
 
+*** ML ***
+
+* Eliminated old Attrib.add_attributes, Method.add_methods and related
+cominators for "args".  INCOMPATIBILITY, need to use simplified
+Attrib/Method.setup introduced in Isabelle2009.
+
+
+*** System ***
+
+* Discontinued support for Poly/ML 4.x versions.
+
+* Removed "compress" option from isabelle-process and isabelle usedir;
+this is always enabled.
+
+
+
 New in Isabelle2009 (April 2009)
 --------------------------------
 
--- a/bin/isabelle-process	Mon Jun 01 09:26:28 2009 +0200
+++ b/bin/isabelle-process	Tue Jun 02 12:18:08 2009 +0200
@@ -26,13 +26,11 @@
   echo "Usage: $PRG [OPTIONS] [INPUT] [OUTPUT]"
   echo
   echo "  Options are:"
-  echo "    -C           tell ML system to copy output image"
   echo "    -I           startup Isar interaction mode"
   echo "    -P           startup Proof General interaction mode"
   echo "    -S           secure mode -- disallow critical operations"
   echo "    -X           startup PGIP interaction mode"
   echo "    -W OUTPUT    startup process wrapper, with messages going to OUTPUT stream"
-  echo "    -c           tell ML system to compress output image"
   echo "    -e MLTEXT    pass MLTEXT to the ML session"
   echo "    -f           pass 'Session.finish();' to the ML session"
   echo "    -m MODE      add print mode for output"
@@ -60,25 +58,20 @@
 
 # options
 
-COPYDB=""
 ISAR=false
 PROOFGENERAL=""
 SECURE=""
 WRAPPER_OUTPUT=""
 PGIP=""
-COMPRESS=""
 MLTEXT=""
 MODES=""
 TERMINATE=""
 READONLY=""
 NOWRITE=""
 
-while getopts "CIPSW:Xce:fm:qruw" OPT
+while getopts "IPSW:Xe:fm:qruw" OPT
 do
   case "$OPT" in
-    C)
-      COPYDB=true
-      ;;
     I)
       ISAR=true
       ;;
@@ -94,9 +87,6 @@
     X)
       PGIP=true
       ;;
-    c)
-      COMPRESS=true
-      ;;
     e)
       MLTEXT="$MLTEXT $OPTARG"
       ;;
@@ -235,8 +225,7 @@
   NICE=""
 fi
 
-export INFILE OUTFILE COPYDB COMPRESS MLTEXT TERMINATE NOWRITE \
-  ISABELLE_PID ISABELLE_TMP
+export INFILE OUTFILE MLTEXT TERMINATE NOWRITE ISABELLE_PID ISABELLE_TMP
 
 if [ -f "$ISABELLE_HOME/lib/scripts/run-$ML_SYSTEM" ]; then
   $NICE "$ISABELLE_HOME/lib/scripts/run-$ML_SYSTEM"
--- a/doc-src/Classes/Thy/Classes.thy	Mon Jun 01 09:26:28 2009 +0200
+++ b/doc-src/Classes/Thy/Classes.thy	Tue Jun 02 12:18:08 2009 +0200
@@ -485,14 +485,23 @@
   qed
 qed intro_locales
 
+text {*
+  \noindent This pattern is also helpful to reuse abstract
+  specifications on the \emph{same} type.  For example, think of a
+  class @{text preorder}; for type @{typ nat}, there are at least two
+  possible instances: the natural order or the order induced by the
+  divides relation.  But only one of these instances can be used for
+  @{command instantiation}; using the locale behind the class @{text
+  preorder}, it is still possible to utilise the same abstract
+  specification again using @{command interpretation}.
+*}
 
 subsection {* Additional subclass relations *}
 
 text {*
-  Any @{text "group"} is also a @{text "monoid"};  this
-  can be made explicit by claiming an additional
-  subclass relation,
-  together with a proof of the logical difference:
+  Any @{text "group"} is also a @{text "monoid"}; this can be made
+  explicit by claiming an additional subclass relation, together with
+  a proof of the logical difference:
 *}
 
 subclass %quote (in group) monoid
@@ -559,7 +568,7 @@
 subsection {* A note on syntax *}
 
 text {*
-  As a commodity, class context syntax allows to refer
+  As a convenience, class context syntax allows to refer
   to local class operations and their global counterparts
   uniformly;  type inference resolves ambiguities.  For example:
 *}
--- a/doc-src/Classes/Thy/document/Classes.tex	Mon Jun 01 09:26:28 2009 +0200
+++ b/doc-src/Classes/Thy/document/Classes.tex	Tue Jun 02 12:18:08 2009 +0200
@@ -922,15 +922,25 @@
 %
 \endisadelimquote
 %
+\begin{isamarkuptext}%
+\noindent This pattern is also helpful to reuse abstract
+  specifications on the \emph{same} type.  For example, think of a
+  class \isa{preorder}; for type \isa{nat}, there are at least two
+  possible instances: the natural order or the order induced by the
+  divides relation.  But only one of these instances can be used for
+  \hyperlink{command.instantiation}{\mbox{\isa{\isacommand{instantiation}}}}; using the locale behind the class \isa{preorder}, it is still possible to utilise the same abstract
+  specification again using \hyperlink{command.interpretation}{\mbox{\isa{\isacommand{interpretation}}}}.%
+\end{isamarkuptext}%
+\isamarkuptrue%
+%
 \isamarkupsubsection{Additional subclass relations%
 }
 \isamarkuptrue%
 %
 \begin{isamarkuptext}%
-Any \isa{group} is also a \isa{monoid};  this
-  can be made explicit by claiming an additional
-  subclass relation,
-  together with a proof of the logical difference:%
+Any \isa{group} is also a \isa{monoid}; this can be made
+  explicit by claiming an additional subclass relation, together with
+  a proof of the logical difference:%
 \end{isamarkuptext}%
 \isamarkuptrue%
 %
@@ -1038,7 +1048,7 @@
 \isamarkuptrue%
 %
 \begin{isamarkuptext}%
-As a commodity, class context syntax allows to refer
+As a convenience, class context syntax allows to refer
   to local class operations and their global counterparts
   uniformly;  type inference resolves ambiguities.  For example:%
 \end{isamarkuptext}%
--- a/doc-src/Classes/classes.tex	Mon Jun 01 09:26:28 2009 +0200
+++ b/doc-src/Classes/classes.tex	Tue Jun 02 12:18:08 2009 +0200
@@ -21,12 +21,11 @@
 \maketitle
 
 \begin{abstract}
-  \noindent This tutorial introduces the look-and-feel of Isar type classes
-  to the end-user; Isar type classes are a convenient mechanism
-  for organizing specifications, overcoming some drawbacks
-  of raw axiomatic type classes. Essentially, they combine
-  an operational aspect (in the manner of Haskell) with
-  a logical aspect, both managed uniformly.
+  \noindent This tutorial introduces the look-and-feel of
+  Isar type classes to the end-user.  Isar type classes
+  are a convenient mechanism for organizing specifications.
+  Essentially, they combine an operational aspect (in the
+  manner of Haskell) with a logical aspect, both managed uniformly.
 \end{abstract}
 
 \thispagestyle{empty}\clearpage
--- a/doc-src/Codegen/Thy/Program.thy	Mon Jun 01 09:26:28 2009 +0200
+++ b/doc-src/Codegen/Thy/Program.thy	Tue Jun 02 12:18:08 2009 +0200
@@ -204,7 +204,7 @@
   interface.
 
   \noindent The current setup of the preprocessor may be inspected using
-  the @{command print_codesetup} command.
+  the @{command print_codeproc} command.
   @{command code_thms} provides a convenient
   mechanism to inspect the impact of a preprocessor setup
   on code equations.
--- a/doc-src/Codegen/Thy/document/Program.tex	Mon Jun 01 09:26:28 2009 +0200
+++ b/doc-src/Codegen/Thy/document/Program.tex	Tue Jun 02 12:18:08 2009 +0200
@@ -486,7 +486,7 @@
   interface.
 
   \noindent The current setup of the preprocessor may be inspected using
-  the \hyperlink{command.print-codesetup}{\mbox{\isa{\isacommand{print{\isacharunderscore}codesetup}}}} command.
+  the \hyperlink{command.print-codeproc}{\mbox{\isa{\isacommand{print{\isacharunderscore}codeproc}}}} command.
   \hyperlink{command.code-thms}{\mbox{\isa{\isacommand{code{\isacharunderscore}thms}}}} provides a convenient
   mechanism to inspect the impact of a preprocessor setup
   on code equations.
--- a/doc-src/Functions/functions.tex	Mon Jun 01 09:26:28 2009 +0200
+++ b/doc-src/Functions/functions.tex	Tue Jun 02 12:18:08 2009 +0200
@@ -16,7 +16,6 @@
 \newcommand{\isasymLOCALE}{\cmd{locale}}
 \newcommand{\isasymINCLUDES}{\cmd{includes}}
 \newcommand{\isasymDATATYPE}{\cmd{datatype}}
-\newcommand{\isasymAXCLASS}{\cmd{axclass}}
 \newcommand{\isasymDEFINES}{\cmd{defines}}
 \newcommand{\isasymNOTES}{\cmd{notes}}
 \newcommand{\isasymCLASS}{\cmd{class}}
--- a/doc-src/IsarOverview/Isar/Calc.thy	Mon Jun 01 09:26:28 2009 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,49 +0,0 @@
-theory Calc imports Main begin
-
-subsection{* Chains of equalities *}
-
-axclass
-  group < zero, plus, minus
-  assoc:       "(x + y) + z = x + (y + z)"
-  left_0:      "0 + x = x"
-  left_minus:  "-x + x = 0"
-
-theorem right_minus: "x + -x = (0::'a::group)"
-proof -
-  have   "x + -x = (-(-x) + -x) + (x + -x)"
-    by (simp only: left_0 left_minus)
-  also have "... = -(-x) + ((-x + x) + -x)"
-    by (simp only: group.assoc)
-  also have "... = 0"
-    by (simp only: left_0 left_minus)
-  finally show ?thesis .
-qed
-
-subsection{* Inequalities and substitution *}
-
-lemmas distrib = zadd_zmult_distrib zadd_zmult_distrib2
-                 zdiff_zmult_distrib zdiff_zmult_distrib2
-declare numeral_2_eq_2[simp]
-
-
-lemma fixes a :: int shows "(a+b)\<twosuperior> \<le> 2*(a\<twosuperior> + b\<twosuperior>)"
-proof -
-       have "(a+b)\<twosuperior> \<le> (a+b)\<twosuperior> + (a-b)\<twosuperior>"  by simp
-  also have "(a+b)\<twosuperior> \<le> a\<twosuperior> + b\<twosuperior> + 2*a*b"  by(simp add:distrib)
-  also have "(a-b)\<twosuperior> = a\<twosuperior> + b\<twosuperior> - 2*a*b"  by(simp add:distrib)
-  finally show ?thesis by simp
-qed
-
-
-subsection{* More transitivity *}
-
-lemma assumes R: "(a,b) \<in> R" "(b,c) \<in> R" "(c,d) \<in> R"
-      shows "(a,d) \<in> R\<^sup>*"
-proof -
-       have "(a,b) \<in> R\<^sup>*" ..
-  also have "(b,c) \<in> R\<^sup>*" ..
-  also have "(c,d) \<in> R\<^sup>*" ..
-  finally show ?thesis .
-qed
-
-end
\ No newline at end of file
--- a/doc-src/IsarRef/Thy/HOL_Specific.thy	Mon Jun 01 09:26:28 2009 +0200
+++ b/doc-src/IsarRef/Thy/HOL_Specific.thy	Tue Jun 02 12:18:08 2009 +0200
@@ -1065,6 +1065,7 @@
     @{command_def (HOL) "code_modulename"} & : & @{text "theory \<rightarrow> theory"} \\
     @{command_def (HOL) "code_abort"} & : & @{text "theory \<rightarrow> theory"} \\
     @{command_def (HOL) "print_codesetup"}@{text "\<^sup>*"} & : & @{text "context \<rightarrow>"} \\
+    @{command_def (HOL) "print_codeproc"}@{text "\<^sup>*"} & : & @{text "context \<rightarrow>"} \\
     @{attribute_def (HOL) code} & : & @{text attribute} \\
   \end{matharray}
 
@@ -1228,8 +1229,10 @@
   preprocessing.
 
   \item @{command (HOL) "print_codesetup"} gives an overview on
-  selected code equations, code generator datatypes and
-  preprocessor setup.
+  selected code equations and code generator datatypes.
+
+  \item @{command (HOL) "print_codeproc"} prints the setup
+  of the code generator preprocessor.
 
   \end{description}
 *}
--- a/doc-src/IsarRef/Thy/document/HOL_Specific.tex	Mon Jun 01 09:26:28 2009 +0200
+++ b/doc-src/IsarRef/Thy/document/HOL_Specific.tex	Tue Jun 02 12:18:08 2009 +0200
@@ -1074,6 +1074,7 @@
     \indexdef{HOL}{command}{code\_modulename}\hypertarget{command.HOL.code-modulename}{\hyperlink{command.HOL.code-modulename}{\mbox{\isa{\isacommand{code{\isacharunderscore}modulename}}}}} & : & \isa{{\isachardoublequote}theory\ {\isasymrightarrow}\ theory{\isachardoublequote}} \\
     \indexdef{HOL}{command}{code\_abort}\hypertarget{command.HOL.code-abort}{\hyperlink{command.HOL.code-abort}{\mbox{\isa{\isacommand{code{\isacharunderscore}abort}}}}} & : & \isa{{\isachardoublequote}theory\ {\isasymrightarrow}\ theory{\isachardoublequote}} \\
     \indexdef{HOL}{command}{print\_codesetup}\hypertarget{command.HOL.print-codesetup}{\hyperlink{command.HOL.print-codesetup}{\mbox{\isa{\isacommand{print{\isacharunderscore}codesetup}}}}}\isa{{\isachardoublequote}\isactrlsup {\isacharasterisk}{\isachardoublequote}} & : & \isa{{\isachardoublequote}context\ {\isasymrightarrow}{\isachardoublequote}} \\
+    \indexdef{HOL}{command}{print\_codeproc}\hypertarget{command.HOL.print-codeproc}{\hyperlink{command.HOL.print-codeproc}{\mbox{\isa{\isacommand{print{\isacharunderscore}codeproc}}}}}\isa{{\isachardoublequote}\isactrlsup {\isacharasterisk}{\isachardoublequote}} & : & \isa{{\isachardoublequote}context\ {\isasymrightarrow}{\isachardoublequote}} \\
     \indexdef{HOL}{attribute}{code}\hypertarget{attribute.HOL.code}{\hyperlink{attribute.HOL.code}{\mbox{\isa{code}}}} & : & \isa{attribute} \\
   \end{matharray}
 
@@ -1234,8 +1235,10 @@
   preprocessing.
 
   \item \hyperlink{command.HOL.print-codesetup}{\mbox{\isa{\isacommand{print{\isacharunderscore}codesetup}}}} gives an overview on
-  selected code equations, code generator datatypes and
-  preprocessor setup.
+  selected code equations and code generator datatypes.
+
+  \item \hyperlink{command.HOL.print-codeproc}{\mbox{\isa{\isacommand{print{\isacharunderscore}codeproc}}}} prints the setup
+  of the code generator preprocessor.
 
   \end{description}%
 \end{isamarkuptext}%
--- a/doc-src/System/Thy/Basics.thy	Mon Jun 01 09:26:28 2009 +0200
+++ b/doc-src/System/Thy/Basics.thy	Tue Jun 02 12:18:08 2009 +0200
@@ -266,13 +266,11 @@
 Usage: isabelle-process [OPTIONS] [INPUT] [OUTPUT]
 
   Options are:
-    -C           tell ML system to copy output image
     -I           startup Isar interaction mode
     -P           startup Proof General interaction mode
     -S           secure mode -- disallow critical operations
     -W OUTPUT    startup process wrapper, with messages going to OUTPUT stream
     -X           startup PGIP interaction mode
-    -c           tell ML system to compress output image
     -e MLTEXT    pass MLTEXT to the ML session
     -f           pass 'Session.finish();' to the ML session
     -m MODE      add print mode for output
@@ -320,16 +318,6 @@
   read-only after terminating.  Thus subsequent invocations cause the
   logic image to be read-only automatically.
 
-  \medskip The @{verbatim "-c"} option tells the underlying ML system
-  to compress the output heap (fully transparently).  On Poly/ML for
-  example, the image is garbage collected and all stored values are
-  maximally shared, resulting in up to @{text "50%"} less disk space
-  consumption.
-
-  \medskip The @{verbatim "-C"} option tells the ML system to produce
-  a completely self-contained output image, probably including a copy
-  of the ML runtime system itself.
-
   \medskip Using the @{verbatim "-e"} option, arbitrary ML code may be
   passed to the Isabelle session from the command line. Multiple
   @{verbatim "-e"}'s are evaluated in the given order. Strange things
--- a/doc-src/System/Thy/Presentation.thy	Mon Jun 01 09:26:28 2009 +0200
+++ b/doc-src/System/Thy/Presentation.thy	Tue Jun 02 12:18:08 2009 +0200
@@ -446,7 +446,6 @@
     -T LEVEL     multithreading: trace level (default 0)
     -V VERSION   declare alternative document VERSION
     -b           build mode (output heap image, using current dir)
-    -c BOOL      tell ML system to compress output image (default true)
     -d FORMAT    build document as FORMAT (default false)
     -f NAME      use ML file NAME (default ROOT.ML)
     -g BOOL      generate session graph image for document (default false)
--- a/doc-src/System/Thy/document/Basics.tex	Mon Jun 01 09:26:28 2009 +0200
+++ b/doc-src/System/Thy/document/Basics.tex	Tue Jun 02 12:18:08 2009 +0200
@@ -275,13 +275,11 @@
 Usage: isabelle-process [OPTIONS] [INPUT] [OUTPUT]
 
   Options are:
-    -C           tell ML system to copy output image
     -I           startup Isar interaction mode
     -P           startup Proof General interaction mode
     -S           secure mode -- disallow critical operations
     -W OUTPUT    startup process wrapper, with messages going to OUTPUT stream
     -X           startup PGIP interaction mode
-    -c           tell ML system to compress output image
     -e MLTEXT    pass MLTEXT to the ML session
     -f           pass 'Session.finish();' to the ML session
     -m MODE      add print mode for output
@@ -331,16 +329,6 @@
   read-only after terminating.  Thus subsequent invocations cause the
   logic image to be read-only automatically.
 
-  \medskip The \verb|-c| option tells the underlying ML system
-  to compress the output heap (fully transparently).  On Poly/ML for
-  example, the image is garbage collected and all stored values are
-  maximally shared, resulting in up to \isa{{\isachardoublequote}{\isadigit{5}}{\isadigit{0}}{\isacharpercent}{\isachardoublequote}} less disk space
-  consumption.
-
-  \medskip The \verb|-C| option tells the ML system to produce
-  a completely self-contained output image, probably including a copy
-  of the ML runtime system itself.
-
   \medskip Using the \verb|-e| option, arbitrary ML code may be
   passed to the Isabelle session from the command line. Multiple
   \verb|-e|'s are evaluated in the given order. Strange things
--- a/doc-src/System/Thy/document/Presentation.tex	Mon Jun 01 09:26:28 2009 +0200
+++ b/doc-src/System/Thy/document/Presentation.tex	Tue Jun 02 12:18:08 2009 +0200
@@ -472,7 +472,6 @@
     -T LEVEL     multithreading: trace level (default 0)
     -V VERSION   declare alternative document VERSION
     -b           build mode (output heap image, using current dir)
-    -c BOOL      tell ML system to compress output image (default true)
     -d FORMAT    build document as FORMAT (default false)
     -f NAME      use ML file NAME (default ROOT.ML)
     -g BOOL      generate session graph image for document (default false)
--- a/doc-src/antiquote_setup.ML	Mon Jun 01 09:26:28 2009 +0200
+++ b/doc-src/antiquote_setup.ML	Tue Jun 02 12:18:08 2009 +0200
@@ -159,9 +159,9 @@
       end);
 
 fun entity_antiqs check markup kind =
- [(entity check markup kind NONE),
-  (entity check markup kind (SOME true)),
-  (entity check markup kind (SOME false))];
+ ((entity check markup kind NONE);
+  (entity check markup kind (SOME true));
+  (entity check markup kind (SOME false)));
 
 in
 
--- a/doc-src/manual.bib	Mon Jun 01 09:26:28 2009 +0200
+++ b/doc-src/manual.bib	Tue Jun 02 12:18:08 2009 +0200
@@ -1344,14 +1344,6 @@
   institution	= {TU Munich},
   note          = {\url{http://isabelle.in.tum.de/doc/implementation.pdf}}}
 
-@manual{isabelle-axclass,
-  author	= {Markus Wenzel},
-  title		= {Using Axiomatic Type Classes in {I}sabelle},
-  institution	= {TU Munich},
-  year          = 2000,
-  note          = {\url{http://isabelle.in.tum.de/doc/axclass.pdf}}}
-
-
 @InProceedings{Wenzel:1999:TPHOL,
   author = 	 {Markus Wenzel},
   title = 	 {{Isar} --- a Generic Interpretative Approach to Readable Formal Proof Documents},
--- a/etc/settings	Mon Jun 01 09:26:28 2009 +0200
+++ b/etc/settings	Tue Jun 02 12:18:08 2009 +0200
@@ -15,7 +15,7 @@
 # not invent new ML system names unless you know what you are doing.
 # Only one of the sections below should be activated.
 
-# Poly/ML 4.x/5.x (automated settings)
+# Poly/ML 5.x (automated settings)
 POLY_HOME="$(type -p poly)"; [ -n "$POLY_HOME" ] && POLY_HOME="$(dirname "$POLY_HOME")"
 ML_PLATFORM=$("$ISABELLE_HOME/lib/scripts/polyml-platform")
 ML_HOME=$(choosefrom \
@@ -29,24 +29,18 @@
 ML_OPTIONS="-H 200"
 ML_DBASE=""
 
-# Poly/ML 5.1
+# Poly/ML 5.2.1
 #ML_PLATFORM=x86-linux
 #ML_HOME=/usr/local/polyml/x86-linux
-#ML_SYSTEM=polyml-5.1
+#ML_SYSTEM=polyml-5.2.1
 #ML_OPTIONS="-H 500"
 
-# Poly/ML 5.1 (64 bit)
+# Poly/ML 5.2.1 (64 bit)
 #ML_PLATFORM=x86_64-linux
 #ML_HOME=/usr/local/polyml/x86_64-linux
-#ML_SYSTEM=polyml-5.1
+#ML_SYSTEM=polyml-5.2.1
 #ML_OPTIONS="-H 1000"
 
-# Poly/ML 4.2.0
-#ML_PLATFORM=x86-linux
-#ML_HOME=/usr/local/polyml/x86-linux
-#ML_SYSTEM=polyml-4.2.0
-#ML_OPTIONS="-H 80"
-
 # Standard ML of New Jersey (slow!)
 #ML_SYSTEM=smlnj-110
 #ML_HOME="/usr/local/smlnj/bin"
--- a/etc/user-settings.sample	Mon Jun 01 09:26:28 2009 +0200
+++ b/etc/user-settings.sample	Tue Jun 02 12:18:08 2009 +0200
@@ -1,4 +1,4 @@
-# -*- shell-script -*-
+# -*- shell-script -*- :mode=shellscript:
 #
 # Isabelle user settings sample -- for use in ~/.isabelle/etc/settings
 
--- a/lib/Tools/usedir	Mon Jun 01 09:26:28 2009 +0200
+++ b/lib/Tools/usedir	Tue Jun 02 12:18:08 2009 +0200
@@ -23,7 +23,6 @@
   echo "    -T LEVEL     multithreading: trace level (default 0)"
   echo "    -V VERSION   declare alternative document VERSION"
   echo "    -b           build mode (output heap image, using current dir)"
-  echo "    -c BOOL      tell ML system to compress output image (default true)"
   echo "    -d FORMAT    build document as FORMAT (default false)"
   echo "    -f NAME      use ML file NAME (default ROOT.ML)"
   echo "    -g BOOL      generate session graph image for document (default false)"
@@ -77,7 +76,6 @@
 TRACETHREADS="0"
 DOCUMENT_VERSIONS=""
 BUILD=""
-COMPRESS=true
 DOCUMENT=false
 ROOT_FILE="ROOT.ML"
 DOCUMENT_GRAPH=false
@@ -91,7 +89,7 @@
 function getoptions()
 {
   OPTIND=1
-  while getopts "C:D:M:P:Q:T:V:bc:d:f:g:i:m:p:rs:v:" OPT
+  while getopts "C:D:M:P:Q:T:V:bd:f:g:i:m:p:rs:v:" OPT
   do
     case "$OPT" in
       C)
@@ -129,10 +127,6 @@
       b)
         BUILD=true
         ;;
-      c)
-        check_bool "$OPTARG"
-        COMPRESS="$OPTARG"
-        ;;
       d)
         DOCUMENT="$OPTARG"
         ;;
@@ -175,7 +169,8 @@
   done
 }
 
-getoptions $ISABELLE_USEDIR_OPTIONS
+eval "OPTIONS=($ISABELLE_USEDIR_OPTIONS)"
+getoptions "${OPTIONS[@]}"
 
 getoptions "$@"
 shift $(($OPTIND - 1))
@@ -233,12 +228,9 @@
   echo "Building $ITEM ..." >&2
   LOG="$LOGDIR/$ITEM"
 
-  OPT_C=""
-  [ "$COMPRESS" = true ] && OPT_C="-c"
-
   "$ISABELLE_PROCESS" \
     -e "Session.use_dir \"$ROOT_FILE\" true [$MODES] $RESET $INFO \"$DOC\" $DOCUMENT_GRAPH [$DOCUMENT_VERSIONS] \"$PARENT\" \"$SESSION\" ($COPY_DUMP, \"$DUMP\") \"$RPATH\" $PROOFS $VERBOSE $MAXTHREADS $TRACETHREADS $PARALLEL_PROOFS;" \
-    $OPT_C -q -w $LOGIC $NAME > "$LOG"
+    -q -w $LOGIC $NAME > "$LOG"
   RC="$?"
 else
   ITEM=$(basename "$LOGIC")-"$SESSION"
--- a/lib/scripts/run-mosml	Mon Jun 01 09:26:28 2009 +0200
+++ b/lib/scripts/run-mosml	Tue Jun 02 12:18:08 2009 +0200
@@ -4,7 +4,7 @@
 #
 # Moscow ML 2.00 startup script
 
-export -n INFILE OUTFILE COPYDB COMPRESS MLTEXT TERMINATE NOWRITE
+export -n INFILE OUTFILE MLTEXT TERMINATE NOWRITE
 
 
 ## diagnostics
--- a/lib/scripts/run-polyml	Mon Jun 01 09:26:28 2009 +0200
+++ b/lib/scripts/run-polyml	Tue Jun 02 12:18:08 2009 +0200
@@ -4,7 +4,7 @@
 #
 # Poly/ML 5.1/5.2 startup script.
 
-export -n INFILE OUTFILE COPYDB COMPRESS MLTEXT TERMINATE NOWRITE
+export -n INFILE OUTFILE MLTEXT TERMINATE NOWRITE
 
 
 ## diagnostics
@@ -54,11 +54,7 @@
 if [ -z "$OUTFILE" ]; then
   COMMIT='fun commit () = (TextIO.output (TextIO.stdErr, "Error - Database is not opened for writing.\n"); false);'
 else
-  if [ -z "$COMPRESS" ]; then
-    COMMIT="fun commit () = (TextIO.output (TextIO.stdOut, \"Exporting $OUTFILE\n\"); PolyML.SaveState.saveState \"$OUTFILE\"; true);"
-  else
-    COMMIT="fun commit () = (PolyML.shareCommonData PolyML.rootFunction; TextIO.output (TextIO.stdOut, \"Exporting $OUTFILE\n\"); PolyML.SaveState.saveState \"$OUTFILE\"; true);"
-  fi
+  COMMIT="fun commit () = (PolyML.shareCommonData PolyML.rootFunction; TextIO.output (TextIO.stdOut, \"Exporting $OUTFILE\n\"); PolyML.SaveState.saveState \"$OUTFILE\"; true);"
   [ -f "$OUTFILE" ] && { chmod +w "$OUTFILE" || fail_out; }
 fi
 
--- a/lib/scripts/run-polyml-4.1.3	Mon Jun 01 09:26:28 2009 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,106 +0,0 @@
-#!/usr/bin/env bash
-#
-# Author: Markus Wenzel, TU Muenchen
-#
-# Poly/ML 4.x startup script.
-
-export -n INFILE OUTFILE COPYDB COMPRESS MLTEXT TERMINATE NOWRITE
-
-
-## diagnostics
-
-function fail_out()
-{
-  echo "Unable to create output heap file: \"$OUTFILE\"" >&2
-  exit 2
-}
-
-function check_file()
-{
-  if [ ! -f "$1" ]; then
-    echo "Unable to locate $1" >&2
-    echo "Please check your ML system settings!" >&2
-    exit 2
-  fi
-}
-
-
-## Poly/ML executable and database
-
-ML_DBASE_PREFIX=""
-
-POLY="$ML_HOME/poly"
-check_file "$POLY"
-
-if [ -z "$ML_DBASE" ]; then
-  if [ ! -e "$ML_HOME/ML_dbase" -a "$(basename "$ML_HOME")" = bin ]; then
-    ML_DBASE_HOME="$(cd "$ML_HOME"; cd "$(pwd -P)"; cd ../lib/poly; pwd)"
-  else
-    ML_DBASE_HOME="$ML_HOME"
-  fi
-  if [ -z "$COPYDB" ]; then
-    ML_DBASE_PREFIX="$ML_DBASE_HOME/"
-    ML_DBASE="ML_dbase"
-  else
-    ML_DBASE="$ML_DBASE_HOME/ML_dbase"
-  fi
-  export POLYPATH="$ML_DBASE_HOME"
-else
-  export POLYPATH="$(dirname "$ML_DBASE")"
-fi
-
-DISCGARB_OPTIONS="-d -c"
-
-EXIT="fun exit 0 = (OS.Process.exit OS.Process.success): unit | exit _ = OS.Process.exit OS.Process.failure;"
-
-
-## prepare databases
-
-if [ -z "$INFILE" ]; then
-  check_file "$ML_DBASE_PREFIX$ML_DBASE"
-  INFILE="$ML_DBASE"
-  MLTEXT="val use = PolyML.use; $EXIT $MLTEXT"
-  DISCGARB_OPTIONS="$DISCGARB_OPTIONS -S max"
-else
-  COPYDB=true
-fi
-
-if [ -z "$OUTFILE" ]; then
-  DB="$INFILE"
-  ML_OPTIONS="-r $ML_OPTIONS"
-elif [ "$INFILE" -ef "$OUTFILE" ]; then
-  DB="$INFILE"
-elif [ -n "$COPYDB" ]; then
-  [ -f "$OUTFILE" ] && { rm -f "$OUTFILE" || fail_out; }
-  cp "$INFILE" "$OUTFILE" || fail_out
-  chmod +w "$OUTFILE" || fail_out
-  DB="$OUTFILE"
-else
-  [ -f "$OUTFILE" ] && { rm -f "$OUTFILE" || fail_out; }
-  echo "PolyML.make_database \"$OUTFILE\"; PolyML.quit();" | "$POLY" -r "$INFILE"
-  [ -f "$OUTFILE" ] || fail_out
-  DB="$OUTFILE"
-fi
-
-
-## run it!
-
-if [ -z "$TERMINATE" ]; then
-  FEEDER_OPTS=""
-else
-  FEEDER_OPTS="-q"
-fi
-
-DB_INFO="$(ls -l "$DB" 2>/dev/null)"
-
-"$ISABELLE_HOME/lib/scripts/feeder" -p -h "$MLTEXT" $FEEDER_OPTS | {
-  read FPID; "$POLY" $ML_OPTIONS "$DB";
-  RC="$?"; kill -HUP "$FPID"; exit "$RC"; }
-RC="$?"
-
-NEW_DB_INFO="$(ls -l "$DB" 2>/dev/null)"
-[ -n "$OUTFILE" -a -n "$COMPRESS" -a "$DB_INFO" != "$NEW_DB_INFO" ] && \
-  "$POLY" $DISCGARB_OPTIONS "$OUTFILE"
-[ -n "$OUTFILE" -a -f "$OUTFILE" -a -n "$NOWRITE" ] && chmod -w "$OUTFILE"
-
-exit "$RC"
--- a/lib/scripts/run-polyml-4.1.4	Mon Jun 01 09:26:28 2009 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,106 +0,0 @@
-#!/usr/bin/env bash
-#
-# Author: Markus Wenzel, TU Muenchen
-#
-# Poly/ML 4.x startup script.
-
-export -n INFILE OUTFILE COPYDB COMPRESS MLTEXT TERMINATE NOWRITE
-
-
-## diagnostics
-
-function fail_out()
-{
-  echo "Unable to create output heap file: \"$OUTFILE\"" >&2
-  exit 2
-}
-
-function check_file()
-{
-  if [ ! -f "$1" ]; then
-    echo "Unable to locate $1" >&2
-    echo "Please check your ML system settings!" >&2
-    exit 2
-  fi
-}
-
-
-## Poly/ML executable and database
-
-ML_DBASE_PREFIX=""
-
-POLY="$ML_HOME/poly"
-check_file "$POLY"
-
-if [ -z "$ML_DBASE" ]; then
-  if [ ! -e "$ML_HOME/ML_dbase" -a "$(basename "$ML_HOME")" = bin ]; then
-    ML_DBASE_HOME="$(cd "$ML_HOME"; cd "$(pwd -P)"; cd ../lib/poly; pwd)"
-  else
-    ML_DBASE_HOME="$ML_HOME"
-  fi
-  if [ -z "$COPYDB" ]; then
-    ML_DBASE_PREFIX="$ML_DBASE_HOME/"
-    ML_DBASE="ML_dbase"
-  else
-    ML_DBASE="$ML_DBASE_HOME/ML_dbase"
-  fi
-  export POLYPATH="$ML_DBASE_HOME"
-else
-  export POLYPATH="$(dirname "$ML_DBASE")"
-fi
-
-DISCGARB_OPTIONS="-d -c"
-
-EXIT="fun exit 0 = (OS.Process.exit OS.Process.success): unit | exit _ = OS.Process.exit OS.Process.failure;"
-
-
-## prepare databases
-
-if [ -z "$INFILE" ]; then
-  check_file "$ML_DBASE_PREFIX$ML_DBASE"
-  INFILE="$ML_DBASE"
-  MLTEXT="val use = PolyML.use; $EXIT $MLTEXT"
-  DISCGARB_OPTIONS="$DISCGARB_OPTIONS -S max"
-else
-  COPYDB=true
-fi
-
-if [ -z "$OUTFILE" ]; then
-  DB="$INFILE"
-  ML_OPTIONS="-r $ML_OPTIONS"
-elif [ "$INFILE" -ef "$OUTFILE" ]; then
-  DB="$INFILE"
-elif [ -n "$COPYDB" ]; then
-  [ -f "$OUTFILE" ] && { rm -f "$OUTFILE" || fail_out; }
-  cp "$INFILE" "$OUTFILE" || fail_out
-  chmod +w "$OUTFILE" || fail_out
-  DB="$OUTFILE"
-else
-  [ -f "$OUTFILE" ] && { rm -f "$OUTFILE" || fail_out; }
-  echo "PolyML.make_database \"$OUTFILE\"; PolyML.quit();" | "$POLY" -r "$INFILE"
-  [ -f "$OUTFILE" ] || fail_out
-  DB="$OUTFILE"
-fi
-
-
-## run it!
-
-if [ -z "$TERMINATE" ]; then
-  FEEDER_OPTS=""
-else
-  FEEDER_OPTS="-q"
-fi
-
-DB_INFO="$(ls -l "$DB" 2>/dev/null)"
-
-"$ISABELLE_HOME/lib/scripts/feeder" -p -h "$MLTEXT" $FEEDER_OPTS | {
-  read FPID; "$POLY" $ML_OPTIONS "$DB";
-  RC="$?"; kill -HUP "$FPID"; exit "$RC"; }
-RC="$?"
-
-NEW_DB_INFO="$(ls -l "$DB" 2>/dev/null)"
-[ -n "$OUTFILE" -a -n "$COMPRESS" -a "$DB_INFO" != "$NEW_DB_INFO" ] && \
-  "$POLY" $DISCGARB_OPTIONS "$OUTFILE"
-[ -n "$OUTFILE" -a -f "$OUTFILE" -a -n "$NOWRITE" ] && chmod -w "$OUTFILE"
-
-exit "$RC"
--- a/lib/scripts/run-polyml-4.2.0	Mon Jun 01 09:26:28 2009 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,106 +0,0 @@
-#!/usr/bin/env bash
-#
-# Author: Markus Wenzel, TU Muenchen
-#
-# Poly/ML 4.x startup script.
-
-export -n INFILE OUTFILE COPYDB COMPRESS MLTEXT TERMINATE NOWRITE
-
-
-## diagnostics
-
-function fail_out()
-{
-  echo "Unable to create output heap file: \"$OUTFILE\"" >&2
-  exit 2
-}
-
-function check_file()
-{
-  if [ ! -f "$1" ]; then
-    echo "Unable to locate $1" >&2
-    echo "Please check your ML system settings!" >&2
-    exit 2
-  fi
-}
-
-
-## Poly/ML executable and database
-
-ML_DBASE_PREFIX=""
-
-POLY="$ML_HOME/poly"
-check_file "$POLY"
-
-if [ -z "$ML_DBASE" ]; then
-  if [ ! -e "$ML_HOME/ML_dbase" -a "$(basename "$ML_HOME")" = bin ]; then
-    ML_DBASE_HOME="$(cd "$ML_HOME"; cd "$(pwd -P)"; cd ../lib/poly; pwd)"
-  else
-    ML_DBASE_HOME="$ML_HOME"
-  fi
-  if [ -z "$COPYDB" ]; then
-    ML_DBASE_PREFIX="$ML_DBASE_HOME/"
-    ML_DBASE="ML_dbase"
-  else
-    ML_DBASE="$ML_DBASE_HOME/ML_dbase"
-  fi
-  export POLYPATH="$ML_DBASE_HOME"
-else
-  export POLYPATH="$(dirname "$ML_DBASE")"
-fi
-
-DISCGARB_OPTIONS="-d -c"
-
-EXIT="fun exit 0 = (OS.Process.exit OS.Process.success): unit | exit _ = OS.Process.exit OS.Process.failure;"
-
-
-## prepare databases
-
-if [ -z "$INFILE" ]; then
-  check_file "$ML_DBASE_PREFIX$ML_DBASE"
-  INFILE="$ML_DBASE"
-  MLTEXT="val use = PolyML.use; $EXIT $MLTEXT"
-  DISCGARB_OPTIONS="$DISCGARB_OPTIONS -S max"
-else
-  COPYDB=true
-fi
-
-if [ -z "$OUTFILE" ]; then
-  DB="$INFILE"
-  ML_OPTIONS="-r $ML_OPTIONS"
-elif [ "$INFILE" -ef "$OUTFILE" ]; then
-  DB="$INFILE"
-elif [ -n "$COPYDB" ]; then
-  [ -f "$OUTFILE" ] && { rm -f "$OUTFILE" || fail_out; }
-  cp "$INFILE" "$OUTFILE" || fail_out
-  chmod +w "$OUTFILE" || fail_out
-  DB="$OUTFILE"
-else
-  [ -f "$OUTFILE" ] && { rm -f "$OUTFILE" || fail_out; }
-  echo "PolyML.make_database \"$OUTFILE\"; PolyML.quit();" | "$POLY" -r "$INFILE"
-  [ -f "$OUTFILE" ] || fail_out
-  DB="$OUTFILE"
-fi
-
-
-## run it!
-
-if [ -z "$TERMINATE" ]; then
-  FEEDER_OPTS=""
-else
-  FEEDER_OPTS="-q"
-fi
-
-DB_INFO="$(ls -l "$DB" 2>/dev/null)"
-
-"$ISABELLE_HOME/lib/scripts/feeder" -p -h "$MLTEXT" $FEEDER_OPTS | {
-  read FPID; "$POLY" $ML_OPTIONS "$DB";
-  RC="$?"; kill -HUP "$FPID"; exit "$RC"; }
-RC="$?"
-
-NEW_DB_INFO="$(ls -l "$DB" 2>/dev/null)"
-[ -n "$OUTFILE" -a -n "$COMPRESS" -a "$DB_INFO" != "$NEW_DB_INFO" ] && \
-  "$POLY" $DISCGARB_OPTIONS "$OUTFILE"
-[ -n "$OUTFILE" -a -f "$OUTFILE" -a -n "$NOWRITE" ] && chmod -w "$OUTFILE"
-
-exit "$RC"
--- a/lib/scripts/run-polyml-5.0	Mon Jun 01 09:26:28 2009 +0200
+++ b/lib/scripts/run-polyml-5.0	Tue Jun 02 12:18:08 2009 +0200
@@ -4,7 +4,7 @@
 #
 # Poly/ML 5.0 startup script.
 
-export -n INFILE OUTFILE COPYDB COMPRESS MLTEXT TERMINATE NOWRITE
+export -n INFILE OUTFILE MLTEXT TERMINATE NOWRITE
 
 
 ## diagnostics
@@ -54,11 +54,7 @@
 if [ -z "$OUTFILE" ]; then
   COMMIT='fun commit () = (TextIO.output (TextIO.stdErr, "Error - Database is not opened for writing.\n"); false);'
 else
-  if [ -z "$COMPRESS" ]; then
-    COMMIT="fun commit () = (TextIO.output (TextIO.stdOut, \"Exporting $OUTFILE\n\"); PolyML.export (\"$OUTFILE\", PolyML.rootFunction); true);"
-  else
-    COMMIT="fun commit () = (PolyML.shareCommonData PolyML.rootFunction; TextIO.output (TextIO.stdOut, \"Exporting $OUTFILE\n\"); PolyML.export (\"$OUTFILE\", PolyML.rootFunction); true);"
-  fi
+  COMMIT="fun commit () = (PolyML.shareCommonData PolyML.rootFunction; TextIO.output (TextIO.stdOut, \"Exporting $OUTFILE\n\"); PolyML.export (\"$OUTFILE\", PolyML.rootFunction); true);"
   [ -f "$OUTFILE" ] && { chmod +w "$OUTFILE" || fail_out; }
   rm -f "${OUTFILE}.o" || fail_out
 fi
--- a/lib/scripts/run-smlnj	Mon Jun 01 09:26:28 2009 +0200
+++ b/lib/scripts/run-smlnj	Tue Jun 02 12:18:08 2009 +0200
@@ -4,7 +4,7 @@
 #
 # SML/NJ startup script (for 110 or later).
 
-export -n INFILE OUTFILE COPYDB COMPRESS MLTEXT TERMINATE NOWRITE
+export -n INFILE OUTFILE MLTEXT TERMINATE NOWRITE
 
 
 ## diagnostics
--- a/lib/scripts/timestart.bash	Mon Jun 01 09:26:28 2009 +0200
+++ b/lib/scripts/timestart.bash	Tue Jun 02 12:18:08 2009 +0200
@@ -1,4 +1,4 @@
-# -*- shell-script -*-
+# -*- shell-script -*- :mode=shellscript:
 #
 # Author: Makarius
 #
--- a/lib/scripts/timestop.bash	Mon Jun 01 09:26:28 2009 +0200
+++ b/lib/scripts/timestop.bash	Tue Jun 02 12:18:08 2009 +0200
@@ -1,4 +1,4 @@
-# -*- shell-script -*-
+# -*- shell-script -*- :mode=shellscript:
 #
 # Author: Makarius
 #
--- a/src/FOL/IFOL.thy	Mon Jun 01 09:26:28 2009 +0200
+++ b/src/FOL/IFOL.thy	Tue Jun 02 12:18:08 2009 +0200
@@ -610,7 +610,7 @@
 
 subsection {* Intuitionistic Reasoning *}
 
-setup {* Intuitionistic.method_setup "iprover" *}
+setup {* Intuitionistic.method_setup @{binding iprover} *}
 
 lemma impE':
   assumes 1: "P --> Q"
--- a/src/HOL/Code_Numeral.thy	Mon Jun 01 09:26:28 2009 +0200
+++ b/src/HOL/Code_Numeral.thy	Tue Jun 02 12:18:08 2009 +0200
@@ -215,7 +215,13 @@
   "of_nat n < of_nat m \<longleftrightarrow> n < m"
   by simp
 
-lemma Suc_code_numeral_minus_one: "Suc_code_numeral n - 1 = n" by simp
+lemma code_numeral_zero_minus_one:
+  "(0::code_numeral) - 1 = 0"
+  by simp
+
+lemma Suc_code_numeral_minus_one:
+  "Suc_code_numeral n - 1 = n"
+  by simp
 
 lemma of_nat_code [code]:
   "of_nat = Nat.of_nat"
--- a/src/HOL/Complex.thy	Mon Jun 01 09:26:28 2009 +0200
+++ b/src/HOL/Complex.thy	Tue Jun 02 12:18:08 2009 +0200
@@ -278,6 +278,9 @@
 definition
   complex_sgn_def: "sgn x = x /\<^sub>R cmod x"
 
+definition
+  dist_complex_def: "dist x y = cmod (x - y)"
+
 lemmas cmod_def = complex_norm_def
 
 lemma complex_norm [simp]: "cmod (Complex x y) = sqrt (x\<twosuperior> + y\<twosuperior>)"
@@ -299,7 +302,10 @@
   show "norm (x * y) = norm x * norm y"
     by (induct x, induct y)
        (simp add: real_sqrt_mult [symmetric] power2_eq_square algebra_simps)
-  show "sgn x = x /\<^sub>R cmod x" by(simp add: complex_sgn_def)
+  show "sgn x = x /\<^sub>R cmod x"
+    by (rule complex_sgn_def)
+  show "dist x y = cmod (x - y)"
+    by (rule dist_complex_def)
 qed
 
 end
--- a/src/HOL/Decision_Procs/cooper_tac.ML	Mon Jun 01 09:26:28 2009 +0200
+++ b/src/HOL/Decision_Procs/cooper_tac.ML	Tue Jun 02 12:18:08 2009 +0200
@@ -2,7 +2,14 @@
     Author:     Amine Chaieb, TU Muenchen
 *)
 
-structure Cooper_Tac =
+signature COOPER_TAC =
+sig
+  val trace: bool ref
+  val linz_tac: Proof.context -> bool -> int -> tactic
+  val setup: theory -> theory
+end
+
+structure Cooper_Tac: COOPER_TAC =
 struct
 
 val trace = ref false;
@@ -33,7 +40,7 @@
 val nat_div_add_eq = @{thm div_add1_eq} RS sym;
 val int_div_add_eq = @{thm zdiv_zadd1_eq} RS sym;
 
-fun prepare_for_linz q fm = 
+fun prepare_for_linz q fm =
   let
     val ps = Logic.strip_params fm
     val hs = map HOLogic.dest_Trueprop (Logic.strip_assums_hyp fm)
@@ -66,8 +73,8 @@
     (* Transform the term*)
     val (t,np,nh) = prepare_for_linz q g
     (* Some simpsets for dealing with mod div abs and nat*)
-    val mod_div_simpset = HOL_basic_ss 
-			addsimps [refl,mod_add_eq, mod_add_left_eq, 
+    val mod_div_simpset = HOL_basic_ss
+			addsimps [refl,mod_add_eq, mod_add_left_eq,
 				  mod_add_right_eq,
 				  nat_div_add_eq, int_div_add_eq,
 				  @{thm mod_self}, @{thm "zmod_self"},
@@ -105,30 +112,24 @@
     val (th, tac) = case (prop_of pre_thm) of
         Const ("==>", _) $ (Const ("Trueprop", _) $ t1) $ _ =>
     let val pth = linzqe_oracle (cterm_of thy (Pattern.eta_long [] t1))
-    in 
+    in
           ((pth RS iffD2) RS pre_thm,
             assm_tac (i + 1) THEN (if q then I else TRY) (rtac TrueI i))
     end
       | _ => (pre_thm, assm_tac i)
-  in (rtac (((mp_step nh) o (spec_step np)) th) i 
+  in (rtac (((mp_step nh) o (spec_step np)) th) i
       THEN tac) st
   end handle Subscript => no_tac st);
 
-fun linz_args meth =
- let val parse_flag = 
-         Args.$$$ "no_quantify" >> (K (K false));
- in
-   Method.simple_args 
-  (Scan.optional (Args.$$$ "(" |-- Scan.repeat1 parse_flag --| Args.$$$ ")") [] >>
-    curry (Library.foldl op |>) true)
-    (fn q => fn ctxt => meth ctxt q)
-  end;
-
-fun linz_method ctxt q = SIMPLE_METHOD' (linz_tac ctxt q);
-
 val setup =
-  Method.add_method ("cooper",
-     linz_args linz_method,
-     "decision procedure for linear integer arithmetic");
+  Method.setup @{binding cooper}
+    let
+      val parse_flag = Args.$$$ "no_quantify" >> K (K false)
+    in
+      Scan.lift (Scan.optional (Args.$$$ "(" |-- Scan.repeat1 parse_flag --| Args.$$$ ")") [] >>
+        curry (Library.foldl op |>) true) >>
+      (fn q => fn ctxt => SIMPLE_METHOD' (linz_tac ctxt q))
+    end
+    "decision procedure for linear integer arithmetic";
 
 end
--- a/src/HOL/Decision_Procs/ferrack_tac.ML	Mon Jun 01 09:26:28 2009 +0200
+++ b/src/HOL/Decision_Procs/ferrack_tac.ML	Tue Jun 02 12:18:08 2009 +0200
@@ -2,6 +2,13 @@
     Author:     Amine Chaieb, TU Muenchen
 *)
 
+signature FERRACK_TAC =
+sig
+  val trace: bool ref
+  val linr_tac: Proof.context -> bool -> int -> tactic
+  val setup: theory -> theory
+end
+
 structure Ferrack_Tac =
 struct
 
@@ -98,12 +105,10 @@
       THEN tac) st
   end handle Subscript => no_tac st);
 
-fun linr_meth src =
-  Method.syntax (Args.mode "no_quantify") src
-  #> (fn (q, ctxt) => SIMPLE_METHOD' (linr_tac ctxt (not q)));
-
 val setup =
-  Method.add_method ("rferrack", linr_meth,
-     "decision procedure for linear real arithmetic");
+  Method.setup @{binding rferrack}
+    (Args.mode "no_quantify" >> (fn q => fn ctxt =>
+      SIMPLE_METHOD' (linr_tac ctxt (not q))))
+    "decision procedure for linear real arithmetic";
 
 end
--- a/src/HOL/Decision_Procs/mir_tac.ML	Mon Jun 01 09:26:28 2009 +0200
+++ b/src/HOL/Decision_Procs/mir_tac.ML	Tue Jun 02 12:18:08 2009 +0200
@@ -2,6 +2,13 @@
     Author:     Amine Chaieb, TU Muenchen
 *)
 
+signature MIR_TAC =
+sig
+  val trace: bool ref
+  val mir_tac: Proof.context -> bool -> int -> tactic
+  val setup: theory -> theory
+end
+
 structure Mir_Tac =
 struct
 
@@ -82,9 +89,9 @@
 
 
 fun mir_tac ctxt q i = 
-    (ObjectLogic.atomize_prems_tac i)
-        THEN (simp_tac (HOL_basic_ss addsimps [@{thm "abs_ge_zero"}] addsimps simp_thms) i)
-        THEN (REPEAT_DETERM (split_tac [@{thm "split_min"}, @{thm "split_max"},@{thm "abs_split"}] i))
+    ObjectLogic.atomize_prems_tac i
+        THEN simp_tac (HOL_basic_ss addsimps [@{thm "abs_ge_zero"}] addsimps simp_thms) i
+        THEN REPEAT_DETERM (split_tac [@{thm "split_min"}, @{thm "split_max"}, @{thm "abs_split"}] i)
         THEN (fn st =>
   let
     val g = List.nth (prems_of st, i - 1)
@@ -143,22 +150,15 @@
       THEN tac) st
   end handle Subscript => no_tac st);
 
-fun mir_args meth =
- let val parse_flag = 
-         Args.$$$ "no_quantify" >> (K (K false));
- in
-   Method.simple_args 
-  (Scan.optional (Args.$$$ "(" |-- Scan.repeat1 parse_flag --| Args.$$$ ")") [] >>
-    curry (Library.foldl op |>) true)
-    (fn q => fn ctxt => meth ctxt q)
-  end;
-
-fun mir_method ctxt q = SIMPLE_METHOD' (mir_tac ctxt q);
-
 val setup =
-  Method.add_method ("mir",
-     mir_args mir_method,
-     "decision procedure for MIR arithmetic");
-
+  Method.setup @{binding mir}
+    let
+      val parse_flag = Args.$$$ "no_quantify" >> K (K false)
+    in
+      Scan.lift (Scan.optional (Args.$$$ "(" |-- Scan.repeat1 parse_flag --| Args.$$$ ")") [] >>
+        curry (Library.foldl op |>) true) >>
+      (fn q => fn ctxt => SIMPLE_METHOD' (mir_tac ctxt q))
+    end
+    "decision procedure for MIR arithmetic";
 
 end
--- a/src/HOL/Deriv.thy	Mon Jun 01 09:26:28 2009 +0200
+++ b/src/HOL/Deriv.thy	Tue Jun 02 12:18:08 2009 +0200
@@ -76,7 +76,7 @@
   hence "(\<lambda>h. f(x+h) - f(x)) -- 0 --> 0"
     by (simp cong: LIM_cong)
   thus "(\<lambda>h. f(x+h)) -- 0 --> f(x)"
-    by (simp add: LIM_def)
+    by (simp add: LIM_def dist_norm)
 qed
 
 lemma DERIV_mult_lemma:
@@ -125,6 +125,7 @@
 text{*Alternative definition for differentiability*}
 
 lemma DERIV_LIM_iff:
+  fixes f :: "'a::{real_normed_vector,inverse} \<Rightarrow> 'a" shows
      "((%h. (f(a + h) - f(a)) / h) -- 0 --> D) =
       ((%x. (f(x)-f(a)) / (x-a)) -- a --> D)"
 apply (rule iffI)
@@ -577,7 +578,7 @@
 apply (drule not_P_Bolzano_bisect', assumption+)
 apply (rename_tac "l")
 apply (drule_tac x = l in spec, clarify)
-apply (simp add: LIMSEQ_def)
+apply (simp add: LIMSEQ_iff)
 apply (drule_tac P = "%r. 0<r --> ?Q r" and x = "d/2" in spec)
 apply (drule_tac P = "%r. 0<r --> ?Q r" and x = "d/2" in spec)
 apply (drule real_less_half_sum, auto)
@@ -614,7 +615,7 @@
 apply (cut_tac P = "% (u,v) . a \<le> u & u \<le> v & v \<le> b --> ~ (f (u) \<le> y & y \<le> f (v))" in lemma_BOLZANO2)
 apply safe
 apply simp_all
-apply (simp add: isCont_iff LIM_def)
+apply (simp add: isCont_iff LIM_eq)
 apply (rule ccontr)
 apply (subgoal_tac "a \<le> x & x \<le> b")
  prefer 2
@@ -675,7 +676,7 @@
 apply (case_tac "a \<le> x & x \<le> b")
 apply (rule_tac [2] x = 1 in exI)
 prefer 2 apply force
-apply (simp add: LIM_def isCont_iff)
+apply (simp add: LIM_eq isCont_iff)
 apply (drule_tac x = x in spec, auto)
 apply (erule_tac V = "\<forall>M. \<exists>x. a \<le> x & x \<le> b & ~ f x \<le> M" in thin_rl)
 apply (drule_tac x = 1 in spec, auto)
@@ -1486,7 +1487,7 @@
 lemma LIM_fun_gt_zero:
      "[| f -- c --> (l::real); 0 < l |]  
          ==> \<exists>r. 0 < r & (\<forall>x::real. x \<noteq> c & \<bar>c - x\<bar> < r --> 0 < f x)"
-apply (auto simp add: LIM_def)
+apply (auto simp add: LIM_eq)
 apply (drule_tac x = "l/2" in spec, safe, force)
 apply (rule_tac x = s in exI)
 apply (auto simp only: abs_less_iff)
@@ -1495,7 +1496,7 @@
 lemma LIM_fun_less_zero:
      "[| f -- c --> (l::real); l < 0 |]  
       ==> \<exists>r. 0 < r & (\<forall>x::real. x \<noteq> c & \<bar>c - x\<bar> < r --> f x < 0)"
-apply (auto simp add: LIM_def)
+apply (auto simp add: LIM_eq)
 apply (drule_tac x = "-l/2" in spec, safe, force)
 apply (rule_tac x = s in exI)
 apply (auto simp only: abs_less_iff)
--- a/src/HOL/HOL.thy	Mon Jun 01 09:26:28 2009 +0200
+++ b/src/HOL/HOL.thy	Tue Jun 02 12:18:08 2009 +0200
@@ -31,7 +31,7 @@
   ("Tools/recfun_codegen.ML")
 begin
 
-setup {* Intuitionistic.method_setup "iprover" *}
+setup {* Intuitionistic.method_setup @{binding iprover} *}
 
 
 subsection {* Primitive logic *}
--- a/src/HOL/Import/import_package.ML	Mon Jun 01 09:26:28 2009 +0200
+++ b/src/HOL/Import/import_package.ML	Tue Jun 02 12:18:08 2009 +0200
@@ -1,13 +1,12 @@
 (*  Title:      HOL/Import/import_package.ML
-    ID:         $Id$
     Author:     Sebastian Skalberg (TU Muenchen)
 *)
 
 signature IMPORT_PACKAGE =
 sig
-    val import_meth: Method.src -> Proof.context -> Proof.method
+    val debug      : bool ref
+    val import_tac : Proof.context -> string * string -> tactic
     val setup      : theory -> theory
-    val debug      : bool ref
 end
 
 structure ImportData = TheoryDataFun
@@ -25,20 +24,16 @@
 val debug = ref false
 fun message s = if !debug then writeln s else ()
 
-val string_of_thm = PrintMode.setmp [] Display.string_of_thm;
-val string_of_cterm = PrintMode.setmp [] Display.string_of_cterm;
-
-fun import_tac (thyname,thmname) =
+fun import_tac ctxt (thyname, thmname) =
     if ! quick_and_dirty
-    then SkipProof.cheat_tac
+    then SkipProof.cheat_tac (ProofContext.theory_of ctxt)
     else
-     fn thy =>
      fn th =>
         let
-            val sg = Thm.theory_of_thm th
+            val thy = ProofContext.theory_of ctxt
             val prem = hd (prems_of th)
-            val _ = message ("Import_tac: thyname="^thyname^", thmname="^thmname)
-            val _ = message ("Import trying to prove " ^ (string_of_cterm (cterm_of sg prem)))
+            val _ = message ("Import_tac: thyname=" ^ thyname ^ ", thmname=" ^ thmname)
+            val _ = message ("Import trying to prove " ^ Syntax.string_of_term ctxt prem)
             val int_thms = case ImportData.get thy of
                                NONE => fst (Replay.setup_int_thms thyname thy)
                              | SOME a => a
@@ -49,9 +44,9 @@
             val thm = equal_elim rew thm
             val prew = ProofKernel.rewrite_hol4_term prem thy
             val prem' = #2 (Logic.dest_equals (prop_of prew))
-            val _ = message ("Import proved " ^ (string_of_thm thm))
+            val _ = message ("Import proved " ^ Display.string_of_thm thm)
             val thm = ProofKernel.disambiguate_frees thm
-            val _ = message ("Disambiguate: " ^ (string_of_thm thm))
+            val _ = message ("Disambiguate: " ^ Display.string_of_thm thm)
         in
             case Shuffler.set_prop thy prem' [("",thm)] of
                 SOME (_,thm) =>
@@ -67,15 +62,10 @@
               | NONE => (message "import: set_prop didn't succeed"; no_tac th)
         end
 
-val import_meth = Method.simple_args (Args.name -- Args.name)
-                  (fn arg =>
-                   fn ctxt =>
-                      let
-                          val thy = ProofContext.theory_of ctxt
-                      in
-                          SIMPLE_METHOD (import_tac arg thy)
-                      end)
+val setup = Method.setup @{binding import}
+  (Scan.lift (Args.name -- Args.name) >>
+    (fn arg => fn ctxt => SIMPLE_METHOD (import_tac ctxt arg)))
+  "import HOL4 theorem"
 
-val setup = Method.add_method("import",import_meth,"Import HOL4 theorem")
 end
 
--- a/src/HOL/Import/shuffler.ML	Mon Jun 01 09:26:28 2009 +0200
+++ b/src/HOL/Import/shuffler.ML	Tue Jun 02 12:18:08 2009 +0200
@@ -15,10 +15,9 @@
 
     val find_potential: theory -> term -> (string * thm) list
 
-    val gen_shuffle_tac: theory -> bool -> (string * thm) list -> int -> tactic
-
-    val shuffle_tac: (string * thm) list -> int -> tactic
-    val search_tac : (string * thm) list -> int -> tactic
+    val gen_shuffle_tac: Proof.context -> bool -> (string * thm) list -> int -> tactic
+    val shuffle_tac: Proof.context -> thm list -> int -> tactic
+    val search_tac : Proof.context -> int -> tactic
 
     val print_shuffles: theory -> unit
 
@@ -631,8 +630,9 @@
         List.filter (match_consts ignored t) all_thms
     end
 
-fun gen_shuffle_tac thy search thms i st =
+fun gen_shuffle_tac ctxt search thms i st =
     let
+        val thy = ProofContext.theory_of ctxt
         val _ = message ("Shuffling " ^ (string_of_thm st))
         val t = List.nth(prems_of st,i-1)
         val set = set_prop thy t
@@ -646,26 +646,11 @@
                                   else no_tac)) st
     end
 
-fun shuffle_tac thms i st =
-    gen_shuffle_tac (the_context()) false thms i st
-
-fun search_tac thms i st =
-    gen_shuffle_tac (the_context()) true thms i st
+fun shuffle_tac ctxt thms =
+  gen_shuffle_tac ctxt false (map (pair "") thms);
 
-fun shuffle_meth (thms:thm list) ctxt =
-    let
-        val thy = ProofContext.theory_of ctxt
-    in
-        SIMPLE_METHOD' (gen_shuffle_tac thy false (map (pair "") thms))
-    end
-
-fun search_meth ctxt =
-    let
-        val thy = ProofContext.theory_of ctxt
-        val prems = Assumption.all_prems_of ctxt
-    in
-        SIMPLE_METHOD' (gen_shuffle_tac thy true (map (pair "premise") prems))
-    end
+fun search_tac ctxt =
+  gen_shuffle_tac ctxt true (map (pair "premise") (Assumption.all_prems_of ctxt));
 
 fun add_shuffle_rule thm thy =
     let
@@ -680,10 +665,11 @@
 val shuffle_attr = Thm.declaration_attribute (fn th => Context.mapping (add_shuffle_rule th) I);
 
 val setup =
-  Method.add_method ("shuffle_tac",
-    Method.thms_ctxt_args shuffle_meth,"solve goal by shuffling terms around") #>
-  Method.add_method ("search_tac",
-    Method.ctxt_args search_meth,"search for suitable theorems") #>
+  Method.setup @{binding shuffle_tac}
+    (Attrib.thms >> (fn ths => fn ctxt => SIMPLE_METHOD' (shuffle_tac ctxt ths)))
+    "solve goal by shuffling terms around" #>
+  Method.setup @{binding search_tac}
+    (Scan.succeed (SIMPLE_METHOD' o search_tac)) "search for suitable theorems" #>
   add_shuffle_rule weaken #>
   add_shuffle_rule equiv_comm #>
   add_shuffle_rule imp_comm #>
--- a/src/HOL/Integration.thy	Mon Jun 01 09:26:28 2009 +0200
+++ b/src/HOL/Integration.thy	Tue Jun 02 12:18:08 2009 +0200
@@ -11,301 +11,163 @@
 
 text{*We follow John Harrison in formalizing the Gauge integral.*}
 
-definition
-  --{*Partitions and tagged partitions etc.*}
-
-  partition :: "[(real*real),nat => real] => bool" where
-  [code del]: "partition = (%(a,b) D. D 0 = a &
-                         (\<exists>N. (\<forall>n < N. D(n) < D(Suc n)) &
-                              (\<forall>n \<ge> N. D(n) = b)))"
-
-definition
-  psize :: "(nat => real) => nat" where
-  [code del]:"psize D = (SOME N. (\<forall>n < N. D(n) < D(Suc n)) &
-                      (\<forall>n \<ge> N. D(n) = D(N)))"
+subsection {* Gauges *}
 
 definition
-  tpart :: "[(real*real),((nat => real)*(nat =>real))] => bool" where
-  [code del]:"tpart = (%(a,b) (D,p). partition(a,b) D &
-                          (\<forall>n. D(n) \<le> p(n) & p(n) \<le> D(Suc n)))"
+  gauge :: "[real set, real => real] => bool" where
+  [code del]:"gauge E g = (\<forall>x\<in>E. 0 < g(x))"
+
+
+subsection {* Gauge-fine divisions *}
+
+inductive
+  fine :: "[real \<Rightarrow> real, real \<times> real, (real \<times> real \<times> real) list] \<Rightarrow> bool"
+for
+  \<delta> :: "real \<Rightarrow> real"
+where
+  fine_Nil:
+    "fine \<delta> (a, a) []"
+| fine_Cons:
+    "\<lbrakk>fine \<delta> (b, c) D; a < b; a \<le> x; x \<le> b; b - a < \<delta> x\<rbrakk>
+      \<Longrightarrow> fine \<delta> (a, c) ((a, x, b) # D)"
+
+lemmas fine_induct [induct set: fine] =
+  fine.induct [of "\<delta>" "(a,b)" "D" "split P", unfolded split_conv, standard]
+
+lemma fine_single:
+  "\<lbrakk>a < b; a \<le> x; x \<le> b; b - a < \<delta> x\<rbrakk> \<Longrightarrow> fine \<delta> (a, b) [(a, x, b)]"
+by (rule fine_Cons [OF fine_Nil])
+
+lemma fine_append:
+  "\<lbrakk>fine \<delta> (a, b) D; fine \<delta> (b, c) D'\<rbrakk> \<Longrightarrow> fine \<delta> (a, c) (D @ D')"
+by (induct set: fine, simp, simp add: fine_Cons)
+
+lemma fine_imp_le: "fine \<delta> (a, b) D \<Longrightarrow> a \<le> b"
+by (induct set: fine, simp_all)
+
+lemma nonempty_fine_imp_less: "\<lbrakk>fine \<delta> (a, b) D; D \<noteq> []\<rbrakk> \<Longrightarrow> a < b"
+apply (induct set: fine, simp)
+apply (drule fine_imp_le, simp)
+done
+
+lemma empty_fine_imp_eq: "\<lbrakk>fine \<delta> (a, b) D; D = []\<rbrakk> \<Longrightarrow> a = b"
+by (induct set: fine, simp_all)
+
+lemma fine_eq: "fine \<delta> (a, b) D \<Longrightarrow> a = b \<longleftrightarrow> D = []"
+apply (cases "D = []")
+apply (drule (1) empty_fine_imp_eq, simp)
+apply (drule (1) nonempty_fine_imp_less, simp)
+done
 
-  --{*Gauges and gauge-fine divisions*}
+lemma mem_fine:
+  "\<lbrakk>fine \<delta> (a, b) D; (u, x, v) \<in> set D\<rbrakk> \<Longrightarrow> u < v \<and> u \<le> x \<and> x \<le> v"
+by (induct set: fine, simp, force)
+
+lemma mem_fine2: "\<lbrakk>fine \<delta> (a, b) D; (u, z, v) \<in> set D\<rbrakk> \<Longrightarrow> a \<le> u \<and> v \<le> b"
+apply (induct arbitrary: z u v set: fine, auto)
+apply (simp add: fine_imp_le)
+apply (erule order_trans [OF less_imp_le], simp)
+done
+
+lemma mem_fine3: "\<lbrakk>fine \<delta> (a, b) D; (u, z, v) \<in> set D\<rbrakk> \<Longrightarrow> v - u < \<delta> z"
+by (induct arbitrary: z u v set: fine) auto
+
+lemma BOLZANO:
+  fixes P :: "real \<Rightarrow> real \<Rightarrow> bool"
+  assumes 1: "a \<le> b"
+  assumes 2: "\<And>a b c. \<lbrakk>P a b; P b c; a \<le> b; b \<le> c\<rbrakk> \<Longrightarrow> P a c"
+  assumes 3: "\<And>x. \<exists>d>0. \<forall>a b. a \<le> x & x \<le> b & (b-a) < d \<longrightarrow> P a b"
+  shows "P a b"
+apply (subgoal_tac "split P (a,b)", simp)
+apply (rule lemma_BOLZANO [OF _ _ 1])
+apply (clarify, erule (3) 2)
+apply (clarify, rule 3)
+done
 
-definition
-  gauge :: "[real => bool, real => real] => bool" where
-  [code del]:"gauge E g = (\<forall>x. E x --> 0 < g(x))"
+text{*We can always find a division that is fine wrt any gauge*}
+
+lemma fine_exists:
+  assumes "a \<le> b" and "gauge {a..b} \<delta>" shows "\<exists>D. fine \<delta> (a, b) D"
+proof -
+  {
+    fix u v :: real assume "u \<le> v"
+    have "a \<le> u \<Longrightarrow> v \<le> b \<Longrightarrow> \<exists>D. fine \<delta> (u, v) D"
+      apply (induct u v rule: BOLZANO, rule `u \<le> v`)
+       apply (simp, fast intro: fine_append)
+      apply (case_tac "a \<le> x \<and> x \<le> b")
+       apply (rule_tac x="\<delta> x" in exI)
+       apply (rule conjI)
+        apply (simp add: `gauge {a..b} \<delta>` [unfolded gauge_def])
+       apply (clarify, rename_tac u v)
+       apply (case_tac "u = v")
+        apply (fast intro: fine_Nil)
+       apply (subgoal_tac "u < v", fast intro: fine_single, simp)
+      apply (rule_tac x="1" in exI, clarsimp)
+      done
+  }
+  with `a \<le> b` show ?thesis by auto
+qed
+
+
+subsection {* Riemann sum *}
 
 definition
-  fine :: "[real => real, ((nat => real)*(nat => real))] => bool" where
-  [code del]:"fine = (%g (D,p). \<forall>n. n < (psize D) --> D(Suc n) - D(n) < g(p n))"
+  rsum :: "[(real \<times> real \<times> real) list, real \<Rightarrow> real] \<Rightarrow> real" where
+  "rsum D f = (\<Sum>(u, x, v)\<leftarrow>D. f x * (v - u))"
+
+lemma rsum_Nil [simp]: "rsum [] f = 0"
+unfolding rsum_def by simp
 
-  --{*Riemann sum*}
+lemma rsum_Cons [simp]: "rsum ((u, x, v) # D) f = f x * (v - u) + rsum D f"
+unfolding rsum_def by simp
+
+lemma rsum_zero [simp]: "rsum D (\<lambda>x. 0) = 0"
+by (induct D, auto)
 
-definition
-  rsum :: "[((nat=>real)*(nat=>real)),real=>real] => real" where
-  "rsum = (%(D,p) f. \<Sum>n=0..<psize(D). f(p n) * (D(Suc n) - D(n)))"
+lemma rsum_left_distrib: "rsum D f * c = rsum D (\<lambda>x. f x * c)"
+by (induct D, auto simp add: algebra_simps)
+
+lemma rsum_right_distrib: "c * rsum D f = rsum D (\<lambda>x. c * f x)"
+by (induct D, auto simp add: algebra_simps)
 
-  --{*Gauge integrability (definite)*}
+lemma rsum_add: "rsum D (\<lambda>x. f x + g x) =  rsum D f + rsum D g"
+by (induct D, auto simp add: algebra_simps)
+
+
+subsection {* Gauge integrability (definite) *}
 
 definition
   Integral :: "[(real*real),real=>real,real] => bool" where
   [code del]: "Integral = (%(a,b) f k. \<forall>e > 0.
-                               (\<exists>g. gauge(%x. a \<le> x & x \<le> b) g &
-                               (\<forall>D p. tpart(a,b) (D,p) & fine(g)(D,p) -->
-                                         \<bar>rsum(D,p) f - k\<bar> < e)))"
-
-
-lemma psize_unique:
-  assumes 1: "\<forall>n < N. D(n) < D(Suc n)"
-  assumes 2: "\<forall>n \<ge> N. D(n) = D(N)"
-  shows "psize D = N"
-unfolding psize_def
-proof (rule some_equality)
-  show "(\<forall>n<N. D(n) < D(Suc n)) \<and> (\<forall>n\<ge>N. D(n) = D(N))" using prems ..
-next
-  fix M assume "(\<forall>n<M. D(n) < D(Suc n)) \<and> (\<forall>n\<ge>M. D(n) = D(M))"
-  hence 3: "\<forall>n<M. D(n) < D(Suc n)" and 4: "\<forall>n\<ge>M. D(n) = D(M)" by fast+
-  show "M = N"
-  proof (rule linorder_cases)
-    assume "M < N"
-    hence "D(M) < D(Suc M)" by (rule 1 [rule_format])
-    also have "D(Suc M) = D(M)" by (rule 4 [rule_format], simp)
-    finally show "M = N" by simp
-  next
-    assume "N < M"
-    hence "D(N) < D(Suc N)" by (rule 3 [rule_format])
-    also have "D(Suc N) = D(N)" by (rule 2 [rule_format], simp)
-    finally show "M = N" by simp
-  next
-    assume "M = N" thus "M = N" .
-  qed
-qed
-
-lemma partition_zero [simp]: "a = b ==> psize (%n. if n = 0 then a else b) = 0"
-by (rule psize_unique, simp_all)
-
-lemma partition_one [simp]: "a < b ==> psize (%n. if n = 0 then a else b) = 1"
-by (rule psize_unique, simp_all)
-
-lemma partition_single [simp]:
-     "a \<le> b ==> partition(a,b)(%n. if n = 0 then a else b)"
-by (auto simp add: partition_def order_le_less)
-
-lemma partition_lhs: "partition(a,b) D ==> (D(0) = a)"
-by (simp add: partition_def)
-
-lemma partition:
-       "(partition(a,b) D) =
-        ((D 0 = a) &
-         (\<forall>n < psize D. D n < D(Suc n)) &
-         (\<forall>n \<ge> psize D. D n = b))"
-apply (simp add: partition_def)
-apply (rule iffI, clarify)
-apply (subgoal_tac "psize D = N", simp)
-apply (rule psize_unique, assumption, simp)
-apply (simp, rule_tac x="psize D" in exI, simp)
-done
-
-lemma partition_rhs: "partition(a,b) D ==> (D(psize D) = b)"
-by (simp add: partition)
-
-lemma partition_rhs2: "[|partition(a,b) D; psize D \<le> n |] ==> (D n = b)"
-by (simp add: partition)
-
-lemma lemma_partition_lt_gen [rule_format]:
- "partition(a,b) D & m + Suc d \<le> n & n \<le> (psize D) --> D(m) < D(m + Suc d)"
-apply (induct "d", auto simp add: partition)
-apply (blast dest: Suc_le_lessD  intro: less_le_trans order_less_trans)
-done
-
-lemma less_eq_add_Suc: "m < n ==> \<exists>d. n = m + Suc d"
-by (auto simp add: less_iff_Suc_add)
-
-lemma partition_lt_gen:
-     "[|partition(a,b) D; m < n; n \<le> (psize D)|] ==> D(m) < D(n)"
-by (auto dest: less_eq_add_Suc intro: lemma_partition_lt_gen)
-
-lemma partition_lt: "partition(a,b) D ==> n < (psize D) ==> D(0) < D(Suc n)"
-apply (induct "n")
-apply (auto simp add: partition)
-done
-
-lemma partition_le: "partition(a,b) D ==> a \<le> b"
-apply (frule partition [THEN iffD1], safe)
-apply (drule_tac x = "psize D" and P="%n. psize D \<le> n --> ?P n" in spec, safe)
-apply (case_tac "psize D = 0")
-apply (drule_tac [2] n = "psize D - Suc 0" in partition_lt, auto)
-done
-
-lemma partition_gt: "[|partition(a,b) D; n < (psize D)|] ==> D(n) < D(psize D)"
-by (auto intro: partition_lt_gen)
-
-lemma partition_eq: "partition(a,b) D ==> ((a = b) = (psize D = 0))"
-apply (frule partition [THEN iffD1], safe)
-apply (rotate_tac 2)
-apply (drule_tac x = "psize D" in spec)
-apply (rule ccontr)
-apply (drule_tac n = "psize D - Suc 0" in partition_lt)
-apply auto
-done
-
-lemma partition_lb: "partition(a,b) D ==> a \<le> D(r)"
-apply (frule partition [THEN iffD1], safe)
-apply (induct "r")
-apply (cut_tac [2] y = "Suc r" and x = "psize D" in linorder_le_less_linear)
-apply (auto intro: partition_le)
-apply (drule_tac x = r in spec)
-apply arith; 
-done
+                               (\<exists>\<delta>. gauge {a .. b} \<delta> &
+                               (\<forall>D. fine \<delta> (a,b) D -->
+                                         \<bar>rsum D f - k\<bar> < e)))"
 
-lemma partition_lb_lt: "[| partition(a,b) D; psize D ~= 0 |] ==> a < D(Suc n)"
-apply (rule_tac t = a in partition_lhs [THEN subst], assumption)
-apply (cut_tac x = "Suc n" and y = "psize D" in linorder_le_less_linear)
-apply (frule partition [THEN iffD1], safe)
- apply (blast intro: partition_lt less_le_trans)
-apply (rotate_tac 3)
-apply (drule_tac x = "Suc n" in spec)
-apply (erule impE)
-apply (erule less_imp_le)
-apply (frule partition_rhs)
-apply (drule partition_gt[of _ _ _ 0], arith)
-apply (simp (no_asm_simp))
-done
-
-lemma partition_ub: "partition(a,b) D ==> D(r) \<le> b"
-apply (frule partition [THEN iffD1])
-apply (cut_tac x = "psize D" and y = r in linorder_le_less_linear, safe, blast)
-apply (subgoal_tac "\<forall>x. D ((psize D) - x) \<le> b")
-apply (rotate_tac 4)
-apply (drule_tac x = "psize D - r" in spec)
-apply (subgoal_tac "psize D - (psize D - r) = r")
-apply simp
-apply arith
-apply safe
-apply (induct_tac "x")
-apply (simp (no_asm), blast)
-apply (case_tac "psize D - Suc n = 0")
-apply (erule_tac V = "\<forall>n. psize D \<le> n --> D n = b" in thin_rl)
-apply (simp (no_asm_simp) add: partition_le)
-apply (rule order_trans)
- prefer 2 apply assumption
-apply (subgoal_tac "psize D - n = Suc (psize D - Suc n)")
- prefer 2 apply arith
-apply (drule_tac x = "psize D - Suc n" in spec, simp) 
-done
-
-lemma partition_ub_lt: "[| partition(a,b) D; n < psize D |] ==> D(n) < b"
-by (blast intro: partition_rhs [THEN subst] partition_gt)
-
-lemma lemma_partition_append1:
-     "[| partition (a, b) D1; partition (b, c) D2 |]
-       ==> (\<forall>n < psize D1 + psize D2.
-             (if n < psize D1 then D1 n else D2 (n - psize D1))
-             < (if Suc n < psize D1 then D1 (Suc n)
-                else D2 (Suc n - psize D1))) &
-         (\<forall>n \<ge> psize D1 + psize D2.
-             (if n < psize D1 then D1 n else D2 (n - psize D1)) =
-             (if psize D1 + psize D2 < psize D1 then D1 (psize D1 + psize D2)
-              else D2 (psize D1 + psize D2 - psize D1)))"
-apply (auto intro: partition_lt_gen)
-apply (subgoal_tac "psize D1 = Suc n")
-apply (auto intro!: partition_lt_gen simp add: partition_lhs partition_ub_lt)
-apply (auto intro!: partition_rhs2 simp add: partition_rhs
-            split: nat_diff_split)
-done
-
-lemma lemma_psize1:
-     "[| partition (a, b) D1; partition (b, c) D2; N < psize D1 |]
-      ==> D1(N) < D2 (psize D2)"
-apply (rule_tac y = "D1 (psize D1)" in order_less_le_trans)
-apply (erule partition_gt)
-apply (auto simp add: partition_rhs partition_le)
-done
-
-lemma lemma_partition_append2:
-     "[| partition (a, b) D1; partition (b, c) D2 |]
-      ==> psize (%n. if n < psize D1 then D1 n else D2 (n - psize D1)) =
-          psize D1 + psize D2"
-apply (rule psize_unique)
-apply (erule (1) lemma_partition_append1 [THEN conjunct1])
-apply (erule (1) lemma_partition_append1 [THEN conjunct2])
-done
-
-lemma tpart_eq_lhs_rhs: "[|psize D = 0; tpart(a,b) (D,p)|] ==> a = b"
-by (auto simp add: tpart_def partition_eq)
-
-lemma tpart_partition: "tpart(a,b) (D,p) ==> partition(a,b) D"
-by (simp add: tpart_def)
-
-lemma partition_append:
-     "[| tpart(a,b) (D1,p1); fine(g) (D1,p1);
-         tpart(b,c) (D2,p2); fine(g) (D2,p2) |]
-       ==> \<exists>D p. tpart(a,c) (D,p) & fine(g) (D,p)"
-apply (rule_tac x = "%n. if n < psize D1 then D1 n else D2 (n - psize D1)"
-       in exI)
-apply (rule_tac x = "%n. if n < psize D1 then p1 n else p2 (n - psize D1)"
-       in exI)
-apply (case_tac "psize D1 = 0")
-apply (auto dest: tpart_eq_lhs_rhs)
- prefer 2
-apply (simp add: fine_def
-                 lemma_partition_append2 [OF tpart_partition tpart_partition])
-  --{*But must not expand @{term fine} in other subgoals*}
-apply auto
-apply (subgoal_tac "psize D1 = Suc n")
- prefer 2 apply arith
-apply (drule tpart_partition [THEN partition_rhs])
-apply (drule tpart_partition [THEN partition_lhs])
-apply (auto split: nat_diff_split)
-apply (auto simp add: tpart_def)
-defer 1
- apply (subgoal_tac "psize D1 = Suc n")
-  prefer 2 apply arith
- apply (drule partition_rhs)
- apply (drule partition_lhs, auto)
-apply (simp split: nat_diff_split)
-apply (subst partition) 
-apply (subst (1 2) lemma_partition_append2, assumption+)
-apply (rule conjI) 
-apply (simp add: partition_lhs)
-apply (drule lemma_partition_append1)
-apply assumption; 
-apply (simp add: partition_rhs)
-done
-
-
-text{*We can always find a division that is fine wrt any gauge*}
-
-lemma partition_exists:
-     "[| a \<le> b; gauge(%x. a \<le> x & x \<le> b) g |]
-      ==> \<exists>D p. tpart(a,b) (D,p) & fine g (D,p)"
-apply (cut_tac P = "%(u,v). a \<le> u & v \<le> b --> 
-                   (\<exists>D p. tpart (u,v) (D,p) & fine (g) (D,p))" 
-       in lemma_BOLZANO2)
-apply safe
-apply (blast intro: order_trans)+
-apply (auto intro: partition_append)
-apply (case_tac "a \<le> x & x \<le> b")
-apply (rule_tac [2] x = 1 in exI, auto)
-apply (rule_tac x = "g x" in exI)
-apply (auto simp add: gauge_def)
-apply (rule_tac x = "%n. if n = 0 then aa else ba" in exI)
-apply (rule_tac x = "%n. if n = 0 then x else ba" in exI)
-apply (auto simp add: tpart_def fine_def)
+lemma Integral_def2:
+  "Integral = (%(a,b) f k. \<forall>e>0. (\<exists>\<delta>. gauge {a..b} \<delta> &
+                               (\<forall>D. fine \<delta> (a,b) D -->
+                                         \<bar>rsum D f - k\<bar> \<le> e)))"
+unfolding Integral_def
+apply (safe intro!: ext)
+apply (fast intro: less_imp_le)
+apply (drule_tac x="e/2" in spec)
+apply force
 done
 
 text{*Lemmas about combining gauges*}
 
 lemma gauge_min:
      "[| gauge(E) g1; gauge(E) g2 |]
-      ==> gauge(E) (%x. if g1(x) < g2(x) then g1(x) else g2(x))"
+      ==> gauge(E) (%x. min (g1(x)) (g2(x)))"
 by (simp add: gauge_def)
 
 lemma fine_min:
-      "fine (%x. if g1(x) < g2(x) then g1(x) else g2(x)) (D,p)
-       ==> fine(g1) (D,p) & fine(g2) (D,p)"
-by (auto simp add: fine_def split: split_if_asm)
-
+      "fine (%x. min (g1(x)) (g2(x))) (a,b) D
+       ==> fine(g1) (a,b) D & fine(g2) (a,b) D"
+apply (erule fine.induct)
+apply (simp add: fine_Nil)
+apply (simp add: fine_Cons)
+done
 
 text{*The integral is unique if it exists*}
 
@@ -315,12 +177,12 @@
 apply (drule_tac x = "\<bar>k1 - k2\<bar> /2" in spec)+
 apply auto
 apply (drule gauge_min, assumption)
-apply (drule_tac g = "%x. if g x < ga x then g x else ga x" 
-       in partition_exists, assumption, auto)
+apply (drule_tac \<delta> = "%x. min (\<delta> x) (\<delta>' x)"
+       in fine_exists, assumption, auto)
 apply (drule fine_min)
 apply (drule spec)+
 apply auto
-apply (subgoal_tac "\<bar>(rsum (D,p) f - k2) - (rsum (D,p) f - k1)\<bar> < \<bar>k1 - k2\<bar>")
+apply (subgoal_tac "\<bar>(rsum D f - k2) - (rsum D f - k1)\<bar> < \<bar>k1 - k2\<bar>")
 apply arith
 apply (drule add_strict_mono, assumption)
 apply (auto simp only: left_distrib [symmetric] mult_2_right [symmetric] 
@@ -330,65 +192,58 @@
 lemma Integral_zero [simp]: "Integral(a,a) f 0"
 apply (auto simp add: Integral_def)
 apply (rule_tac x = "%x. 1" in exI)
-apply (auto dest: partition_eq simp add: gauge_def tpart_def rsum_def)
+apply (auto dest: fine_eq simp add: gauge_def rsum_def)
 done
 
-lemma sumr_partition_eq_diff_bounds [simp]:
-     "(\<Sum>n=0..<m. D (Suc n) - D n::real) = D(m) - D 0"
-by (induct "m", auto)
+lemma fine_rsum_const: "fine \<delta> (a,b) D \<Longrightarrow> rsum D (\<lambda>x. c) = (c * (b - a))"
+unfolding rsum_def
+by (induct set: fine, auto simp add: algebra_simps)
 
 lemma Integral_eq_diff_bounds: "a \<le> b ==> Integral(a,b) (%x. 1) (b - a)"
-apply (auto simp add: order_le_less rsum_def Integral_def)
+apply (cases "a = b", simp)
+apply (simp add: Integral_def, clarify)
 apply (rule_tac x = "%x. b - a" in exI)
-apply (auto simp add: gauge_def abs_less_iff tpart_def partition)
+apply (rule conjI, simp add: gauge_def)
+apply (clarify)
+apply (subst fine_rsum_const, assumption, simp)
 done
 
 lemma Integral_mult_const: "a \<le> b ==> Integral(a,b) (%x. c)  (c*(b - a))"
-apply (auto simp add: order_le_less rsum_def Integral_def)
+apply (cases "a = b", simp)
+apply (simp add: Integral_def, clarify)
 apply (rule_tac x = "%x. b - a" in exI)
-apply (auto simp add: setsum_right_distrib [symmetric] gauge_def abs_less_iff 
-               right_diff_distrib [symmetric] partition tpart_def)
+apply (rule conjI, simp add: gauge_def)
+apply (clarify)
+apply (subst fine_rsum_const, assumption, simp)
 done
 
 lemma Integral_mult:
      "[| a \<le> b; Integral(a,b) f k |] ==> Integral(a,b) (%x. c * f x) (c * k)"
 apply (auto simp add: order_le_less 
             dest: Integral_unique [OF order_refl Integral_zero])
-apply (auto simp add: rsum_def Integral_def setsum_right_distrib[symmetric] mult_assoc)
-apply (rule_tac a2 = c in abs_ge_zero [THEN order_le_imp_less_or_eq, THEN disjE])
- prefer 2 apply force
-apply (drule_tac x = "e/abs c" in spec, auto)
-apply (simp add: zero_less_mult_iff divide_inverse)
-apply (rule exI, auto)
-apply (drule spec)+
-apply auto
-apply (rule_tac z1 = "inverse (abs c)" in real_mult_less_iff1 [THEN iffD1])
-apply (auto simp add: abs_mult divide_inverse [symmetric] right_diff_distrib [symmetric])
+apply (auto simp add: Integral_def setsum_right_distrib[symmetric] mult_assoc)
+apply (case_tac "c = 0", force)
+apply (drule_tac x = "e/abs c" in spec)
+apply (simp add: divide_pos_pos)
+apply clarify
+apply (rule_tac x="\<delta>" in exI, clarify)
+apply (drule_tac x="D" in spec, clarify)
+apply (simp add: pos_less_divide_eq abs_mult [symmetric]
+                 algebra_simps rsum_right_distrib)
 done
 
+
 text{*Fundamental theorem of calculus (Part I)*}
 
 text{*"Straddle Lemma" : Swartz and Thompson: AMM 95(7) 1988 *}
 
-lemma choiceP: "\<forall>x. P(x) --> (\<exists>y. Q x y) ==> \<exists>f. (\<forall>x. P(x) --> Q x (f x))" 
-by (insert bchoice [of "Collect P" Q], simp) 
-
-(*UNUSED
-lemma choice2: "\<forall>x. (\<exists>y. R(y) & (\<exists>z. Q x y z)) ==>
-      \<exists>f fa. (\<forall>x. R(f x) & Q x (f x) (fa x))"
-*)
-
-
-(* new simplifications e.g. (y < x/n) = (y * n < x) are a real nuisance
-   they break the original proofs and make new proofs longer!*)
 lemma strad1:
-       "\<lbrakk>\<forall>xa::real. xa \<noteq> x \<and> \<bar>xa - x\<bar> < s \<longrightarrow>
-             \<bar>(f xa - f x) / (xa - x) - f' x\<bar> * 2 < e;
-        0 < e; a \<le> x; x \<le> b; 0 < s\<rbrakk>
-       \<Longrightarrow> \<forall>z. \<bar>z - x\<bar> < s -->\<bar>f z - f x - f' x * (z - x)\<bar> * 2 \<le> e * \<bar>z - x\<bar>"
-apply auto
-apply (case_tac "0 < \<bar>z - x\<bar>")
- prefer 2 apply (simp add: zero_less_abs_iff)
+       "\<lbrakk>\<forall>z::real. z \<noteq> x \<and> \<bar>z - x\<bar> < s \<longrightarrow>
+             \<bar>(f z - f x) / (z - x) - f' x\<bar> < e/2;
+        0 < s; 0 < e; a \<le> x; x \<le> b\<rbrakk>
+       \<Longrightarrow> \<forall>z. \<bar>z - x\<bar> < s -->\<bar>f z - f x - f' x * (z - x)\<bar> \<le> e/2 * \<bar>z - x\<bar>"
+apply clarify
+apply (case_tac "z = x", simp)
 apply (drule_tac x = z in spec)
 apply (rule_tac z1 = "\<bar>inverse (z - x)\<bar>" 
        in real_mult_le_cancel_iff2 [THEN iffD1])
@@ -405,71 +260,82 @@
 done
 
 lemma lemma_straddle:
-     "[| \<forall>x. a \<le> x & x \<le> b --> DERIV f x :> f'(x); 0 < e |]
-      ==> \<exists>g. gauge(%x. a \<le> x & x \<le> b) g &
+  assumes f': "\<forall>x. a \<le> x & x \<le> b --> DERIV f x :> f'(x)" and "0 < e"
+  shows "\<exists>g. gauge {a..b} g &
                 (\<forall>x u v. a \<le> u & u \<le> x & x \<le> v & v \<le> b & (v - u) < g(x)
                   --> \<bar>(f(v) - f(u)) - (f'(x) * (v - u))\<bar> \<le> e * (v - u))"
-apply (simp add: gauge_def)
-apply (subgoal_tac "\<forall>x. a \<le> x & x \<le> b --> 
+proof -
+  have "\<forall>x\<in>{a..b}.
         (\<exists>d > 0. \<forall>u v. u \<le> x & x \<le> v & (v - u) < d --> 
-                       \<bar>(f (v) - f (u)) - (f' (x) * (v - u))\<bar> \<le> e * (v - u))")
-apply (drule choiceP, auto)
-apply (drule spec, auto)
-apply (auto simp add: DERIV_iff2 LIM_def)
-apply (drule_tac x = "e/2" in spec, auto)
-apply (frule strad1, assumption+)
-apply (rule_tac x = s in exI, auto)
-apply (rule_tac x = u and y = v in linorder_cases, auto)
-apply (rule_tac y = "\<bar>(f (v) - f (x)) - (f' (x) * (v - x))\<bar> + 
-                     \<bar>(f (x) - f (u)) - (f' (x) * (x - u))\<bar>"
-       in order_trans)
-apply (rule abs_triangle_ineq [THEN [2] order_trans])
-apply (simp add: right_diff_distrib)
-apply (rule_tac t = "e* (v - u)" in real_sum_of_halves [THEN subst])
-apply (rule add_mono)
-apply (rule_tac y = "(e/2) * \<bar>v - x\<bar>" in order_trans)
- prefer 2 apply simp
-apply (erule_tac [!] V= "\<forall>x'. x' ~= x & \<bar>x' - x\<bar> < s --> ?P x'" in thin_rl)
-apply (drule_tac x = v in spec, simp add: times_divide_eq)
-apply (drule_tac x = u in spec, auto)
-apply (subgoal_tac "\<bar>f u - f x - f' x * (u - x)\<bar> = \<bar>f x - f u - f' x * (x - u)\<bar>")
-apply (rule order_trans)
-apply (auto simp add: abs_le_iff)
-apply (simp add: right_diff_distrib)
-done
+                       \<bar>(f(v) - f(u)) - (f'(x) * (v - u))\<bar> \<le> e * (v - u))"
+  proof (clarsimp)
+    fix x :: real assume "a \<le> x" and "x \<le> b"
+    with f' have "DERIV f x :> f'(x)" by simp
+    then have "\<forall>r>0. \<exists>s>0. \<forall>z. z \<noteq> x \<and> \<bar>z - x\<bar> < s \<longrightarrow> \<bar>(f z - f x) / (z - x) - f' x\<bar> < r"
+      by (simp add: DERIV_iff2 LIM_eq)
+    with `0 < e` obtain s
+    where "\<forall>z. z \<noteq> x \<and> \<bar>z - x\<bar> < s \<longrightarrow> \<bar>(f z - f x) / (z - x) - f' x\<bar> < e/2" and "0 < s"
+      by (drule_tac x="e/2" in spec, auto)
+    then have strad [rule_format]:
+        "\<forall>z. \<bar>z - x\<bar> < s --> \<bar>f z - f x - f' x * (z - x)\<bar> \<le> e/2 * \<bar>z - x\<bar>"
+      using `0 < e` `a \<le> x` `x \<le> b` by (rule strad1)
+    show "\<exists>d>0. \<forall>u v. u \<le> x \<and> x \<le> v \<and> v - u < d \<longrightarrow> \<bar>f v - f u - f' x * (v - u)\<bar> \<le> e * (v - u)"
+    proof (safe intro!: exI)
+      show "0 < s" by fact
+    next
+      fix u v :: real assume "u \<le> x" and "x \<le> v" and "v - u < s"
+      have "\<bar>f v - f u - f' x * (v - u)\<bar> =
+            \<bar>(f v - f x - f' x * (v - x)) + (f x - f u - f' x * (x - u))\<bar>"
+        by (simp add: right_diff_distrib)
+      also have "\<dots> \<le> \<bar>f v - f x - f' x * (v - x)\<bar> + \<bar>f x - f u - f' x * (x - u)\<bar>"
+        by (rule abs_triangle_ineq)
+      also have "\<dots> = \<bar>f v - f x - f' x * (v - x)\<bar> + \<bar>f u - f x - f' x * (u - x)\<bar>"
+        by (simp add: right_diff_distrib)
+      also have "\<dots> \<le> (e/2) * \<bar>v - x\<bar> + (e/2) * \<bar>u - x\<bar>"
+        using `u \<le> x` `x \<le> v` `v - u < s` by (intro add_mono strad, simp_all)
+      also have "\<dots> \<le> e * (v - u) / 2 + e * (v - u) / 2"
+        using `u \<le> x` `x \<le> v` `0 < e` by (intro add_mono, simp_all)
+      also have "\<dots> = e * (v - u)"
+        by simp
+      finally show "\<bar>f v - f u - f' x * (v - u)\<bar> \<le> e * (v - u)" .
+    qed
+  qed
+  thus ?thesis
+    by (simp add: gauge_def) (drule bchoice, auto)
+qed
+
+lemma fine_listsum_eq_diff:
+  fixes f :: "real \<Rightarrow> real"
+  shows "fine \<delta> (a, b) D \<Longrightarrow> (\<Sum>(u, x, v)\<leftarrow>D. f v - f u) = f b - f a"
+by (induct set: fine) simp_all
 
 lemma FTC1: "[|a \<le> b; \<forall>x. a \<le> x & x \<le> b --> DERIV f x :> f'(x) |]
              ==> Integral(a,b) f' (f(b) - f(a))"
-apply (drule order_le_imp_less_or_eq, auto) 
-apply (auto simp add: Integral_def)
-apply (rule ccontr)
-apply (subgoal_tac "\<forall>e > 0. \<exists>g. gauge (%x. a \<le> x & x \<le> b) g & (\<forall>D p. tpart (a, b) (D, p) & fine g (D, p) --> \<bar>rsum (D, p) f' - (f b - f a)\<bar> \<le> e)")
-apply (rotate_tac 3)
-apply (drule_tac x = "e/2" in spec, auto)
-apply (drule spec, auto)
-apply ((drule spec)+, auto)
-apply (drule_tac e = "ea/ (b - a)" in lemma_straddle)
-apply (auto simp add: zero_less_divide_iff)
-apply (rule exI)
-apply (auto simp add: tpart_def rsum_def)
-apply (subgoal_tac "(\<Sum>n=0..<psize D. f(D(Suc n)) - f(D n)) = f b - f a")
- prefer 2
- apply (cut_tac D = "%n. f (D n)" and m = "psize D"
-        in sumr_partition_eq_diff_bounds)
- apply (simp add: partition_lhs partition_rhs)
-apply (drule sym, simp)
-apply (simp (no_asm) add: setsum_subtractf[symmetric])
-apply (rule setsum_abs [THEN order_trans])
-apply (subgoal_tac "ea = (\<Sum>n=0..<psize D. (ea / (b - a)) * (D (Suc n) - (D n)))")
-apply (simp add: abs_minus_commute)
-apply (rule_tac t = ea in ssubst, assumption)
-apply (rule setsum_mono)
-apply (rule_tac [2] setsum_right_distrib [THEN subst])
-apply (auto simp add: partition_rhs partition_lhs partition_lb partition_ub
-          fine_def)
+ apply (drule order_le_imp_less_or_eq, auto)
+ apply (auto simp add: Integral_def2)
+ apply (drule_tac e = "e / (b - a)" in lemma_straddle)
+  apply (simp add: divide_pos_pos)
+ apply clarify
+ apply (rule_tac x="g" in exI, clarify)
+ apply (clarsimp simp add: rsum_def)
+ apply (frule fine_listsum_eq_diff [where f=f])
+ apply (erule subst)
+ apply (subst listsum_subtractf [symmetric])
+ apply (rule listsum_abs [THEN order_trans])
+ apply (subst map_compose [symmetric, unfolded o_def])
+ apply (subgoal_tac "e = (\<Sum>(u, x, v)\<leftarrow>D. (e / (b - a)) * (v - u))")
+  apply (erule ssubst)
+  apply (simp add: abs_minus_commute)
+  apply (rule listsum_mono)
+  apply (clarify, rename_tac u x v)
+  apply ((drule spec)+, erule mp)
+  apply (simp add: mem_fine mem_fine2 mem_fine3)
+ apply (frule fine_listsum_eq_diff [where f="\<lambda>x. x"])
+ apply (simp only: split_def)
+ apply (subst listsum_const_mult)
+ apply simp
 done
 
-
 lemma Integral_subst: "[| Integral(a,b) f k1; k2=k1 |] ==> Integral(a,b) f k2"
 by simp
 
@@ -485,320 +351,40 @@
 apply (drule_tac [3] ?k2.0 = "f c - f b" in Integral_unique, auto)
 done
 
-lemma partition_psize_Least:
-     "partition(a,b) D ==> psize D = (LEAST n. D(n) = b)"
-apply (auto intro!: Least_equality [symmetric] partition_rhs)
-apply (auto dest: partition_ub_lt simp add: linorder_not_less [symmetric])
-done
-
-lemma lemma_partition_bounded: "partition (a, c) D ==> ~ (\<exists>n. c < D(n))"
-apply safe
-apply (drule_tac r = n in partition_ub, auto)
-done
-
-lemma lemma_partition_eq:
-     "partition (a, c) D ==> D = (%n. if D n < c then D n else c)"
-apply (rule ext, auto)
-apply (auto dest!: lemma_partition_bounded)
-apply (drule_tac x = n in spec, auto)
-done
-
-lemma lemma_partition_eq2:
-     "partition (a, c) D ==> D = (%n. if D n \<le> c then D n else c)"
-apply (rule ext, auto)
-apply (auto dest!: lemma_partition_bounded)
-apply (drule_tac x = n in spec, auto)
-done
-
-lemma partition_lt_Suc:
-     "[| partition(a,b) D; n < psize D |] ==> D n < D (Suc n)"
-by (auto simp add: partition)
-
-lemma tpart_tag_eq: "tpart(a,c) (D,p) ==> p = (%n. if D n < c then p n else c)"
-apply (rule ext)
-apply (auto simp add: tpart_def)
-apply (drule linorder_not_less [THEN iffD1])
-apply (drule_tac r = "Suc n" in partition_ub)
-apply (drule_tac x = n in spec, auto)
-done
-
-subsection{*Lemmas for Additivity Theorem of Gauge Integral*}
-
-lemma lemma_additivity1:
-     "[| a \<le> D n; D n < b; partition(a,b) D |] ==> n < psize D"
-by (auto simp add: partition linorder_not_less [symmetric])
-
-lemma lemma_additivity2: "[| a \<le> D n; partition(a,D n) D |] ==> psize D \<le> n"
-apply (rule ccontr, drule not_leE)
-apply (frule partition [THEN iffD1], safe)
-apply (frule_tac r = "Suc n" in partition_ub)
-apply (auto dest!: spec)
-done
-
-lemma partition_eq_bound:
-     "[| partition(a,b) D; psize D < m |] ==> D(m) = D(psize D)"
-by (auto simp add: partition)
-
-lemma partition_ub2: "[| partition(a,b) D; psize D < m |] ==> D(r) \<le> D(m)"
-by (simp add: partition partition_ub)
-
-lemma tag_point_eq_partition_point:
-    "[| tpart(a,b) (D,p); psize D \<le> m |] ==> p(m) = D(m)"
-apply (simp add: tpart_def, auto)
-apply (drule_tac x = m in spec)
-apply (auto simp add: partition_rhs2)
-done
-
-lemma partition_lt_cancel: "[| partition(a,b) D; D m < D n |] ==> m < n"
-apply (cut_tac less_linear [of n "psize D"], auto)
-apply (cut_tac less_linear [of m n])
-apply (cut_tac less_linear [of m "psize D"])
-apply (auto dest: partition_gt)
-apply (drule_tac n = m in partition_lt_gen, auto)
-apply (frule partition_eq_bound)
-apply (drule_tac [2] partition_gt, auto)
-apply (metis linear not_less partition_rhs partition_rhs2)
-apply (metis lemma_additivity1 order_less_trans partition_eq_bound partition_lb partition_rhs)
-done
-
-lemma lemma_additivity4_psize_eq:
-     "[| a \<le> D n; D n < b; partition (a, b) D |]
-      ==> psize (%x. if D x < D n then D(x) else D n) = n"
-apply (frule (2) lemma_additivity1)
-apply (rule psize_unique, auto)
-apply (erule partition_lt_Suc, erule (1) less_trans)
-apply (erule notE)
-apply (erule (1) partition_lt_gen, erule less_imp_le)
-apply (drule (1) partition_lt_cancel, simp)
-done
-
-lemma lemma_psize_left_less_psize:
-     "partition (a, b) D
-      ==> psize (%x. if D x < D n then D(x) else D n) \<le> psize D"
-apply (frule_tac r = n in partition_ub)
-apply (drule_tac x = "D n" in order_le_imp_less_or_eq)
-apply (auto simp add: lemma_partition_eq [symmetric])
-apply (frule_tac r = n in partition_lb)
-apply (drule (2) lemma_additivity4_psize_eq)  
-apply (rule ccontr, auto)
-apply (frule_tac not_leE [THEN [2] partition_eq_bound])
-apply (auto simp add: partition_rhs)
-done
-
-lemma lemma_psize_left_less_psize2:
-     "[| partition(a,b) D; na < psize (%x. if D x < D n then D(x) else D n) |]
-      ==> na < psize D"
-by (erule lemma_psize_left_less_psize [THEN [2] less_le_trans])
-
-
-lemma lemma_additivity3:
-     "[| partition(a,b) D; D na < D n; D n < D (Suc na);
-         n < psize D |]
-      ==> False"
-by (metis not_less_eq partition_lt_cancel real_of_nat_less_iff)
-
-
-lemma psize_const [simp]: "psize (%x. k) = 0"
-by (auto simp add: psize_def)
-
-lemma lemma_additivity3a:
-     "[| partition(a,b) D; D na < D n; D n < D (Suc na);
-         na < psize D |]
-      ==> False"
-apply (frule_tac m = n in partition_lt_cancel)
-apply (auto intro: lemma_additivity3)
-done
-
-lemma better_lemma_psize_right_eq1:
-     "[| partition(a,b) D; D n < b |] ==> psize (%x. D (x + n)) \<le> psize D - n"
-apply (simp add: psize_def [of "(%x. D (x + n))"]);
-apply (rule_tac a = "psize D - n" in someI2, auto)
-  apply (simp add: partition less_diff_conv)
- apply (simp add: le_diff_conv partition_rhs2 split: nat_diff_split)
-apply (drule_tac x = "psize D - n" in spec, auto)
-apply (frule partition_rhs, safe)
-apply (frule partition_lt_cancel, assumption)
-apply (drule partition [THEN iffD1], safe)
-apply (subgoal_tac "~ D (psize D - n + n) < D (Suc (psize D - n + n))")
- apply blast
-apply (drule_tac x = "Suc (psize D)" and P="%n. ?P n \<longrightarrow> D n = D (psize D)"
-       in spec)
-apply simp
-done
-
-lemma psize_le_n: "partition (a, D n) D ==> psize D \<le> n" 
-apply (rule ccontr, drule not_leE)
-apply (frule partition_lt_Suc, assumption)
-apply (frule_tac r = "Suc n" in partition_ub, auto)
-done
-
-lemma better_lemma_psize_right_eq1a:
-     "partition(a,D n) D ==> psize (%x. D (x + n)) \<le> psize D - n"
-apply (simp add: psize_def [of "(%x. D (x + n))"]);
-apply (rule_tac a = "psize D - n" in someI2, auto)
-  apply (simp add: partition less_diff_conv)
- apply (simp add: le_diff_conv)
-apply (case_tac "psize D \<le> n")
-  apply (force intro: partition_rhs2)
- apply (simp add: partition linorder_not_le)
-apply (rule ccontr, drule not_leE)
-apply (frule psize_le_n)
-apply (drule_tac x = "psize D - n" in spec, simp)
-apply (drule partition [THEN iffD1], safe)
-apply (drule_tac x = "Suc n" and P="%na. ?s \<le> na \<longrightarrow> D na = D n" in spec, auto)
-done
-
-lemma better_lemma_psize_right_eq:
-     "partition(a,b) D ==> psize (%x. D (x + n)) \<le> psize D - n"
-apply (frule_tac r1 = n in partition_ub [THEN order_le_imp_less_or_eq])
-apply (blast intro: better_lemma_psize_right_eq1a better_lemma_psize_right_eq1)
-done
-
-lemma lemma_psize_right_eq1:
-     "[| partition(a,b) D; D n < b |] ==> psize (%x. D (x + n)) \<le> psize D"
-apply (simp add: psize_def [of "(%x. D (x + n))"])
-apply (rule_tac a = "psize D - n" in someI2, auto)
-  apply (simp add: partition less_diff_conv)
- apply (subgoal_tac "n \<le> psize D")
-  apply (simp add: partition le_diff_conv)
- apply (rule ccontr, drule not_leE)
- apply (drule_tac less_imp_le [THEN [2] partition_rhs2], assumption, simp)
-apply (drule_tac x = "psize D" in spec)
-apply (simp add: partition)
-done
-
-(* should be combined with previous theorem; also proof has redundancy *)
-lemma lemma_psize_right_eq1a:
-     "partition(a,D n) D ==> psize (%x. D (x + n)) \<le> psize D"
-apply (simp add: psize_def [of "(%x. D (x + n))"]);
-apply (rule_tac a = "psize D - n" in someI2, auto)
-  apply (simp add: partition less_diff_conv)
- apply (case_tac "psize D \<le> n")
-  apply (force intro: partition_rhs2 simp add: le_diff_conv)
- apply (simp add: partition le_diff_conv)
-apply (rule ccontr, drule not_leE)
-apply (drule_tac x = "psize D" in spec)
-apply (simp add: partition)
-done
-
-lemma lemma_psize_right_eq:
-     "[| partition(a,b) D |] ==> psize (%x. D (x + n)) \<le> psize D"
-apply (frule_tac r1 = n in partition_ub [THEN order_le_imp_less_or_eq])
-apply (blast intro: lemma_psize_right_eq1a lemma_psize_right_eq1)
-done
-
-lemma tpart_left1:
-     "[| a \<le> D n; tpart (a, b) (D, p) |]
-      ==> tpart(a, D n) (%x. if D x < D n then D(x) else D n,
-          %x. if D x < D n then p(x) else D n)"
-apply (frule_tac r = n in tpart_partition [THEN partition_ub])
-apply (drule_tac x = "D n" in order_le_imp_less_or_eq)
-apply (auto simp add: tpart_partition [THEN lemma_partition_eq, symmetric] tpart_tag_eq [symmetric])
-apply (frule_tac tpart_partition [THEN [3] lemma_additivity1])
-apply (auto simp add: tpart_def)
-apply (drule_tac [2] linorder_not_less [THEN iffD1, THEN order_le_imp_less_or_eq], auto)
-  prefer 3 apply (drule_tac x=na in spec, arith)
- prefer 2 apply (blast dest: lemma_additivity3)
-apply (frule (2) lemma_additivity4_psize_eq)
-apply (rule partition [THEN iffD2])
-apply (frule partition [THEN iffD1])
-apply safe 
-apply (auto simp add: partition_lt_gen)  
-apply (drule (1) partition_lt_cancel, arith)
-done
-
-lemma fine_left1:
-     "[| a \<le> D n; tpart (a, b) (D, p); gauge (%x. a \<le> x & x \<le> D n) g;
-         fine (%x. if x < D n then min (g x) ((D n - x)/ 2)
-                 else if x = D n then min (g (D n)) (ga (D n))
-                      else min (ga x) ((x - D n)/ 2)) (D, p) |]
-      ==> fine g
-           (%x. if D x < D n then D(x) else D n,
-            %x. if D x < D n then p(x) else D n)"
-apply (auto simp add: fine_def tpart_def gauge_def)
-apply (frule_tac [!] na=na in lemma_psize_left_less_psize2)
-apply (drule_tac [!] x = na in spec, auto)
-apply (drule_tac [!] x = na in spec, auto)
-apply (auto dest: lemma_additivity3a simp add: split_if_asm)
-done
-
-lemma tpart_right1:
-     "[| a \<le> D n; tpart (a, b) (D, p) |]
-      ==> tpart(D n, b) (%x. D(x + n),%x. p(x + n))"
-apply (simp add: tpart_def partition_def, safe)
-apply (rule_tac x = "N - n" in exI, auto)
-done
-
-lemma fine_right1:
-     "[| a \<le> D n; tpart (a, b) (D, p); gauge (%x. D n \<le> x & x \<le> b) ga;
-         fine (%x. if x < D n then min (g x) ((D n - x)/ 2)
-                 else if x = D n then min (g (D n)) (ga (D n))
-                      else min (ga x) ((x - D n)/ 2)) (D, p) |]
-      ==> fine ga (%x. D(x + n),%x. p(x + n))"
-apply (auto simp add: fine_def gauge_def)
-apply (drule_tac x = "na + n" in spec)
-apply (frule_tac n = n in tpart_partition [THEN better_lemma_psize_right_eq], auto)
-apply (simp add: tpart_def, safe)
-apply (subgoal_tac "D n \<le> p (na + n)")
-apply (drule_tac y = "p (na + n)" in order_le_imp_less_or_eq)
-apply safe
-apply (simp split: split_if_asm, simp)
-apply (drule less_le_trans, assumption)
-apply (rotate_tac 5)
-apply (drule_tac x = "na + n" in spec, safe)
-apply (rule_tac y="D (na + n)" in order_trans)
-apply (case_tac "na = 0", auto)
-apply (erule partition_lt_gen [THEN order_less_imp_le])
-apply arith
-apply arith
-done
-
-lemma rsum_add: "rsum (D, p) (%x. f x + g x) =  rsum (D, p) f + rsum(D, p) g"
-by (simp add: rsum_def setsum_addf left_distrib)
+subsection {* Additivity Theorem of Gauge Integral *}
 
 text{* Bartle/Sherbert: Theorem 10.1.5 p. 278 *}
 lemma Integral_add_fun:
     "[| a \<le> b; Integral(a,b) f k1; Integral(a,b) g k2 |]
      ==> Integral(a,b) (%x. f x + g x) (k1 + k2)"
-apply (simp add: Integral_def, auto)
-apply ((drule_tac x = "e/2" in spec)+)
-apply auto
-apply (drule gauge_min, assumption)
-apply (rule_tac x = " (%x. if ga x < gaa x then ga x else gaa x)" in exI)
-apply auto
+unfolding Integral_def
+apply clarify
+apply (drule_tac x = "e/2" in spec)+
+apply clarsimp
+apply (rule_tac x = "\<lambda>x. min (\<delta> x) (\<delta>' x)" in exI)
+apply (rule conjI, erule (1) gauge_min)
+apply clarify
 apply (drule fine_min)
-apply ((drule spec)+, auto)
-apply (drule_tac a = "\<bar>rsum (D, p) f - k1\<bar> * 2" and c = "\<bar>rsum (D, p) g - k2\<bar> * 2" in add_strict_mono, assumption)
+apply (drule_tac x=D in spec, simp)+
+apply (drule_tac a = "\<bar>rsum D f - k1\<bar> * 2" and c = "\<bar>rsum D g - k2\<bar> * 2" in add_strict_mono, assumption)
 apply (auto simp only: rsum_add left_distrib [symmetric]
                 mult_2_right [symmetric] real_mult_less_iff1)
 done
 
-lemma partition_lt_gen2:
-     "[| partition(a,b) D; r < psize D |] ==> 0 < D (Suc r) - D r"
-by (auto simp add: partition)
-
-lemma lemma_Integral_le:
-     "[| \<forall>x. a \<le> x & x \<le> b --> f x \<le> g x;
-         tpart(a,b) (D,p)
-      |] ==> \<forall>n \<le> psize D. f (p n) \<le> g (p n)"
-apply (simp add: tpart_def)
-apply (auto, frule partition [THEN iffD1], auto)
-apply (drule_tac x = "p n" in spec, auto)
-apply (case_tac "n = 0", simp)
-apply (rule partition_lt_gen [THEN order_less_le_trans, THEN order_less_imp_le], auto)
-apply (drule le_imp_less_or_eq, auto)
-apply (drule_tac [2] x = "psize D" in spec, auto)
-apply (drule_tac r = "Suc n" in partition_ub)
-apply (drule_tac x = n in spec, auto)
-done
-
 lemma lemma_Integral_rsum_le:
      "[| \<forall>x. a \<le> x & x \<le> b --> f x \<le> g x;
-         tpart(a,b) (D,p)
-      |] ==> rsum(D,p) f \<le> rsum(D,p) g"
-apply (simp add: rsum_def)
-apply (auto intro!: setsum_mono dest: tpart_partition [THEN partition_lt_gen2]
-               dest!: lemma_Integral_le)
+         fine \<delta> (a,b) D
+      |] ==> rsum D f \<le> rsum D g"
+unfolding rsum_def
+apply (rule listsum_mono)
+apply clarify
+apply (rule mult_right_mono)
+apply (drule spec, erule mp)
+apply (frule (1) mem_fine)
+apply (frule (1) mem_fine2)
+apply simp
+apply (frule (1) mem_fine)
+apply simp
 done
 
 lemma Integral_le:
@@ -811,13 +397,11 @@
 apply (drule_tac x = "\<bar>k1 - k2\<bar> /2" in spec)
 apply (drule_tac x = "\<bar>k1 - k2\<bar> /2" in spec, auto)
 apply (drule gauge_min, assumption)
-apply (drule_tac g = "%x. if ga x < gaa x then ga x else gaa x" 
-       in partition_exists, assumption, auto)
+apply (drule_tac \<delta> = "\<lambda>x. min (\<delta> x) (\<delta>' x)" in fine_exists, assumption, clarify)
 apply (drule fine_min)
-apply (drule_tac x = D in spec, drule_tac x = D in spec)
-apply (drule_tac x = p in spec, drule_tac x = p in spec, auto)
+apply (drule_tac x = D in spec, drule_tac x = D in spec, clarsimp)
 apply (frule lemma_Integral_rsum_le, assumption)
-apply (subgoal_tac "\<bar>(rsum (D,p) f - k1) - (rsum (D,p) g - k2)\<bar> < \<bar>k1 - k2\<bar>")
+apply (subgoal_tac "\<bar>(rsum D f - k1) - (rsum D g - k2)\<bar> < \<bar>k1 - k2\<bar>")
 apply arith
 apply (drule add_strict_mono, assumption)
 apply (auto simp only: left_distrib [symmetric] mult_2_right [symmetric]
@@ -826,18 +410,18 @@
 
 lemma Integral_imp_Cauchy:
      "(\<exists>k. Integral(a,b) f k) ==>
-      (\<forall>e > 0. \<exists>g. gauge (%x. a \<le> x & x \<le> b) g &
-                       (\<forall>D1 D2 p1 p2.
-                            tpart(a,b) (D1, p1) & fine g (D1,p1) &
-                            tpart(a,b) (D2, p2) & fine g (D2,p2) -->
-                            \<bar>rsum(D1,p1) f - rsum(D2,p2) f\<bar> < e))"
+      (\<forall>e > 0. \<exists>\<delta>. gauge {a..b} \<delta> &
+                       (\<forall>D1 D2.
+                            fine \<delta> (a,b) D1 &
+                            fine \<delta> (a,b) D2 -->
+                            \<bar>rsum D1 f - rsum D2 f\<bar> < e))"
 apply (simp add: Integral_def, auto)
 apply (drule_tac x = "e/2" in spec, auto)
 apply (rule exI, auto)
 apply (frule_tac x = D1 in spec)
-apply (frule_tac x = D2 in spec)
-apply ((drule spec)+, auto)
-apply (erule_tac V = "0 < e" in thin_rl)
+apply (drule_tac x = D2 in spec)
+apply simp
+apply (thin_tac "0 < e")
 apply (drule add_strict_mono, assumption)
 apply (auto simp only: left_distrib [symmetric] mult_2_right [symmetric]
                        real_mult_less_iff1)
@@ -846,7 +430,7 @@
 lemma Cauchy_iff2:
      "Cauchy X =
       (\<forall>j. (\<exists>M. \<forall>m \<ge> M. \<forall>n \<ge> M. \<bar>X m - X n\<bar> < inverse(real (Suc j))))"
-apply (simp add: Cauchy_def, auto)
+apply (simp add: Cauchy_iff, auto)
 apply (drule reals_Archimedean, safe)
 apply (drule_tac x = n in spec, auto)
 apply (rule_tac x = M in exI, auto)
@@ -854,11 +438,6 @@
 apply (drule_tac x = na in spec, auto)
 done
 
-lemma partition_exists2:
-     "[| a \<le> b; \<forall>n. gauge (%x. a \<le> x & x \<le> b) (fa n) |]
-      ==> \<forall>n. \<exists>D p. tpart (a, b) (D, p) & fine (fa n) (D, p)"
-by (blast dest: partition_exists) 
-
 lemma monotonic_anti_derivative:
   fixes f g :: "real => real" shows
      "[| a \<le> b; \<forall>c. a \<le> c & c \<le> b --> f' c \<le> g' c;
--- a/src/HOL/IsaMakefile	Mon Jun 01 09:26:28 2009 +0200
+++ b/src/HOL/IsaMakefile	Tue Jun 02 12:18:08 2009 +0200
@@ -244,6 +244,7 @@
   Tools/numeral_simprocs.ML \
   Tools/numeral_syntax.ML \
   Tools/polyhash.ML \
+  Tools/quickcheck_generators.ML \
   Tools/Qelim/cooper_data.ML \
   Tools/Qelim/cooper.ML \
   Tools/Qelim/generated_cooper.ML \
@@ -279,6 +280,7 @@
   Fact.thy \
   Integration.thy \
   Lim.thy \
+  Limits.thy \
   Ln.thy \
   Log.thy \
   MacLaurin.thy \
--- a/src/HOL/Library/BigO.thy	Mon Jun 01 09:26:28 2009 +0200
+++ b/src/HOL/Library/BigO.thy	Tue Jun 02 12:18:08 2009 +0200
@@ -871,7 +871,7 @@
   done
 
 lemma bigo_LIMSEQ1: "f =o O(g) ==> g ----> 0 ==> f ----> (0::real)"
-  apply (simp add: LIMSEQ_def bigo_alt_def)
+  apply (simp add: LIMSEQ_iff bigo_alt_def)
   apply clarify
   apply (drule_tac x = "r / c" in spec)
   apply (drule mp)
--- a/src/HOL/Library/Binomial.thy	Mon Jun 01 09:26:28 2009 +0200
+++ b/src/HOL/Library/Binomial.thy	Tue Jun 02 12:18:08 2009 +0200
@@ -6,7 +6,7 @@
 header {* Binomial Coefficients *}
 
 theory Binomial
-imports Fact SetInterval Presburger Main
+imports Fact SetInterval Presburger Main Rational
 begin
 
 text {* This development is based on the work of Andy Gordon and
@@ -290,7 +290,7 @@
 
 subsection{* Generalized binomial coefficients *}
 
-definition gbinomial :: "'a::{field, ring_char_0} \<Rightarrow> nat \<Rightarrow> 'a" (infixl "gchoose" 65)
+definition gbinomial :: "'a::field_char_0 \<Rightarrow> nat \<Rightarrow> 'a" (infixl "gchoose" 65)
   where "a gchoose n = (if n = 0 then 1 else (setprod (\<lambda>i. a - of_nat i) {0 .. n - 1}) / of_nat (fact n))"
 
 lemma gbinomial_0[simp]: "a gchoose 0 = 1" "0 gchoose (Suc n) = 0"
@@ -345,7 +345,7 @@
   
 lemma binomial_fact: 
   assumes kn: "k \<le> n" 
-  shows "(of_nat (n choose k) :: 'a::{field, ring_char_0}) = of_nat (fact n) / (of_nat (fact k) * of_nat (fact (n - k)))"
+  shows "(of_nat (n choose k) :: 'a::field_char_0) = of_nat (fact n) / (of_nat (fact k) * of_nat (fact (n - k)))"
   using binomial_fact_lemma[OF kn]
   by (simp add: field_simps fact_not_eq_zero of_nat_mult[symmetric])
 
@@ -418,16 +418,16 @@
   by (simp add: gbinomial_def)
  
 lemma gbinomial_mult_fact:
-  "(of_nat (fact (Suc k)) :: 'a) * ((a::'a::{field, ring_char_0}) gchoose (Suc k)) = (setprod (\<lambda>i. a - of_nat i) {0 .. k})"
+  "(of_nat (fact (Suc k)) :: 'a) * ((a::'a::field_char_0) gchoose (Suc k)) = (setprod (\<lambda>i. a - of_nat i) {0 .. k})"
   unfolding gbinomial_Suc
   by (simp_all add: field_simps del: fact_Suc)
 
 lemma gbinomial_mult_fact':
-  "((a::'a::{field, ring_char_0}) gchoose (Suc k)) * (of_nat (fact (Suc k)) :: 'a) = (setprod (\<lambda>i. a - of_nat i) {0 .. k})"
+  "((a::'a::field_char_0) gchoose (Suc k)) * (of_nat (fact (Suc k)) :: 'a) = (setprod (\<lambda>i. a - of_nat i) {0 .. k})"
   using gbinomial_mult_fact[of k a]
   apply (subst mult_commute) .
 
-lemma gbinomial_Suc_Suc: "((a::'a::{field, ring_char_0}) + 1) gchoose (Suc k) = a gchoose k + (a gchoose (Suc k))"
+lemma gbinomial_Suc_Suc: "((a::'a::field_char_0) + 1) gchoose (Suc k) = a gchoose k + (a gchoose (Suc k))"
 proof-
   {assume "k = 0" then have ?thesis by simp}
   moreover
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/HOL/Library/Convex_Euclidean_Space.thy	Tue Jun 02 12:18:08 2009 +0200
@@ -0,0 +1,3242 @@
+(* Title:      Convex
+   ID:         $Id: 
+   Author:     Robert Himmelmann, TU Muenchen*)
+
+header {* Convex sets, functions and related things. *}
+
+theory Convex_Euclidean_Space
+  imports Topology_Euclidean_Space
+begin
+
+
+(* ------------------------------------------------------------------------- *)
+(* To be moved elsewhere                                                     *)
+(* ------------------------------------------------------------------------- *)
+
+declare vector_add_ldistrib[simp] vector_ssub_ldistrib[simp] vector_smult_assoc[simp] vector_smult_rneg[simp]
+declare vector_sadd_rdistrib[simp] vector_sub_rdistrib[simp]
+declare dot_ladd[simp] dot_radd[simp] dot_lsub[simp] dot_rsub[simp]
+declare dot_lmult[simp] dot_rmult[simp] dot_lneg[simp] dot_rneg[simp]
+declare UNIV_1[simp]
+
+term "(x::real^'n \<Rightarrow> real) 0"
+
+lemma dim1in[intro]:"Suc 0 \<in> {1::nat .. CARD(1)}" by auto
+
+lemmas vector_component_simps = vector_minus_component vector_smult_component vector_add_component vector_less_eq_def Cart_lambda_beta dest_vec1_def basis_component vector_uminus_component
+
+lemmas continuous_intros = continuous_add continuous_vmul continuous_cmul continuous_const continuous_sub continuous_at_id continuous_within_id
+
+lemmas continuous_on_intros = continuous_on_add continuous_on_const continuous_on_id continuous_on_compose continuous_on_cmul continuous_on_neg continuous_on_sub
+  uniformly_continuous_on_add uniformly_continuous_on_const uniformly_continuous_on_id uniformly_continuous_on_compose uniformly_continuous_on_cmul uniformly_continuous_on_neg uniformly_continuous_on_sub
+
+lemma dest_vec1_simps[simp]: fixes a::"real^1"
+  shows "a$1 = 0 \<longleftrightarrow> a = 0" (*"a \<le> 1 \<longleftrightarrow> dest_vec1 a \<le> 1" "0 \<le> a \<longleftrightarrow> 0 \<le> dest_vec1 a"*)
+  "a \<le> b \<longleftrightarrow> dest_vec1 a \<le> dest_vec1 b" "dest_vec1 (1::real^1) = 1"
+  by(auto simp add:vector_component_simps all_1 Cart_eq)
+
+lemma nequals0I:"x\<in>A \<Longrightarrow> A \<noteq> {}" by auto
+
+lemma norm_not_0:"(x::real^'n::finite)\<noteq>0 \<Longrightarrow> norm x \<noteq> 0" by auto
+
+lemma vector_unminus_smult[simp]: "(-1::real) *s x = -x" unfolding pth_3[symmetric] by simp
+
+lemma setsum_delta_notmem: assumes "x\<notin>s"
+  shows "setsum (\<lambda>y. if (y = x) then P x else Q y) s = setsum Q s"
+        "setsum (\<lambda>y. if (x = y) then P x else Q y) s = setsum Q s"
+        "setsum (\<lambda>y. if (y = x) then P y else Q y) s = setsum Q s"
+        "setsum (\<lambda>y. if (x = y) then P y else Q y) s = setsum Q s"
+  apply(rule_tac [!] setsum_cong2) using assms by auto
+
+lemma setsum_diff1'':assumes "finite A" "a \<in> A"
+  shows "setsum f (A - {a}) = setsum f A - (f a::'a::ring)" unfolding setsum_diff1'[OF assms] by auto
+
+lemma setsum_delta'': fixes s::"(real^'n) set" assumes "finite s"
+  shows "(\<Sum>x\<in>s. (if y = x then f x else 0) *s x) = (if y\<in>s then (f y) *s y else 0)"
+proof-
+  have *:"\<And>x y. (if y = x then f x else (0::real)) *s x = (if x=y then (f x) *s x else 0)" by auto
+  show ?thesis unfolding * using setsum_delta[OF assms, of y "\<lambda>x. f x *s x"] by auto
+qed
+
+lemma not_disjointI:"x\<in>A \<Longrightarrow> x\<in>B \<Longrightarrow> A \<inter> B \<noteq> {}" by blast
+
+lemma if_smult:"(if P then x else (y::real)) *s v = (if P then x *s v else y *s v)" by auto
+
+lemma ex_bij_betw_nat_finite_1:
+  assumes "finite M"
+  shows "\<exists>h. bij_betw h {1 .. card M} M"
+proof-
+  obtain h where h:"bij_betw h {0..<card M} M" using ex_bij_betw_nat_finite[OF assms] by auto
+  let ?h = "h \<circ> (\<lambda>i. i - 1)"
+  have *:"(\<lambda>i. i - 1) ` {1..card M} = {0..<card M}" apply auto  unfolding image_iff apply(rule_tac x="Suc x" in bexI) by auto
+  hence "?h ` {1..card M} = h ` {0..<card M}" unfolding image_compose by auto 
+  hence "?h ` {1..card M} = M" unfolding image_compose using h unfolding * unfolding bij_betw_def by auto
+  moreover
+  have "inj_on (\<lambda>i. i - Suc 0) {Suc 0..card M}" unfolding inj_on_def by auto
+  hence "inj_on ?h {1..card M}" apply(rule_tac comp_inj_on) unfolding * using h[unfolded bij_betw_def] by auto
+  ultimately show ?thesis apply(rule_tac x="h \<circ> (\<lambda>i. i - 1)" in exI) unfolding o_def and bij_betw_def by auto
+qed
+
+lemma finite_subset_image:
+  assumes "B \<subseteq> f ` A" "finite B"
+  shows "\<exists>C\<subseteq>A. finite C \<and> B = f ` C"
+proof- from assms(1) have "\<forall>x\<in>B. \<exists>y\<in>A. x = f y" by auto
+  then obtain c where "\<forall>x\<in>B. c x \<in> A \<and> x = f (c x)"
+    using bchoice[of B "\<lambda>x y. y\<in>A \<and> x = f y"] by auto
+  thus ?thesis apply(rule_tac x="c ` B" in exI) using assms(2) by auto qed
+
+lemma inj_on_image_eq_iff: assumes "inj_on f (A \<union> B)"
+  shows "f ` A = f ` B \<longleftrightarrow> A = B"
+  using assms by(blast dest: inj_onD)
+
+
+lemma mem_interval_1: fixes x :: "real^1" shows
+ "(x \<in> {a .. b} \<longleftrightarrow> dest_vec1 a \<le> dest_vec1 x \<and> dest_vec1 x \<le> dest_vec1 b)"
+ "(x \<in> {a<..<b} \<longleftrightarrow> dest_vec1 a < dest_vec1 x \<and> dest_vec1 x < dest_vec1 b)"
+by(simp_all add: Cart_eq vector_less_def vector_less_eq_def dest_vec1_def all_1)
+
+lemma image_smult_interval:"(\<lambda>x. m *s (x::real^'n::finite)) ` {a..b} =
+  (if {a..b} = {} then {} else if 0 \<le> m then {m *s a..m *s b} else {m *s b..m *s a})"
+  using image_affinity_interval[of m 0 a b] by auto
+
+lemma dest_vec1_inverval:
+  "dest_vec1 ` {a .. b} = {dest_vec1 a .. dest_vec1 b}"
+  "dest_vec1 ` {a<.. b} = {dest_vec1 a<.. dest_vec1 b}"
+  "dest_vec1 ` {a ..<b} = {dest_vec1 a ..<dest_vec1 b}"
+  "dest_vec1 ` {a<..<b} = {dest_vec1 a<..<dest_vec1 b}"
+  apply(rule_tac [!] equalityI)
+  unfolding subset_eq Ball_def Bex_def mem_interval_1 image_iff
+  apply(rule_tac [!] allI)apply(rule_tac [!] impI)
+  apply(rule_tac[2] x="vec1 x" in exI)apply(rule_tac[4] x="vec1 x" in exI)
+  apply(rule_tac[6] x="vec1 x" in exI)apply(rule_tac[8] x="vec1 x" in exI)
+  by (auto simp add: vector_less_def vector_less_eq_def all_1 dest_vec1_def
+    vec1_dest_vec1[unfolded dest_vec1_def One_nat_def])
+
+lemma dest_vec1_setsum: assumes "finite S"
+  shows " dest_vec1 (setsum f S) = setsum (\<lambda>x. dest_vec1 (f x)) S"
+  using dest_vec1_sum[OF assms] by auto
+
+lemma dist_triangle_eq:"dist x z = dist x y + dist y z \<longleftrightarrow> norm (x - y) *s (y - z) = norm (y - z) *s (x - y)"
+proof- have *:"x - y + (y - z) = x - z" by auto
+  show ?thesis unfolding dist_norm norm_triangle_eq[of "x - y" "y - z", unfolded *] 
+    by(auto simp add:norm_minus_commute) qed
+
+lemma norm_eqI:"x = y \<Longrightarrow> norm x = norm y" by auto 
+lemma norm_minus_eqI:"(x::real^'n::finite) = - y \<Longrightarrow> norm x = norm y" by auto
+
+lemma Min_grI: assumes "finite A" "A \<noteq> {}" "\<forall>a\<in>A. x < a" shows "x < Min A"
+  unfolding Min_gr_iff[OF assms(1,2)] using assms(3) by auto
+
+lemma dimindex_ge_1:"CARD(_::finite) \<ge> 1"
+  using one_le_card_finite by auto
+
+lemma real_dimindex_ge_1:"real (CARD('n::finite)) \<ge> 1" 
+  by(metis dimindex_ge_1 linorder_not_less real_eq_of_nat real_le_trans real_of_nat_1 real_of_nat_le_iff) 
+
+lemma real_dimindex_gt_0:"real (CARD('n::finite)) > 0" apply(rule less_le_trans[OF _ real_dimindex_ge_1]) by auto
+
+subsection {* Affine set and affine hull.*}
+
+definition "affine s \<longleftrightarrow> (\<forall>x\<in>s. \<forall>y\<in>s. \<forall>u v::real. u + v = 1 \<longrightarrow> (u *s x + v *s y) \<in> s)"
+
+lemma affine_alt: "affine s \<longleftrightarrow> (\<forall>x\<in>s. \<forall>y\<in>s. \<forall>u::real. (1 - u) *s x + u *s y \<in> s)"
+proof- have *:"\<And>u v ::real. u + v = 1 \<longleftrightarrow> v = 1 - u" by auto
+  { fix x y assume "x\<in>s" "y\<in>s"
+    hence "(\<forall>u v::real. u + v = 1 \<longrightarrow> u *s x + v *s y \<in> s) \<longleftrightarrow> (\<forall>u::real. (1 - u) *s x + u *s y \<in> s)" apply auto 
+      apply(erule_tac[!] x="1 - u" in allE) unfolding * by auto  }
+  thus ?thesis unfolding affine_def by auto qed
+
+lemma affine_empty[intro]: "affine {}"
+  unfolding affine_def by auto
+
+lemma affine_sing[intro]: "affine {x}"
+  unfolding affine_alt by (auto simp add: vector_sadd_rdistrib[THEN sym]) 
+
+lemma affine_UNIV[intro]: "affine UNIV"
+  unfolding affine_def by auto
+
+lemma affine_Inter: "(\<forall>s\<in>f. affine s) \<Longrightarrow> affine (\<Inter> f)"
+  unfolding affine_def by auto 
+
+lemma affine_Int: "affine s \<Longrightarrow> affine t \<Longrightarrow> affine (s \<inter> t)"
+  unfolding affine_def by auto
+
+lemma affine_affine_hull: "affine(affine hull s)"
+  unfolding hull_def using affine_Inter[of "{t \<in> affine. s \<subseteq> t}"]
+  unfolding mem_def by auto
+
+lemma affine_hull_eq[simp]: "(affine hull s = s) \<longleftrightarrow> affine s"
+proof-
+  { fix f assume "f \<subseteq> affine"
+    hence "affine (\<Inter>f)" using affine_Inter[of f] unfolding subset_eq mem_def by auto  }
+  thus ?thesis using hull_eq[unfolded mem_def, of affine s] by auto
+qed
+
+lemma setsum_restrict_set'': assumes "finite A"
+  shows "setsum f {x \<in> A. P x} = (\<Sum>x\<in>A. if P x  then f x else 0)"
+  unfolding mem_def[of _ P, symmetric] unfolding setsum_restrict_set'[OF assms] ..
+
+subsection {* Some explicit formulations (from Lars Schewe). *}
+
+lemma affine: fixes V::"(real^'n) set"
+  shows "affine V \<longleftrightarrow> (\<forall>s u. finite s \<and> s \<noteq> {} \<and> s \<subseteq> V \<and> setsum u s = 1 \<longrightarrow> (setsum (\<lambda>x. (u x) *s x)) s \<in> V)"
+unfolding affine_def apply rule apply(rule, rule, rule) apply(erule conjE)+ 
+defer apply(rule, rule, rule, rule, rule) proof-
+  fix x y u v assume as:"x \<in> V" "y \<in> V" "u + v = (1::real)"
+    "\<forall>s u. finite s \<and> s \<noteq> {} \<and> s \<subseteq> V \<and> setsum u s = 1 \<longrightarrow> (\<Sum>x\<in>s. u x *s x) \<in> V"
+  thus "u *s x + v *s y \<in> V" apply(cases "x=y")
+    using as(4)[THEN spec[where x="{x,y}"], THEN spec[where x="\<lambda>w. if w = x then u else v"]] and as(1-3) 
+    by(auto simp add: vector_sadd_rdistrib[THEN sym])
+next
+  fix s u assume as:"\<forall>x\<in>V. \<forall>y\<in>V. \<forall>u v. u + v = 1 \<longrightarrow> u *s x + v *s y \<in> V"
+    "finite s" "s \<noteq> {}" "s \<subseteq> V" "setsum u s = (1::real)"
+  def n \<equiv> "card s"
+  have "card s = 0 \<or> card s = 1 \<or> card s = 2 \<or> card s > 2" by auto
+  thus "(\<Sum>x\<in>s. u x *s x) \<in> V" proof(auto simp only: disjE)
+    assume "card s = 2" hence "card s = Suc (Suc 0)" by auto
+    then obtain a b where "s = {a, b}" unfolding card_Suc_eq by auto
+    thus ?thesis using as(1)[THEN bspec[where x=a], THEN bspec[where x=b]] using as(4,5)
+      by(auto simp add: setsum_clauses(2))
+  next assume "card s > 2" thus ?thesis using as and n_def proof(induct n arbitrary: u s)
+      case (Suc n) fix s::"(real^'n) set" and u::"real^'n\<Rightarrow> real"
+      assume IA:"\<And>u s.  \<lbrakk>2 < card s; \<forall>x\<in>V. \<forall>y\<in>V. \<forall>u v. u + v = 1 \<longrightarrow> u *s x + v *s y \<in> V; finite s;
+               s \<noteq> {}; s \<subseteq> V; setsum u s = 1; n \<equiv> card s \<rbrakk> \<Longrightarrow> (\<Sum>x\<in>s. u x *s x) \<in> V" and
+	as:"Suc n \<equiv> card s" "2 < card s" "\<forall>x\<in>V. \<forall>y\<in>V. \<forall>u v. u + v = 1 \<longrightarrow> u *s x + v *s y \<in> V"
+           "finite s" "s \<noteq> {}" "s \<subseteq> V" "setsum u s = 1"
+      have "\<exists>x\<in>s. u x \<noteq> 1" proof(rule_tac ccontr)
+	assume " \<not> (\<exists>x\<in>s. u x \<noteq> 1)" hence "setsum u s = real_of_nat (card s)" unfolding card_eq_setsum by auto
+	thus False using as(7) and `card s > 2` by (metis Numeral1_eq1_nat less_0_number_of less_int_code(15)
+	  less_nat_number_of not_less_iff_gr_or_eq of_nat_1 of_nat_eq_iff pos2 rel_simps(4)) qed
+      then obtain x where x:"x\<in>s" "u x \<noteq> 1" by auto
+
+      have c:"card (s - {x}) = card s - 1" apply(rule card_Diff_singleton) using `x\<in>s` as(4) by auto
+      have *:"s = insert x (s - {x})" "finite (s - {x})" using `x\<in>s` and as(4) by auto
+      have **:"setsum u (s - {x}) = 1 - u x"
+	using setsum_clauses(2)[OF *(2), of u x, unfolded *(1)[THEN sym] as(7)] by auto
+      have ***:"inverse (1 - u x) * setsum u (s - {x}) = 1" unfolding ** using `u x \<noteq> 1` by auto
+      have "(\<Sum>xa\<in>s - {x}. (inverse (1 - u x) * u xa) *s xa) \<in> V" proof(cases "card (s - {x}) > 2")
+	case True hence "s - {x} \<noteq> {}" "card (s - {x}) = n" unfolding c and as(1)[symmetric] proof(rule_tac ccontr) 
+	  assume "\<not> s - {x} \<noteq> {}" hence "card (s - {x}) = 0" unfolding card_0_eq[OF *(2)] by simp 
+	  thus False using True by auto qed auto
+	thus ?thesis apply(rule_tac IA[of "s - {x}" "\<lambda>y. (inverse (1 - u x) * u y)"])
+	unfolding setsum_right_distrib[THEN sym] using as and *** and True by auto
+      next case False hence "card (s - {x}) = Suc (Suc 0)" using as(2) and c by auto
+	then obtain a b where "(s - {x}) = {a, b}" "a\<noteq>b" unfolding card_Suc_eq by auto
+	thus ?thesis using as(3)[THEN bspec[where x=a], THEN bspec[where x=b]]
+	  using *** *(2) and `s \<subseteq> V` unfolding setsum_right_distrib by(auto simp add: setsum_clauses(2)) qed
+      thus "(\<Sum>x\<in>s. u x *s x) \<in> V" unfolding vector_smult_assoc[THEN sym] and setsum_cmul
+ 	 apply(subst *) unfolding setsum_clauses(2)[OF *(2)]
+	 using as(3)[THEN bspec[where x=x], THEN bspec[where x="(inverse (1 - u x)) *s (\<Sum>xa\<in>s - {x}. u xa *s xa)"], 
+	 THEN spec[where x="u x"], THEN spec[where x="1 - u x"]] and rev_subsetD[OF `x\<in>s` `s\<subseteq>V`] and `u x \<noteq> 1` by auto
+    qed auto
+  next assume "card s = 1" then obtain a where "s={a}" by(auto simp add: card_Suc_eq)
+    thus ?thesis using as(4,5) by simp
+  qed(insert `s\<noteq>{}` `finite s`, auto)
+qed
+
+lemma affine_hull_explicit:
+  "affine hull p = {y. \<exists>s u. finite s \<and> s \<noteq> {} \<and> s \<subseteq> p \<and> setsum u s = 1 \<and> setsum (\<lambda>v. (u v) *s v) s = y}"
+  apply(rule hull_unique) apply(subst subset_eq) prefer 3 apply rule unfolding mem_Collect_eq and mem_def[of _ affine]
+  apply (erule exE)+ apply(erule conjE)+ prefer 2 apply rule proof-
+  fix x assume "x\<in>p" thus "\<exists>s u. finite s \<and> s \<noteq> {} \<and> s \<subseteq> p \<and> setsum u s = 1 \<and> (\<Sum>v\<in>s. u v *s v) = x"
+    apply(rule_tac x="{x}" in exI, rule_tac x="\<lambda>x. 1" in exI) by auto
+next
+  fix t x s u assume as:"p \<subseteq> t" "affine t" "finite s" "s \<noteq> {}" "s \<subseteq> p" "setsum u s = 1" "(\<Sum>v\<in>s. u v *s v) = x" 
+  thus "x \<in> t" using as(2)[unfolded affine, THEN spec[where x=s], THEN spec[where x=u]] by auto
+next
+  show "affine {y. \<exists>s u. finite s \<and> s \<noteq> {} \<and> s \<subseteq> p \<and> setsum u s = 1 \<and> (\<Sum>v\<in>s. u v *s v) = y}" unfolding affine_def
+    apply(rule,rule,rule,rule,rule) unfolding mem_Collect_eq proof-
+    fix u v ::real assume uv:"u + v = 1"
+    fix x assume "\<exists>s u. finite s \<and> s \<noteq> {} \<and> s \<subseteq> p \<and> setsum u s = 1 \<and> (\<Sum>v\<in>s. u v *s v) = x"
+    then obtain sx ux where x:"finite sx" "sx \<noteq> {}" "sx \<subseteq> p" "setsum ux sx = 1" "(\<Sum>v\<in>sx. ux v *s v) = x" by auto
+    fix y assume "\<exists>s u. finite s \<and> s \<noteq> {} \<and> s \<subseteq> p \<and> setsum u s = 1 \<and> (\<Sum>v\<in>s. u v *s v) = y"
+    then obtain sy uy where y:"finite sy" "sy \<noteq> {}" "sy \<subseteq> p" "setsum uy sy = 1" "(\<Sum>v\<in>sy. uy v *s v) = y" by auto
+    have xy:"finite (sx \<union> sy)" using x(1) y(1) by auto
+    have **:"(sx \<union> sy) \<inter> sx = sx" "(sx \<union> sy) \<inter> sy = sy" by auto
+    show "\<exists>s ua. finite s \<and> s \<noteq> {} \<and> s \<subseteq> p \<and> setsum ua s = 1 \<and> (\<Sum>v\<in>s. ua v *s v) = u *s x + v *s y"
+      apply(rule_tac x="sx \<union> sy" in exI)
+      apply(rule_tac x="\<lambda>a. (if a\<in>sx then u * ux a else 0) + (if a\<in>sy then v * uy a else 0)" in exI)
+      unfolding vector_sadd_rdistrib setsum_addf if_smult vector_smult_lzero  ** setsum_restrict_set[OF xy, THEN sym]
+      unfolding vector_smult_assoc[THEN sym] setsum_cmul and setsum_right_distrib[THEN sym]
+      unfolding x y using x(1-3) y(1-3) uv by simp qed qed
+
+lemma affine_hull_finite:
+  assumes "finite s"
+  shows "affine hull s = {y. \<exists>u. setsum u s = 1 \<and> setsum (\<lambda>v. u v *s v) s = y}"
+  unfolding affine_hull_explicit and expand_set_eq and mem_Collect_eq apply (rule,rule)
+  apply(erule exE)+ apply(erule conjE)+ defer apply(erule exE) apply(erule conjE) proof-
+  fix x u assume "setsum u s = 1" "(\<Sum>v\<in>s. u v *s v) = x"
+  thus "\<exists>sa u. finite sa \<and> \<not> (\<forall>x. (x \<in> sa) = (x \<in> {})) \<and> sa \<subseteq> s \<and> setsum u sa = 1 \<and> (\<Sum>v\<in>sa. u v *s v) = x"
+    apply(rule_tac x=s in exI, rule_tac x=u in exI) using assms by auto
+next
+  fix x t u assume "t \<subseteq> s" hence *:"s \<inter> t = t" by auto
+  assume "finite t" "\<not> (\<forall>x. (x \<in> t) = (x \<in> {}))" "setsum u t = 1" "(\<Sum>v\<in>t. u v *s v) = x"
+  thus "\<exists>u. setsum u s = 1 \<and> (\<Sum>v\<in>s. u v *s v) = x" apply(rule_tac x="\<lambda>x. if x\<in>t then u x else 0" in exI)
+    unfolding if_smult vector_smult_lzero and setsum_restrict_set[OF assms, THEN sym] and * by auto qed
+
+subsection {* Stepping theorems and hence small special cases. *}
+
+lemma affine_hull_empty[simp]: "affine hull {} = {}"
+  apply(rule hull_unique) unfolding mem_def by auto
+
+lemma affine_hull_finite_step:
+  shows "(\<exists>u::real^'n=>real. setsum u {} = w \<and> setsum (\<lambda>x. u x *s x) {} = y) \<longleftrightarrow> w = 0 \<and> y = 0" (is ?th1)
+  "finite s \<Longrightarrow> (\<exists>u. setsum u (insert a s) = w \<and> setsum (\<lambda>x. u x *s x) (insert a s) = y) \<longleftrightarrow>
+                (\<exists>v u. setsum u s = w - v \<and> setsum (\<lambda>x. u x *s x) s = y - v *s a)" (is "?as \<Longrightarrow> (?lhs = ?rhs)")
+proof-
+  show ?th1 by simp
+  assume ?as 
+  { assume ?lhs
+    then obtain u where u:"setsum u (insert a s) = w \<and> (\<Sum>x\<in>insert a s. u x *s x) = y" by auto
+    have ?rhs proof(cases "a\<in>s")
+      case True hence *:"insert a s = s" by auto
+      show ?thesis using u[unfolded *] apply(rule_tac x=0 in exI) by auto
+    next
+      case False thus ?thesis apply(rule_tac x="u a" in exI) using u and `?as` by auto 
+    qed  } moreover
+  { assume ?rhs
+    then obtain v u where vu:"setsum u s = w - v"  "(\<Sum>x\<in>s. u x *s x) = y - v *s a" by auto
+    have *:"\<And>x M. (if x = a then v else M) *s x = (if x = a then v *s x else M *s x)" by auto
+    have ?lhs proof(cases "a\<in>s")
+      case True thus ?thesis
+	apply(rule_tac x="\<lambda>x. (if x=a then v else 0) + u x" in exI)
+	unfolding setsum_clauses(2)[OF `?as`]  apply simp
+	unfolding vector_sadd_rdistrib and setsum_addf 
+	unfolding vu and * and pth_4(1)
+	by (auto simp add: setsum_delta[OF `?as`])
+    next
+      case False 
+      hence **:"\<And>x. x \<in> s \<Longrightarrow> u x = (if x = a then v else u x)"
+               "\<And>x. x \<in> s \<Longrightarrow> u x *s x = (if x = a then v *s x else u x *s x)" by auto
+      from False show ?thesis
+	apply(rule_tac x="\<lambda>x. if x=a then v else u x" in exI)
+	unfolding setsum_clauses(2)[OF `?as`] and * using vu
+	using setsum_cong2[of s "\<lambda>x. u x *s x" "\<lambda>x. if x = a then v *s x else u x *s x", OF **(2)]
+	using setsum_cong2[of s u "\<lambda>x. if x = a then v else u x", OF **(1)] by auto  
+    qed }
+  ultimately show "?lhs = ?rhs" by blast
+qed
+
+lemma affine_hull_2: "affine hull {a,b::real^'n} = {u *s a + v *s b| u v. (u + v = 1)}" (is "?lhs = ?rhs")
+proof-
+  have *:"\<And>x y z. z = x - y \<longleftrightarrow> y + z = (x::real)" 
+         "\<And>x y z. z = x - y \<longleftrightarrow> y + z = (x::real^'n)" by auto
+  have "?lhs = {y. \<exists>u. setsum u {a, b} = 1 \<and> (\<Sum>v\<in>{a, b}. u v *s v) = y}"
+    using affine_hull_finite[of "{a,b}"] by auto
+  also have "\<dots> = {y. \<exists>v u. u b = 1 - v \<and> u b *s b = y - v *s a}"
+    by(simp add: affine_hull_finite_step(2)[of "{b}" a]) 
+  also have "\<dots> = ?rhs" unfolding * by auto
+  finally show ?thesis by auto
+qed
+
+lemma affine_hull_3: "affine hull {a,b,c::real^'n} = { u *s a + v *s b + w *s c| u v w. u + v + w = 1}" (is "?lhs = ?rhs")
+proof-
+  have *:"\<And>x y z. z = x - y \<longleftrightarrow> y + z = (x::real)" 
+         "\<And>x y z. z = x - y \<longleftrightarrow> y + z = (x::real^'n)" by auto
+  show ?thesis apply(simp add: affine_hull_finite affine_hull_finite_step)
+    unfolding * apply auto
+    apply(rule_tac x=v in exI) apply(rule_tac x=va in exI) apply auto
+    apply(rule_tac x=u in exI) by(auto intro!: exI)
+qed
+
+subsection {* Some relations between affine hull and subspaces. *}
+
+lemma affine_hull_insert_subset_span:
+  "affine hull (insert a s) \<subseteq> {a + v| v . v \<in> span {x - a | x . x \<in> s}}"
+  unfolding subset_eq Ball_def unfolding affine_hull_explicit span_explicit mem_Collect_eq
+  apply(rule,rule) apply(erule exE)+ apply(erule conjE)+ proof-
+  fix x t u assume as:"finite t" "t \<noteq> {}" "t \<subseteq> insert a s" "setsum u t = 1" "(\<Sum>v\<in>t. u v *s v) = x"
+  have "(\<lambda>x. x - a) ` (t - {a}) \<subseteq> {x - a |x. x \<in> s}" using as(3) by auto
+  thus "\<exists>v. x = a + v \<and> (\<exists>S u. finite S \<and> S \<subseteq> {x - a |x. x \<in> s} \<and> (\<Sum>v\<in>S. u v *s v) = v)"
+    apply(rule_tac x="x - a" in exI) apply rule defer apply(rule_tac x="(\<lambda>x. x - a) ` (t - {a})" in exI)
+    apply(rule_tac x="\<lambda>x. u (x + a)" in exI) using as(1)
+    apply(simp add: setsum_reindex[unfolded inj_on_def] setsum_subtractf setsum_diff1 setsum_vmul[THEN sym])
+    unfolding as by simp_all qed
+
+lemma affine_hull_insert_span:
+  assumes "a \<notin> s"
+  shows "affine hull (insert a s) =
+            {a + v | v . v \<in> span {x - a | x.  x \<in> s}}"
+  apply(rule, rule affine_hull_insert_subset_span) unfolding subset_eq Ball_def
+  unfolding affine_hull_explicit and mem_Collect_eq proof(rule,rule,erule exE,erule conjE)
+  fix y v assume "y = a + v" "v \<in> span {x - a |x. x \<in> s}"
+  then obtain t u where obt:"finite t" "t \<subseteq> {x - a |x. x \<in> s}" "a + (\<Sum>v\<in>t. u v *s v) = y" unfolding span_explicit by auto
+  def f \<equiv> "(\<lambda>x. x + a) ` t"
+  have f:"finite f" "f \<subseteq> s" "(\<Sum>v\<in>f. u (v - a) *s (v - a)) = y - a" unfolding f_def using obt 
+    by(auto simp add: setsum_reindex[unfolded inj_on_def])
+  have *:"f \<inter> {a} = {}" "f \<inter> - {a} = f" using f(2) assms by auto
+  show "\<exists>sa u. finite sa \<and> sa \<noteq> {} \<and> sa \<subseteq> insert a s \<and> setsum u sa = 1 \<and> (\<Sum>v\<in>sa. u v *s v) = y"
+    apply(rule_tac x="insert a f" in exI)
+    apply(rule_tac x="\<lambda>x. if x=a then 1 - setsum (\<lambda>x. u (x - a)) f else u (x - a)" in exI)
+    using assms and f unfolding setsum_clauses(2)[OF f(1)] and if_smult
+    unfolding setsum_cases[OF f(1), of "{a}", unfolded singleton_iff] and *
+    by (auto simp add: setsum_subtractf setsum_vmul field_simps) qed
+
+lemma affine_hull_span:
+  assumes "a \<in> s"
+  shows "affine hull s = {a + v | v. v \<in> span {x - a | x. x \<in> s - {a}}}"
+  using affine_hull_insert_span[of a "s - {a}", unfolded insert_Diff[OF assms]] by auto
+
+subsection {* Convexity. *}
+
+definition "convex (s::(real^'n) set) \<longleftrightarrow>
+        (\<forall>x\<in>s. \<forall>y\<in>s. \<forall>u\<ge>0. \<forall>v\<ge>0. (u + v = 1) \<longrightarrow> (u *s x + v *s y) \<in> s)"
+
+lemma convex_alt: "convex s \<longleftrightarrow> (\<forall>x\<in>s. \<forall>y\<in>s. \<forall>u. 0 \<le> u \<and> u \<le> 1 \<longrightarrow> ((1 - u) *s x + u *s y) \<in> s)"
+proof- have *:"\<And>u v::real. u + v = 1 \<longleftrightarrow> u = 1 - v" by auto
+  show ?thesis unfolding convex_def apply auto
+    apply(erule_tac x=x in ballE) apply(erule_tac x=y in ballE) apply(erule_tac x="1 - u" in allE)
+    by (auto simp add: *) qed
+
+lemma mem_convex:
+  assumes "convex s" "a \<in> s" "b \<in> s" "0 \<le> u" "u \<le> 1"
+  shows "((1 - u) *s a + u *s b) \<in> s"
+  using assms unfolding convex_alt by auto
+
+lemma convex_empty[intro]: "convex {}"
+  unfolding convex_def by simp
+
+lemma convex_singleton[intro]: "convex {a}"
+  unfolding convex_def by (auto simp add:vector_sadd_rdistrib[THEN sym])
+
+lemma convex_UNIV[intro]: "convex UNIV"
+  unfolding convex_def by auto
+
+lemma convex_Inter: "(\<forall>s\<in>f. convex s) ==> convex(\<Inter> f)"
+  unfolding convex_def by auto
+
+lemma convex_Int: "convex s \<Longrightarrow> convex t \<Longrightarrow> convex (s \<inter> t)"
+  unfolding convex_def by auto
+
+lemma convex_halfspace_le: "convex {x. a \<bullet> x \<le> b}"
+  unfolding convex_def apply auto
+  unfolding dot_radd dot_rmult by (metis real_convex_bound_le) 
+
+lemma convex_halfspace_ge: "convex {x. a \<bullet> x \<ge> b}"
+proof- have *:"{x. a \<bullet> x \<ge> b} = {x. -a \<bullet> x \<le> -b}" by auto
+  show ?thesis apply(unfold *) using convex_halfspace_le[of "-a" "-b"] by auto qed
+
+lemma convex_hyperplane: "convex {x. a \<bullet> x = b}"
+proof-
+  have *:"{x. a \<bullet> x = b} = {x. a \<bullet> x \<le> b} \<inter> {x. a \<bullet> x \<ge> b}" by auto
+  show ?thesis unfolding * apply(rule convex_Int)
+    using convex_halfspace_le convex_halfspace_ge by auto
+qed
+
+lemma convex_halfspace_lt: "convex {x. a \<bullet> x < b}"
+  unfolding convex_def by(auto simp add: real_convex_bound_lt dot_radd dot_rmult)
+
+lemma convex_halfspace_gt: "convex {x. a \<bullet> x > b}"
+   using convex_halfspace_lt[of "-a" "-b"] by(auto simp add: dot_lneg neg_less_iff_less)
+
+lemma convex_positive_orthant: "convex {x::real^'n. (\<forall>i. 0 \<le> x$i)}"
+  unfolding convex_def apply auto apply(erule_tac x=i in allE)+
+  apply(rule add_nonneg_nonneg) by(auto simp add: mult_nonneg_nonneg)
+
+subsection {* Explicit expressions for convexity in terms of arbitrary sums. *}
+
+lemma convex: "convex s \<longleftrightarrow>
+  (\<forall>(k::nat) u x. (\<forall>i. 1\<le>i \<and> i\<le>k \<longrightarrow> 0 \<le> u i \<and> x i \<in>s) \<and> (setsum u {1..k} = 1)
+           \<longrightarrow> setsum (\<lambda>i. u i *s x i) {1..k} \<in> s)"
+  unfolding convex_def apply rule apply(rule allI)+ defer apply(rule ballI)+ apply(rule allI)+ proof(rule,rule,rule,rule)
+  fix x y u v assume as:"\<forall>(k::nat) u x. (\<forall>i. 1 \<le> i \<and> i \<le> k \<longrightarrow> 0 \<le> u i \<and> x i \<in> s) \<and> setsum u {1..k} = 1 \<longrightarrow> (\<Sum>i = 1..k. u i *s x i) \<in> s"
+    "x \<in> s" "y \<in> s" "0 \<le> u" "0 \<le> v" "u + v = (1::real)"
+  show "u *s x + v *s y \<in> s" using as(1)[THEN spec[where x=2], THEN spec[where x="\<lambda>n. if n=1 then u else v"], THEN spec[where x="\<lambda>n. if n=1 then x else y"]] and as(2-)
+    by (auto simp add: setsum_head_Suc) 
+next
+  fix k u x assume as:"\<forall>x\<in>s. \<forall>y\<in>s. \<forall>u\<ge>0. \<forall>v\<ge>0. u + v = 1 \<longrightarrow> u *s x + v *s y \<in> s" 
+  show "(\<forall>i::nat. 1 \<le> i \<and> i \<le> k \<longrightarrow> 0 \<le> u i \<and> x i \<in> s) \<and> setsum u {1..k} = 1 \<longrightarrow> (\<Sum>i = 1..k. u i *s x i) \<in> s" apply(rule,erule conjE) proof(induct k arbitrary: u)
+  case (Suc k) show ?case proof(cases "u (Suc k) = 1")
+    case True hence "(\<Sum>i = Suc 0..k. u i *s x i) = 0" apply(rule_tac setsum_0') apply(rule ccontr) unfolding ball_simps apply(erule bexE) proof-
+      fix i assume i:"i \<in> {Suc 0..k}" "u i *s x i \<noteq> 0"
+      hence ui:"u i \<noteq> 0" by auto
+      hence "setsum (\<lambda>k. if k=i then u i else 0) {1 .. k} \<le> setsum u {1 .. k}" apply(rule_tac setsum_mono) using Suc(2) by auto
+      hence "setsum u {1 .. k} \<ge> u i" using i(1) by(auto simp add: setsum_delta) 
+      hence "setsum u {1 .. k} > 0"  using ui apply(rule_tac less_le_trans[of _ "u i"]) using Suc(2)[THEN spec[where x=i]] and i(1) by auto
+      thus False using Suc(3) unfolding setsum_cl_ivl_Suc and True by simp qed
+    thus ?thesis unfolding setsum_cl_ivl_Suc using True and Suc(2) by auto
+  next
+    have *:"setsum u {1..k} = 1 - u (Suc k)" using Suc(3)[unfolded setsum_cl_ivl_Suc] by auto
+    have **:"u (Suc k) \<le> 1" apply(rule ccontr) unfolding not_le using Suc(3) using setsum_nonneg[of "{1..k}" u] using Suc(2) by auto
+    have ***:"\<And>i k. (u i / (1 - u (Suc k))) *s x i = (inverse (1 - u (Suc k))) *s (u i *s x i)" unfolding real_divide_def by auto
+    case False hence nn:"1 - u (Suc k) \<noteq> 0" by auto
+    have "(\<Sum>i = 1..k. (u i / (1 - u (Suc k))) *s x i) \<in> s" apply(rule Suc(1)) unfolding setsum_divide_distrib[THEN sym] and *
+      apply(rule_tac allI) apply(rule,rule) apply(rule divide_nonneg_pos) using nn Suc(2) ** by auto
+    hence "(1 - u (Suc k)) *s (\<Sum>i = 1..k. (u i / (1 - u (Suc k))) *s x i) + u (Suc k) *s x (Suc k) \<in> s"
+      apply(rule as[THEN bspec, THEN bspec, THEN spec, THEN mp, THEN spec, THEN mp, THEN mp]) using Suc(2)[THEN spec[where x="Suc k"]] and ** by auto
+    thus ?thesis unfolding setsum_cl_ivl_Suc and *** and setsum_cmul using nn by auto qed qed auto qed
+
+
+lemma convex_explicit: "convex (s::(real^'n) set) \<longleftrightarrow>
+  (\<forall>t u. finite t \<and> t \<subseteq> s \<and> (\<forall>x\<in>t. 0 \<le> u x) \<and> setsum u t = 1 \<longrightarrow> setsum (\<lambda>x. u x *s x) t \<in> s)"
+  unfolding convex_def apply(rule,rule,rule) apply(subst imp_conjL,rule) defer apply(rule,rule,rule,rule,rule,rule,rule) proof-
+  fix x y u v assume as:"\<forall>t u. finite t \<and> t \<subseteq> s \<and> (\<forall>x\<in>t. 0 \<le> u x) \<and> setsum u t = 1 \<longrightarrow> (\<Sum>x\<in>t. u x *s x) \<in> s" "x \<in> s" "y \<in> s" "0 \<le> u" "0 \<le> v" "u + v = (1::real)"
+  show "u *s x + v *s y \<in> s" proof(cases "x=y")
+    case True show ?thesis unfolding True and vector_sadd_rdistrib[THEN sym] using as(3,6) by auto next
+    case False thus ?thesis using as(1)[THEN spec[where x="{x,y}"], THEN spec[where x="\<lambda>z. if z=x then u else v"]] and as(2-) by auto qed
+next 
+  fix t u assume asm:"\<forall>x\<in>s. \<forall>y\<in>s. \<forall>u\<ge>0. \<forall>v\<ge>0. u + v = 1 \<longrightarrow> u *s x + v *s y \<in> s" "finite (t::(real^'n) set)"
+  (*"finite t" "t \<subseteq> s" "\<forall>x\<in>t. (0::real) \<le> u x" "setsum u t = 1"*)
+  from this(2) have "\<forall>u. t \<subseteq> s \<and> (\<forall>x\<in>t. 0 \<le> u x) \<and> setsum u t = 1 \<longrightarrow> (\<Sum>x\<in>t. u x *s x) \<in> s" apply(induct_tac t rule:finite_induct)
+    prefer 3 apply (rule,rule) apply(erule conjE)+ proof-
+    fix x f u assume ind:"\<forall>u. f \<subseteq> s \<and> (\<forall>x\<in>f. 0 \<le> u x) \<and> setsum u f = 1 \<longrightarrow> (\<Sum>x\<in>f. u x *s x) \<in> s"
+    assume as:"finite f" "x \<notin> f" "insert x f \<subseteq> s" "\<forall>x\<in>insert x f. 0 \<le> u x" "setsum u (insert x f) = (1::real)"
+    show "(\<Sum>x\<in>insert x f. u x *s x) \<in> s" proof(cases "u x = 1")
+      case True hence "setsum (\<lambda>x. u x *s x) f = 0" apply(rule_tac setsum_0') apply(rule ccontr) unfolding ball_simps apply(erule bexE) proof-
+	fix y assume y:"y \<in> f" "u y *s y \<noteq> 0"
+	hence uy:"u y \<noteq> 0" by auto
+	hence "setsum (\<lambda>k. if k=y then u y else 0) f \<le> setsum u f" apply(rule_tac setsum_mono) using as(4) by auto
+	hence "setsum u f \<ge> u y" using y(1) and as(1) by(auto simp add: setsum_delta) 
+	hence "setsum u f > 0" using uy apply(rule_tac less_le_trans[of _ "u y"]) using as(4) and y(1) by auto
+	thus False using as(2,5) unfolding setsum_clauses(2)[OF as(1)] and True by auto qed
+      thus ?thesis unfolding setsum_clauses(2)[OF as(1)] using as(2,3) unfolding True by auto
+    next
+      have *:"setsum u f = setsum u (insert x f) - u x" using as(2) unfolding setsum_clauses(2)[OF as(1)] by auto
+      have **:"u x \<le> 1" apply(rule ccontr) unfolding not_le using as(5)[unfolded setsum_clauses(2)[OF as(1)]] and as(2)
+	using setsum_nonneg[of f u] and as(4) by auto
+      case False hence "inverse (1 - u x) *s (\<Sum>x\<in>f. u x *s x) \<in> s" unfolding setsum_cmul[THEN sym] and vector_smult_assoc
+	apply(rule_tac ind[THEN spec, THEN mp]) apply rule defer apply rule apply rule apply(rule mult_nonneg_nonneg)
+	unfolding setsum_right_distrib[THEN sym] and * using as and ** by auto
+      hence "u x *s x + (1 - u x) *s ((inverse (1 - u x)) *s setsum (\<lambda>x. u x *s x) f) \<in>s" 
+	apply(rule_tac asm(1)[THEN bspec, THEN bspec, THEN spec, THEN mp, THEN spec, THEN mp, THEN mp]) using as and ** False by auto 
+      thus ?thesis unfolding setsum_clauses(2)[OF as(1)] using as(2) and False by auto qed
+  qed auto thus "t \<subseteq> s \<and> (\<forall>x\<in>t. 0 \<le> u x) \<and> setsum u t = 1 \<longrightarrow> (\<Sum>x\<in>t. u x *s x) \<in> s" by auto
+qed
+
+lemma convex_finite: assumes "finite s"
+  shows "convex s \<longleftrightarrow> (\<forall>u. (\<forall>x\<in>s. 0 \<le> u x) \<and> setsum u s = 1
+                      \<longrightarrow> setsum (\<lambda>x. u x *s x) s \<in> s)"
+  unfolding convex_explicit apply(rule, rule, rule) defer apply(rule,rule,rule)apply(erule conjE)+ proof-
+  fix t u assume as:"\<forall>u. (\<forall>x\<in>s. 0 \<le> u x) \<and> setsum u s = 1 \<longrightarrow> (\<Sum>x\<in>s. u x *s x) \<in> s" " finite t" "t \<subseteq> s" "\<forall>x\<in>t. 0 \<le> u x" "setsum u t = (1::real)"
+  have *:"s \<inter> t = t" using as(3) by auto
+  show "(\<Sum>x\<in>t. u x *s x) \<in> s" using as(1)[THEN spec[where x="\<lambda>x. if x\<in>t then u x else 0"]]
+    unfolding if_smult and setsum_cases[OF assms] and * using as(2-) by auto
+qed (erule_tac x=s in allE, erule_tac x=u in allE, auto)
+
+subsection {* Cones. *}
+
+definition "cone (s::(real^'n) set) \<longleftrightarrow> (\<forall>x\<in>s. \<forall>c\<ge>0. (c *s x) \<in> s)"
+
+lemma cone_empty[intro, simp]: "cone {}"
+  unfolding cone_def by auto
+
+lemma cone_univ[intro, simp]: "cone UNIV"
+  unfolding cone_def by auto
+
+lemma cone_Inter[intro]: "(\<forall>s\<in>f. cone s) \<Longrightarrow> cone(\<Inter> f)"
+  unfolding cone_def by auto
+
+subsection {* Conic hull. *}
+
+lemma cone_cone_hull: "cone (cone hull s)"
+  unfolding hull_def using cone_Inter[of "{t \<in> conic. s \<subseteq> t}"] 
+  by (auto simp add: mem_def)
+
+lemma cone_hull_eq: "(cone hull s = s) \<longleftrightarrow> cone s"
+  apply(rule hull_eq[unfolded mem_def])
+  using cone_Inter unfolding subset_eq by (auto simp add: mem_def)
+
+subsection {* Affine dependence and consequential theorems (from Lars Schewe). *}
+
+definition "affine_dependent (s::(real^'n) set) \<longleftrightarrow> (\<exists>x\<in>s. x \<in> (affine hull (s - {x})))"
+
+lemma affine_dependent_explicit:
+  "affine_dependent p \<longleftrightarrow>
+    (\<exists>s u. finite s \<and> s \<subseteq> p \<and> setsum u s = 0 \<and>
+    (\<exists>v\<in>s. u v \<noteq> 0) \<and> setsum (\<lambda>v. u v *s v) s = 0)"
+  unfolding affine_dependent_def affine_hull_explicit mem_Collect_eq apply(rule)
+  apply(erule bexE,erule exE,erule exE) apply(erule conjE)+ defer apply(erule exE,erule exE) apply(erule conjE)+ apply(erule bexE)
+proof-
+  fix x s u assume as:"x \<in> p" "finite s" "s \<noteq> {}" "s \<subseteq> p - {x}" "setsum u s = 1" "(\<Sum>v\<in>s. u v *s v) = x"
+  have "x\<notin>s" using as(1,4) by auto
+  show "\<exists>s u. finite s \<and> s \<subseteq> p \<and> setsum u s = 0 \<and> (\<exists>v\<in>s. u v \<noteq> 0) \<and> (\<Sum>v\<in>s. u v *s v) = 0"
+    apply(rule_tac x="insert x s" in exI, rule_tac x="\<lambda>v. if v = x then - 1 else u v" in exI)
+    unfolding if_smult and setsum_clauses(2)[OF as(2)] and setsum_delta_notmem[OF `x\<notin>s`] and as using as by auto 
+next
+  fix s u v assume as:"finite s" "s \<subseteq> p" "setsum u s = 0" "(\<Sum>v\<in>s. u v *s v) = 0" "v \<in> s" "u v \<noteq> 0"
+  have "s \<noteq> {v}" using as(3,6) by auto
+  thus "\<exists>x\<in>p. \<exists>s u. finite s \<and> s \<noteq> {} \<and> s \<subseteq> p - {x} \<and> setsum u s = 1 \<and> (\<Sum>v\<in>s. u v *s v) = x" 
+    apply(rule_tac x=v in bexI, rule_tac x="s - {v}" in exI, rule_tac x="\<lambda>x. - (1 / u v) * u x" in exI)
+    unfolding vector_smult_assoc[THEN sym] and setsum_cmul unfolding setsum_right_distrib[THEN sym] and setsum_diff1''[OF as(1,5)] using as by auto
+qed
+
+lemma affine_dependent_explicit_finite:
+  assumes "finite (s::(real^'n) set)"
+  shows "affine_dependent s \<longleftrightarrow> (\<exists>u. setsum u s = 0 \<and> (\<exists>v\<in>s. u v \<noteq> 0) \<and> setsum (\<lambda>v. u v *s v) s = 0)"
+  (is "?lhs = ?rhs")
+proof
+  have *:"\<And>vt u v. (if vt then u v else 0) *s v = (if vt then (u v) *s v else (0::real^'n))" by auto
+  assume ?lhs
+  then obtain t u v where "finite t" "t \<subseteq> s" "setsum u t = 0" "v\<in>t" "u v \<noteq> 0"  "(\<Sum>v\<in>t. u v *s v) = 0"
+    unfolding affine_dependent_explicit by auto
+  thus ?rhs apply(rule_tac x="\<lambda>x. if x\<in>t then u x else 0" in exI)
+    apply auto unfolding * and setsum_restrict_set[OF assms, THEN sym]
+    unfolding Int_absorb2[OF `t\<subseteq>s`, unfolded Int_commute] by auto
+next
+  assume ?rhs
+  then obtain u v where "setsum u s = 0"  "v\<in>s" "u v \<noteq> 0" "(\<Sum>v\<in>s. u v *s v) = 0" by auto
+  thus ?lhs unfolding affine_dependent_explicit using assms by auto
+qed
+
+subsection {* A general lemma. *}
+
+lemma convex_connected:
+  assumes "convex s" shows "connected s"
+proof-
+  { fix e1 e2 assume as:"open e1" "open e2" "e1 \<inter> e2 \<inter> s = {}" "s \<subseteq> e1 \<union> e2" 
+    assume "e1 \<inter> s \<noteq> {}" "e2 \<inter> s \<noteq> {}"
+    then obtain x1 x2 where x1:"x1\<in>e1" "x1\<in>s" and x2:"x2\<in>e2" "x2\<in>s" by auto
+    hence n:"norm (x1 - x2) > 0" unfolding zero_less_norm_iff using as(3) by auto
+
+    { fix x e::real assume as:"0 \<le> x" "x \<le> 1" "0 < e"
+      { fix y have *:"(1 - x) *s x1 + x *s x2 - ((1 - y) *s x1 + y *s x2) = (y - x) *s x1 - (y - x) *s x2"
+	  by(simp add: ring_simps vector_sadd_rdistrib vector_sub_rdistrib)
+	assume "\<bar>y - x\<bar> < e / norm (x1 - x2)"
+	hence "norm ((1 - x) *s x1 + x *s x2 - ((1 - y) *s x1 + y *s x2)) < e"
+	  unfolding * and vector_ssub_ldistrib[THEN sym] and norm_mul 
+	  unfolding less_divide_eq using n by auto  }
+      hence "\<exists>d>0. \<forall>y. \<bar>y - x\<bar> < d \<longrightarrow> norm ((1 - x) *s x1 + x *s x2 - ((1 - y) *s x1 + y *s x2)) < e"
+	apply(rule_tac x="e / norm (x1 - x2)" in exI) using as
+	apply auto unfolding zero_less_divide_iff using n by simp  }  note * = this
+
+    have "\<exists>x\<ge>0. x \<le> 1 \<and> (1 - x) *s x1 + x *s x2 \<notin> e1 \<and> (1 - x) *s x1 + x *s x2 \<notin> e2"
+      apply(rule connected_real_lemma) apply (simp add: `x1\<in>e1` `x2\<in>e2` dist_commute)+
+      using * apply(simp add: dist_norm)
+      using as(1,2)[unfolded open_def] apply simp
+      using as(1,2)[unfolded open_def] apply simp
+      using assms[unfolded convex_alt, THEN bspec[where x=x1], THEN bspec[where x=x2]] using x1 x2
+      using as(3) by auto
+    then obtain x where "x\<ge>0" "x\<le>1" "(1 - x) *s x1 + x *s x2 \<notin> e1"  "(1 - x) *s x1 + x *s x2 \<notin> e2" by auto
+    hence False using as(4) 
+      using assms[unfolded convex_alt, THEN bspec[where x=x1], THEN bspec[where x=x2]]
+      using x1(2) x2(2) by auto  }
+  thus ?thesis unfolding connected_def by auto
+qed
+
+subsection {* One rather trivial consequence. *}
+
+lemma connected_UNIV: "connected (UNIV :: (real ^ _) set)"
+  by(simp add: convex_connected convex_UNIV)
+
+subsection {* Convex functions into the reals. *}
+
+definition "convex_on s (f::real^'n \<Rightarrow> real) = 
+  (\<forall>x\<in>s. \<forall>y\<in>s. \<forall>u\<ge>0. \<forall>v\<ge>0. u + v = 1 \<longrightarrow> f (u *s x + v *s y) \<le> u * f x + v * f y)"
+
+lemma convex_on_subset: "convex_on t f \<Longrightarrow> s \<subseteq> t \<Longrightarrow> convex_on s f"
+  unfolding convex_on_def by auto
+
+lemma convex_add:
+  assumes "convex_on s f" "convex_on s g"
+  shows "convex_on s (\<lambda>x. f x + g x)"
+proof-
+  { fix x y assume "x\<in>s" "y\<in>s" moreover
+    fix u v ::real assume "0 \<le> u" "0 \<le> v" "u + v = 1"
+    ultimately have "f (u *s x + v *s y) + g (u *s x + v *s y) \<le> (u * f x + v * f y) + (u * g x + v * g y)"
+      using assms(1)[unfolded convex_on_def, THEN bspec[where x=x], THEN bspec[where x=y], THEN spec[where x=u]]
+      using assms(2)[unfolded convex_on_def, THEN bspec[where x=x], THEN bspec[where x=y], THEN spec[where x=u]]
+      apply - apply(rule add_mono) by auto
+    hence "f (u *s x + v *s y) + g (u *s x + v *s y) \<le> u * (f x + g x) + v * (f y + g y)" by (simp add: ring_simps)  }
+  thus ?thesis unfolding convex_on_def by auto 
+qed
+
+lemma convex_cmul: 
+  assumes "0 \<le> (c::real)" "convex_on s f"
+  shows "convex_on s (\<lambda>x. c * f x)"
+proof-
+  have *:"\<And>u c fx v fy ::real. u * (c * fx) + v * (c * fy) = c * (u * fx + v * fy)" by (simp add: ring_simps)
+  show ?thesis using assms(2) and mult_mono1[OF _ assms(1)] unfolding convex_on_def and * by auto
+qed
+
+lemma convex_lower:
+  assumes "convex_on s f"  "x\<in>s"  "y \<in> s"  "0 \<le> u"  "0 \<le> v"  "u + v = 1"
+  shows "f (u *s x + v *s y) \<le> max (f x) (f y)"
+proof-
+  let ?m = "max (f x) (f y)"
+  have "u * f x + v * f y \<le> u * max (f x) (f y) + v * max (f x) (f y)" apply(rule add_mono) 
+    using assms(4,5) by(auto simp add: mult_mono1)
+  also have "\<dots> = max (f x) (f y)" using assms(6) unfolding distrib[THEN sym] by auto
+  finally show ?thesis using assms(1)[unfolded convex_on_def, THEN bspec[where x=x], THEN bspec[where x=y], THEN spec[where x=u]]
+    using assms(2-6) by auto 
+qed
+
+lemma convex_local_global_minimum:
+  assumes "0<e" "convex_on s f" "ball x e \<subseteq> s" "\<forall>y\<in>ball x e. f x \<le> f y"
+  shows "\<forall>y\<in>s. f x \<le> f y"
+proof(rule ccontr)
+  have "x\<in>s" using assms(1,3) by auto
+  assume "\<not> (\<forall>y\<in>s. f x \<le> f y)"
+  then obtain y where "y\<in>s" and y:"f x > f y" by auto
+  hence xy:"0 < dist x y" by (auto simp add: dist_nz[THEN sym])
+
+  then obtain u where "0 < u" "u \<le> 1" and u:"u < e / dist x y"
+    using real_lbound_gt_zero[of 1 "e / dist x y"] using xy `e>0` and divide_pos_pos[of e "dist x y"] by auto
+  hence "f ((1-u) *s x + u *s y) \<le> (1-u) * f x + u * f y" using `x\<in>s` `y\<in>s`
+    using assms(2)[unfolded convex_on_def, THEN bspec[where x=x], THEN bspec[where x=y], THEN spec[where x="1-u"]] by auto
+  moreover
+  have *:"x - ((1 - u) *s x + u *s y) = u *s (x - y)" by (simp add: vector_ssub_ldistrib vector_sub_rdistrib)
+  have "(1 - u) *s x + u *s y \<in> ball x e" unfolding mem_ball dist_norm unfolding * and norm_mul and abs_of_pos[OF `0<u`] unfolding dist_norm[THEN sym]
+    using u unfolding pos_less_divide_eq[OF xy] by auto
+  hence "f x \<le> f ((1 - u) *s x + u *s y)" using assms(4) by auto
+  ultimately show False using mult_strict_left_mono[OF y `u>0`] unfolding left_diff_distrib by auto
+qed
+
+lemma convex_distance: "convex_on s (\<lambda>x. dist a x)"
+proof(auto simp add: convex_on_def dist_norm)
+  fix x y assume "x\<in>s" "y\<in>s"
+  fix u v ::real assume "0 \<le> u" "0 \<le> v" "u + v = 1"
+  have "a = u *s a + v *s a" unfolding vector_sadd_rdistrib[THEN sym] and `u+v=1` by simp
+  hence *:"a - (u *s x + v *s y) = (u *s (a - x)) + (v *s (a - y))" by auto
+  show "norm (a - (u *s x + v *s y)) \<le> u * norm (a - x) + v * norm (a - y)"
+    unfolding * using norm_triangle_ineq[of "u *s (a - x)" "v *s (a - y)"] unfolding norm_mul
+    using `0 \<le> u` `0 \<le> v` by auto
+qed
+
+subsection {* Arithmetic operations on sets preserve convexity. *}
+
+lemma convex_scaling: "convex s \<Longrightarrow> convex ((\<lambda>x. c *s x) ` s)"
+  unfolding convex_def and image_iff apply auto
+  apply (rule_tac x="u *s x+v *s y" in bexI) by (auto simp add: field_simps)
+
+lemma convex_negations: "convex s \<Longrightarrow> convex ((\<lambda>x. -x)` s)"
+  unfolding convex_def and image_iff apply auto
+  apply (rule_tac x="u *s x+v *s y" in bexI) by auto
+
+lemma convex_sums:
+  assumes "convex s" "convex t"
+  shows "convex {x + y| x y. x \<in> s \<and> y \<in> t}"
+proof(auto simp add: convex_def image_iff)
+  fix xa xb ya yb assume xy:"xa\<in>s" "xb\<in>s" "ya\<in>t" "yb\<in>t"
+  fix u v ::real assume uv:"0 \<le> u" "0 \<le> v" "u + v = 1"
+  show "\<exists>x y. u *s xa + u *s ya + (v *s xb + v *s yb) = x + y \<and> x \<in> s \<and> y \<in> t"
+    apply(rule_tac x="u *s xa + v *s xb" in exI) apply(rule_tac x="u *s ya + v *s yb" in exI)
+    using assms(1)[unfolded convex_def, THEN bspec[where x=xa], THEN bspec[where x=xb]]
+    using assms(2)[unfolded convex_def, THEN bspec[where x=ya], THEN bspec[where x=yb]]
+    using uv xy by auto
+qed
+
+lemma convex_differences: 
+  assumes "convex s" "convex t"
+  shows "convex {x - y| x y. x \<in> s \<and> y \<in> t}"
+proof-
+  have "{x - y| x y. x \<in> s \<and> y \<in> t} = {x + y |x y. x \<in> s \<and> y \<in> uminus ` t}" unfolding image_iff apply auto
+    apply(rule_tac x=xa in exI) apply(rule_tac x="-y" in exI) apply simp
+    apply(rule_tac x=xa in exI) apply(rule_tac x=xb in exI) by simp
+  thus ?thesis using convex_sums[OF assms(1)  convex_negations[OF assms(2)]] by auto
+qed
+
+lemma convex_translation: assumes "convex s" shows "convex ((\<lambda>x. a + x) ` s)"
+proof- have "{a + y |y. y \<in> s} = (\<lambda>x. a + x) ` s" by auto
+  thus ?thesis using convex_sums[OF convex_singleton[of a] assms] by auto qed
+
+lemma convex_affinity: assumes "convex (s::(real^'n) set)" shows "convex ((\<lambda>x. a + c *s x) ` s)"
+proof- have "(\<lambda>x. a + c *s x) ` s = op + a ` op *s c ` s" by auto
+  thus ?thesis using convex_translation[OF convex_scaling[OF assms], of a c] by auto qed
+
+lemma convex_linear_image: assumes c:"convex s" and l:"linear f" shows "convex(f ` s)"
+proof(auto simp add: convex_def)
+  fix x y assume xy:"x \<in> s" "y \<in> s"
+  fix u v ::real assume uv:"0 \<le> u" "0 \<le> v" "u + v = 1"
+  show "u *s f x + v *s f y \<in> f ` s" unfolding image_iff
+    apply(rule_tac x="u *s x + v *s y" in bexI)
+    unfolding linear_add[OF l] linear_cmul[OF l] 
+    using c[unfolded convex_def] xy uv by auto
+qed
+
+subsection {* Balls, being convex, are connected. *}
+
+lemma convex_ball: "convex (ball x e)" 
+proof(auto simp add: convex_def)
+  fix y z assume yz:"dist x y < e" "dist x z < e"
+  fix u v ::real assume uv:"0 \<le> u" "0 \<le> v" "u + v = 1"
+  have "dist x (u *s y + v *s z) \<le> u * dist x y + v * dist x z" using uv yz
+    using convex_distance[of "ball x e" x, unfolded convex_on_def, THEN bspec[where x=y], THEN bspec[where x=z]] by auto
+  thus "dist x (u *s y + v *s z) < e" using real_convex_bound_lt[OF yz uv] by auto 
+qed
+
+lemma convex_cball: "convex(cball x e)"
+proof(auto simp add: convex_def Ball_def mem_cball)
+  fix y z assume yz:"dist x y \<le> e" "dist x z \<le> e"
+  fix u v ::real assume uv:" 0 \<le> u" "0 \<le> v" "u + v = 1"
+  have "dist x (u *s y + v *s z) \<le> u * dist x y + v * dist x z" using uv yz
+    using convex_distance[of "cball x e" x, unfolded convex_on_def, THEN bspec[where x=y], THEN bspec[where x=z]] by auto
+  thus "dist x (u *s y + v *s z) \<le> e" using real_convex_bound_le[OF yz uv] by auto 
+qed
+
+lemma connected_ball: "connected(ball (x::real^_) e)" (* FIXME: generalize *)
+  using convex_connected convex_ball by auto
+
+lemma connected_cball: "connected(cball (x::real^_) e)" (* FIXME: generalize *)
+  using convex_connected convex_cball by auto
+
+subsection {* Convex hull. *}
+
+lemma convex_convex_hull: "convex(convex hull s)"
+  unfolding hull_def using convex_Inter[of "{t\<in>convex. s\<subseteq>t}"]
+  unfolding mem_def by auto
+
+lemma convex_hull_eq: "(convex hull s = s) \<longleftrightarrow> convex s" apply(rule hull_eq[unfolded mem_def])
+  using convex_Inter[unfolded Ball_def mem_def] by auto
+
+lemma bounded_convex_hull: assumes "bounded s" shows "bounded(convex hull s)"
+proof- from assms obtain B where B:"\<forall>x\<in>s. norm x \<le> B" unfolding bounded_def by auto
+  show ?thesis apply(rule bounded_subset[OF bounded_cball, of _ 0 B])
+    unfolding subset_hull[unfolded mem_def, of convex, OF convex_cball]
+    unfolding subset_eq mem_cball dist_norm using B by auto qed
+
+lemma finite_imp_bounded_convex_hull:
+  "finite s \<Longrightarrow> bounded(convex hull s)"
+  using bounded_convex_hull finite_imp_bounded by auto
+
+subsection {* Stepping theorems for convex hulls of finite sets. *}
+
+lemma convex_hull_empty[simp]: "convex hull {} = {}"
+  apply(rule hull_unique) unfolding mem_def by auto
+
+lemma convex_hull_singleton[simp]: "convex hull {a} = {a}"
+  apply(rule hull_unique) unfolding mem_def by auto
+
+lemma convex_hull_insert:
+  assumes "s \<noteq> {}"
+  shows "convex hull (insert a s) = {x. \<exists>u\<ge>0. \<exists>v\<ge>0. \<exists>b. (u + v = 1) \<and>
+                                    b \<in> (convex hull s) \<and> (x = u *s a + v *s b)}" (is "?xyz = ?hull")
+ apply(rule,rule hull_minimal,rule) unfolding mem_def[of _ convex] and insert_iff prefer 3 apply rule proof-
+ fix x assume x:"x = a \<or> x \<in> s"
+ thus "x\<in>?hull" apply rule unfolding mem_Collect_eq apply(rule_tac x=1 in exI) defer 
+   apply(rule_tac x=0 in exI) using assms hull_subset[of s convex] by auto
+next
+  fix x assume "x\<in>?hull"
+  then obtain u v b where obt:"u\<ge>0" "v\<ge>0" "u + v = 1" "b \<in> convex hull s" "x = u *s a + v *s b" by auto
+  have "a\<in>convex hull insert a s" "b\<in>convex hull insert a s"
+    using hull_mono[of s "insert a s" convex] hull_mono[of "{a}" "insert a s" convex] and obt(4) by auto
+  thus "x\<in> convex hull insert a s" unfolding obt(5) using convex_convex_hull[of "insert a s", unfolded convex_def]
+    apply(erule_tac x=a in ballE) apply(erule_tac x=b in ballE) apply(erule_tac x=u in allE) using obt by auto
+next
+  show "convex ?hull" unfolding convex_def apply(rule,rule,rule,rule,rule,rule,rule) proof-
+    fix x y u v assume as:"(0::real) \<le> u" "0 \<le> v" "u + v = 1" "x\<in>?hull" "y\<in>?hull"
+    from as(4) obtain u1 v1 b1 where obt1:"u1\<ge>0" "v1\<ge>0" "u1 + v1 = 1" "b1 \<in> convex hull s" "x = u1 *s a + v1 *s b1" by auto
+    from as(5) obtain u2 v2 b2 where obt2:"u2\<ge>0" "v2\<ge>0" "u2 + v2 = 1" "b2 \<in> convex hull s" "y = u2 *s a + v2 *s b2" by auto
+    have *:"\<And>x s1 s2. x - s1 *s x - s2 *s x = ((1::real) - (s1 + s2)) *s x" by auto
+    have "\<exists>b \<in> convex hull s. u *s x + v *s y = (u * u1) *s a + (v * u2) *s a + (b - (u * u1) *s b - (v * u2) *s b)"
+    proof(cases "u * v1 + v * v2 = 0")
+      have *:"\<And>x s1 s2. x - s1 *s x - s2 *s x = ((1::real) - (s1 + s2)) *s x" by auto
+      case True hence **:"u * v1 = 0" "v * v2 = 0" apply- apply(rule_tac [!] ccontr)
+	using mult_nonneg_nonneg[OF `u\<ge>0` `v1\<ge>0`] mult_nonneg_nonneg[OF `v\<ge>0` `v2\<ge>0`] by auto
+      hence "u * u1 + v * u2 = 1" using as(3) obt1(3) obt2(3) by auto
+      thus ?thesis unfolding obt1(5) obt2(5) * using assms hull_subset[of s convex] by(auto simp add: **) 
+    next
+      have "1 - (u * u1 + v * u2) = (u + v) - (u * u1 + v * u2)" using as(3) obt1(3) obt2(3) by (auto simp add: field_simps)
+      also have "\<dots> = u * (v1 + u1 - u1) + v * (v2 + u2 - u2)" using as(3) obt1(3) obt2(3) by (auto simp add: field_simps) 
+      also have "\<dots> = u * v1 + v * v2" by simp finally have **:"1 - (u * u1 + v * u2) = u * v1 + v * v2" by auto
+      case False have "0 \<le> u * v1 + v * v2" "0 \<le> u * v1" "0 \<le> u * v1 + v * v2" "0 \<le> v * v2" apply -
+	apply(rule add_nonneg_nonneg) prefer 4 apply(rule add_nonneg_nonneg) apply(rule_tac [!] mult_nonneg_nonneg)
+	using as(1,2) obt1(1,2) obt2(1,2) by auto 
+      thus ?thesis unfolding obt1(5) obt2(5) unfolding * and ** using False
+	apply(rule_tac x="((u * v1) / (u * v1 + v * v2)) *s b1 + ((v * v2) / (u * v1 + v * v2)) *s b2" in bexI) defer
+	apply(rule convex_convex_hull[of s, unfolded convex_def, rule_format]) using obt1(4) obt2(4)
+	unfolding add_divide_distrib[THEN sym] and real_0_le_divide_iff by auto
+    qed note * = this
+    have u1:"u1 \<le> 1" apply(rule ccontr) unfolding obt1(3)[THEN sym] and not_le using obt1(2) by auto
+    have u2:"u2 \<le> 1" apply(rule ccontr) unfolding obt2(3)[THEN sym] and not_le using obt2(2) by auto
+    have "u1 * u + u2 * v \<le> (max u1 u2) * u + (max u1 u2) * v" apply(rule add_mono)
+      apply(rule_tac [!] mult_right_mono) using as(1,2) obt1(1,2) obt2(1,2) by auto
+    also have "\<dots> \<le> 1" unfolding mult.add_right[THEN sym] and as(3) using u1 u2 by auto
+    finally 
+    show "u *s x + v *s y \<in> ?hull" unfolding mem_Collect_eq apply(rule_tac x="u * u1 + v * u2" in exI)
+      apply(rule conjI) defer apply(rule_tac x="1 - u * u1 - v * u2" in exI) unfolding Bex_def
+      using as(1,2) obt1(1,2) obt2(1,2) * by(auto intro!: mult_nonneg_nonneg add_nonneg_nonneg simp add:field_simps)
+  qed
+qed
+
+
+subsection {* Explicit expression for convex hull. *}
+
+lemma convex_hull_indexed:
+  "convex hull s = {y. \<exists>k u x. (\<forall>i\<in>{1::nat .. k}. 0 \<le> u i \<and> x i \<in> s) \<and>
+                            (setsum u {1..k} = 1) \<and>
+                            (setsum (\<lambda>i. u i *s x i) {1..k} = y)}" (is "?xyz = ?hull")
+  apply(rule hull_unique) unfolding mem_def[of _ convex] apply(rule) defer
+  apply(subst convex_def) apply(rule,rule,rule,rule,rule,rule,rule)
+proof-
+  fix x assume "x\<in>s"
+  thus "x \<in> ?hull" unfolding mem_Collect_eq apply(rule_tac x=1 in exI, rule_tac x="\<lambda>x. 1" in exI) by auto
+next
+  fix t assume as:"s \<subseteq> t" "convex t"
+  show "?hull \<subseteq> t" apply(rule) unfolding mem_Collect_eq apply(erule exE | erule conjE)+ proof-
+    fix x k u y assume assm:"\<forall>i\<in>{1::nat..k}. 0 \<le> u i \<and> y i \<in> s" "setsum u {1..k} = 1" "(\<Sum>i = 1..k. u i *s y i) = x"
+    show "x\<in>t" unfolding assm(3)[THEN sym] apply(rule as(2)[unfolded convex, rule_format])
+      using assm(1,2) as(1) by auto qed
+next
+  fix x y u v assume uv:"0\<le>u" "0\<le>v" "u+v=(1::real)" and xy:"x\<in>?hull" "y\<in>?hull"
+  from xy obtain k1 u1 x1 where x:"\<forall>i\<in>{1::nat..k1}. 0\<le>u1 i \<and> x1 i \<in> s" "setsum u1 {Suc 0..k1} = 1" "(\<Sum>i = Suc 0..k1. u1 i *s x1 i) = x" by auto
+  from xy obtain k2 u2 x2 where y:"\<forall>i\<in>{1::nat..k2}. 0\<le>u2 i \<and> x2 i \<in> s" "setsum u2 {Suc 0..k2} = 1" "(\<Sum>i = Suc 0..k2. u2 i *s x2 i) = y" by auto
+  have *:"\<And>P x1 x2 s1 s2 i.(if P i then s1 else s2) *s (if P i then x1 else x2) = (if P i then s1 *s x1 else s2 *s x2)"
+    "{1..k1 + k2} \<inter> {1..k1} = {1..k1}" "{1..k1 + k2} \<inter> - {1..k1} = (\<lambda>i. i + k1) ` {1..k2}"
+    prefer 3 apply(rule,rule) unfolding image_iff apply(rule_tac x="x - k1" in bexI) by(auto simp add: not_le)
+  have inj:"inj_on (\<lambda>i. i + k1) {1..k2}" unfolding inj_on_def by auto  
+  show "u *s x + v *s y \<in> ?hull" apply(rule)
+    apply(rule_tac x="k1 + k2" in exI, rule_tac x="\<lambda>i. if i \<in> {1..k1} then u * u1 i else v * u2 (i - k1)" in exI)
+    apply(rule_tac x="\<lambda>i. if i \<in> {1..k1} then x1 i else x2 (i - k1)" in exI) apply(rule,rule) defer apply(rule)
+    unfolding * and setsum_cases[OF finite_atLeastAtMost[of 1 "k1 + k2"]] and setsum_reindex[OF inj] and o_def
+    unfolding vector_smult_assoc[THEN sym] setsum_cmul setsum_right_distrib[THEN sym] proof-
+    fix i assume i:"i \<in> {1..k1+k2}"
+    show "0 \<le> (if i \<in> {1..k1} then u * u1 i else v * u2 (i - k1)) \<and> (if i \<in> {1..k1} then x1 i else x2 (i - k1)) \<in> s"
+    proof(cases "i\<in>{1..k1}")
+      case True thus ?thesis using mult_nonneg_nonneg[of u "u1 i"] and uv(1) x(1)[THEN bspec[where x=i]] by auto
+    next def j \<equiv> "i - k1"
+      case False with i have "j \<in> {1..k2}" unfolding j_def by auto
+      thus ?thesis unfolding j_def[symmetric] using False
+	using mult_nonneg_nonneg[of v "u2 j"] and uv(2) y(1)[THEN bspec[where x=j]] by auto qed
+  qed(auto simp add: not_le x(2,3) y(2,3) uv(3))
+qed
+
+lemma convex_hull_finite:
+  assumes "finite (s::(real^'n)set)"
+  shows "convex hull s = {y. \<exists>u. (\<forall>x\<in>s. 0 \<le> u x) \<and>
+         setsum u s = 1 \<and> setsum (\<lambda>x. u x *s x) s = y}" (is "?HULL = ?set")
+proof(rule hull_unique, auto simp add: mem_def[of _ convex] convex_def[of ?set])
+  fix x assume "x\<in>s" thus " \<exists>u. (\<forall>x\<in>s. 0 \<le> u x) \<and> setsum u s = 1 \<and> (\<Sum>x\<in>s. u x *s x) = x" 
+    apply(rule_tac x="\<lambda>y. if x=y then 1 else 0" in exI) apply auto
+    unfolding setsum_delta'[OF assms] and setsum_delta''[OF assms] by auto 
+next
+  fix u v ::real assume uv:"0 \<le> u" "0 \<le> v" "u + v = 1"
+  fix ux assume ux:"\<forall>x\<in>s. 0 \<le> ux x" "setsum ux s = (1::real)"
+  fix uy assume uy:"\<forall>x\<in>s. 0 \<le> uy x" "setsum uy s = (1::real)"
+  { fix x assume "x\<in>s"
+    hence "0 \<le> u * ux x + v * uy x" using ux(1)[THEN bspec[where x=x]] uy(1)[THEN bspec[where x=x]] and uv(1,2)
+      by (auto, metis add_nonneg_nonneg mult_nonneg_nonneg uv(1) uv(2))  }
+  moreover have "(\<Sum>x\<in>s. u * ux x + v * uy x) = 1"
+    unfolding setsum_addf and setsum_right_distrib[THEN sym] and ux(2) uy(2) using uv(3) by auto
+  moreover have "(\<Sum>x\<in>s. (u * ux x + v * uy x) *s x) = u *s (\<Sum>x\<in>s. ux x *s x) + v *s (\<Sum>x\<in>s. uy x *s x)"
+    unfolding vector_sadd_rdistrib and setsum_addf and vector_smult_assoc[THEN sym] and setsum_cmul by auto
+  ultimately show "\<exists>uc. (\<forall>x\<in>s. 0 \<le> uc x) \<and> setsum uc s = 1 \<and> (\<Sum>x\<in>s. uc x *s x) = u *s (\<Sum>x\<in>s. ux x *s x) + v *s (\<Sum>x\<in>s. uy x *s x)"
+    apply(rule_tac x="\<lambda>x. u * ux x + v * uy x" in exI) by auto 
+next
+  fix t assume t:"s \<subseteq> t" "convex t" 
+  fix u assume u:"\<forall>x\<in>s. 0 \<le> u x" "setsum u s = (1::real)"
+  thus "(\<Sum>x\<in>s. u x *s x) \<in> t" using t(2)[unfolded convex_explicit, THEN spec[where x=s], THEN spec[where x=u]]
+    using assms and t(1) by auto
+qed
+
+subsection {* Another formulation from Lars Schewe. *}
+
+lemma convex_hull_explicit:
+  "convex hull p = {y. \<exists>s u. finite s \<and> s \<subseteq> p \<and>
+             (\<forall>x\<in>s. 0 \<le> u x) \<and> setsum u s = 1 \<and> setsum (\<lambda>v. u v *s v) s = y}" (is "?lhs = ?rhs")
+proof-
+  { fix x assume "x\<in>?lhs"
+    then obtain k u y where obt:"\<forall>i\<in>{1::nat..k}. 0 \<le> u i \<and> y i \<in> p" "setsum u {1..k} = 1" "(\<Sum>i = 1..k. u i *s y i) = x"
+      unfolding convex_hull_indexed by auto
+
+    have fin:"finite {1..k}" by auto
+    have fin':"\<And>v. finite {i \<in> {1..k}. y i = v}" by auto
+    { fix j assume "j\<in>{1..k}"
+      hence "y j \<in> p" "0 \<le> setsum u {i. Suc 0 \<le> i \<and> i \<le> k \<and> y i = y j}"
+	using obt(1)[THEN bspec[where x=j]] and obt(2) apply simp
+	apply(rule setsum_nonneg) using obt(1) by auto } 
+    moreover
+    have "(\<Sum>v\<in>y ` {1..k}. setsum u {i \<in> {1..k}. y i = v}) = 1"  
+      unfolding setsum_image_gen[OF fin, THEN sym] using obt(2) by auto
+    moreover have "(\<Sum>v\<in>y ` {1..k}. setsum u {i \<in> {1..k}. y i = v} *s v) = x"
+      using setsum_image_gen[OF fin, of "\<lambda>i. u i *s y i" y, THEN sym]
+      unfolding setsum_vmul[OF fin']  using obt(3) by auto
+    ultimately have "\<exists>s u. finite s \<and> s \<subseteq> p \<and> (\<forall>x\<in>s. 0 \<le> u x) \<and> setsum u s = 1 \<and> (\<Sum>v\<in>s. u v *s v) = x"
+      apply(rule_tac x="y ` {1..k}" in exI)
+      apply(rule_tac x="\<lambda>v. setsum u {i\<in>{1..k}. y i = v}" in exI) by auto
+    hence "x\<in>?rhs" by auto  }
+  moreover
+  { fix y assume "y\<in>?rhs"
+    then obtain s u where obt:"finite s" "s \<subseteq> p" "\<forall>x\<in>s. 0 \<le> u x" "setsum u s = 1" "(\<Sum>v\<in>s. u v *s v) = y" by auto
+
+    obtain f where f:"inj_on f {1..card s}" "f ` {1..card s} = s" using ex_bij_betw_nat_finite_1[OF obt(1)] unfolding bij_betw_def by auto
+    
+    { fix i::nat assume "i\<in>{1..card s}"
+      hence "f i \<in> s"  apply(subst f(2)[THEN sym]) by auto
+      hence "0 \<le> u (f i)" "f i \<in> p" using obt(2,3) by auto  }
+    moreover have *:"finite {1..card s}" by auto
+    { fix y assume "y\<in>s"
+      then obtain i where "i\<in>{1..card s}" "f i = y" using f using image_iff[of y f "{1..card s}"] by auto
+      hence "{x. Suc 0 \<le> x \<and> x \<le> card s \<and> f x = y} = {i}" apply auto using f(1)[unfolded inj_on_def] apply(erule_tac x=x in ballE) by auto
+      hence "card {x. Suc 0 \<le> x \<and> x \<le> card s \<and> f x = y} = 1" by auto
+      hence "(\<Sum>x\<in>{x \<in> {1..card s}. f x = y}. u (f x)) = u y" "(\<Sum>x\<in>{x \<in> {1..card s}. f x = y}. u (f x) *s f x) = u y *s y" by auto   }
+
+    hence "(\<Sum>x = 1..card s. u (f x)) = 1" "(\<Sum>i = 1..card s. u (f i) *s f i) = y"
+      unfolding setsum_image_gen[OF *(1), of "\<lambda>x. u (f x) *s f x" f] and setsum_image_gen[OF *(1), of "\<lambda>x. u (f x)" f] 
+      unfolding f using setsum_cong2[of s "\<lambda>y. (\<Sum>x\<in>{x \<in> {1..card s}. f x = y}. u (f x) *s f x)" "\<lambda>v. u v *s v"]
+      using setsum_cong2 [of s "\<lambda>y. (\<Sum>x\<in>{x \<in> {1..card s}. f x = y}. u (f x))" u] unfolding obt(4,5) by auto
+    
+    ultimately have "\<exists>k u x. (\<forall>i\<in>{1..k}. 0 \<le> u i \<and> x i \<in> p) \<and> setsum u {1..k} = 1 \<and> (\<Sum>i::nat = 1..k. u i *s x i) = y"
+      apply(rule_tac x="card s" in exI) apply(rule_tac x="u \<circ> f" in exI) apply(rule_tac x=f in exI) by fastsimp
+    hence "y \<in> ?lhs" unfolding convex_hull_indexed by auto  }
+  ultimately show ?thesis unfolding expand_set_eq by blast
+qed
+
+subsection {* A stepping theorem for that expansion. *}
+
+lemma convex_hull_finite_step:
+  assumes "finite (s::(real^'n) set)"
+  shows "(\<exists>u. (\<forall>x\<in>insert a s. 0 \<le> u x) \<and> setsum u (insert a s) = w \<and> setsum (\<lambda>x. u x *s x) (insert a s) = y)
+     \<longleftrightarrow> (\<exists>v\<ge>0. \<exists>u. (\<forall>x\<in>s. 0 \<le> u x) \<and> setsum u s = w - v \<and> setsum (\<lambda>x. u x *s x) s = y - v *s a)" (is "?lhs = ?rhs")
+proof(rule, case_tac[!] "a\<in>s")
+  assume "a\<in>s" hence *:"insert a s = s" by auto
+  assume ?lhs thus ?rhs unfolding * apply(rule_tac x=0 in exI) by auto
+next
+  assume ?lhs then obtain u where u:"\<forall>x\<in>insert a s. 0 \<le> u x" "setsum u (insert a s) = w" "(\<Sum>x\<in>insert a s. u x *s x) = y" by auto
+  assume "a\<notin>s" thus ?rhs apply(rule_tac x="u a" in exI) using u(1)[THEN bspec[where x=a]] apply simp
+    apply(rule_tac x=u in exI) using u[unfolded setsum_clauses(2)[OF assms]] and `a\<notin>s` by auto
+next
+  assume "a\<in>s" hence *:"insert a s = s" by auto
+  have fin:"finite (insert a s)" using assms by auto
+  assume ?rhs then obtain v u where uv:"v\<ge>0" "\<forall>x\<in>s. 0 \<le> u x" "setsum u s = w - v" "(\<Sum>x\<in>s. u x *s x) = y - v *s a" by auto
+  show ?lhs apply(rule_tac x="\<lambda>x. (if a = x then v else 0) + u x" in exI) unfolding vector_sadd_rdistrib and setsum_addf and setsum_delta''[OF fin] and setsum_delta'[OF fin]
+    unfolding setsum_clauses(2)[OF assms] using uv and uv(2)[THEN bspec[where x=a]] and `a\<in>s` by auto
+next
+  assume ?rhs then obtain v u where uv:"v\<ge>0" "\<forall>x\<in>s. 0 \<le> u x" "setsum u s = w - v" "(\<Sum>x\<in>s. u x *s x) = y - v *s a" by auto
+  moreover assume "a\<notin>s" moreover have "(\<Sum>x\<in>s. if a = x then v else u x) = setsum u s" "(\<Sum>x\<in>s. (if a = x then v else u x) *s x) = (\<Sum>x\<in>s. u x *s x)"
+    apply(rule_tac setsum_cong2) defer apply(rule_tac setsum_cong2) using `a\<notin>s` by auto
+  ultimately show ?lhs apply(rule_tac x="\<lambda>x. if a = x then v else u x" in exI)  unfolding setsum_clauses(2)[OF assms] by auto
+qed
+
+subsection {* Hence some special cases. *}
+
+lemma convex_hull_2:
+  "convex hull {a,b} = {u *s a + v *s b | u v. 0 \<le> u \<and> 0 \<le> v \<and> u + v = 1}"
+proof- have *:"\<And>u. (\<forall>x\<in>{a, b}. 0 \<le> u x) \<longleftrightarrow> 0 \<le> u a \<and> 0 \<le> u b" by auto have **:"finite {b}" by auto
+show ?thesis apply(simp add: convex_hull_finite) unfolding convex_hull_finite_step[OF **, of a 1, unfolded * conj_assoc]
+  apply auto apply(rule_tac x=v in exI) apply(rule_tac x="1 - v" in exI) apply simp
+  apply(rule_tac x=u in exI) apply simp apply(rule_tac x="\<lambda>x. v" in exI) by simp qed
+
+lemma convex_hull_2_alt: "convex hull {a,b} = {a + u *s (b - a) | u.  0 \<le> u \<and> u \<le> 1}"
+  unfolding convex_hull_2 unfolding Collect_def 
+proof(rule ext) have *:"\<And>x y ::real. x + y = 1 \<longleftrightarrow> x = 1 - y" by auto
+  fix x show "(\<exists>v u. x = v *s a + u *s b \<and> 0 \<le> v \<and> 0 \<le> u \<and> v + u = 1) = (\<exists>u. x = a + u *s (b - a) \<and> 0 \<le> u \<and> u \<le> 1)"
+    unfolding * apply auto apply(rule_tac[!] x=u in exI) by auto qed
+
+lemma convex_hull_3:
+  "convex hull {a::real^'n,b,c} = { u *s a + v *s b + w *s c | u v w. 0 \<le> u \<and> 0 \<le> v \<and> 0 \<le> w \<and> u + v + w = 1}"
+proof-
+  have fin:"finite {a,b,c}" "finite {b,c}" "finite {c}" by auto
+  have *:"\<And>x y z ::real. x + y + z = 1 \<longleftrightarrow> x = 1 - y - z"
+         "\<And>x y z ::real^'n. x + y + z = 1 \<longleftrightarrow> x = 1 - y - z" by (auto simp add: ring_simps)
+  show ?thesis unfolding convex_hull_finite[OF fin(1)] and Collect_def and convex_hull_finite_step[OF fin(2)] and *
+    unfolding convex_hull_finite_step[OF fin(3)] apply(rule ext) apply simp apply auto
+    apply(rule_tac x=va in exI) apply (rule_tac x="u c" in exI) apply simp
+    apply(rule_tac x="1 - v - w" in exI) apply simp apply(rule_tac x=v in exI) apply simp apply(rule_tac x="\<lambda>x. w" in exI) by simp qed
+
+lemma convex_hull_3_alt:
+  "convex hull {a,b,c} = {a + u *s (b - a) + v *s (c - a) | u v.  0 \<le> u \<and> 0 \<le> v \<and> u + v \<le> 1}"
+proof- have *:"\<And>x y z ::real. x + y + z = 1 \<longleftrightarrow> x = 1 - y - z" by auto
+  show ?thesis unfolding convex_hull_3 apply (auto simp add: *) apply(rule_tac x=v in exI) apply(rule_tac x=w in exI) apply simp
+    apply(rule_tac x=u in exI) apply(rule_tac x=v in exI) by simp qed
+
+subsection {* Relations among closure notions and corresponding hulls. *}
+
+lemma subspace_imp_affine: "subspace s \<Longrightarrow> affine s"
+  unfolding subspace_def affine_def by auto
+
+lemma affine_imp_convex: "affine s \<Longrightarrow> convex s"
+  unfolding affine_def convex_def by auto
+
+lemma subspace_imp_convex: "subspace s \<Longrightarrow> convex s"
+  using subspace_imp_affine affine_imp_convex by auto
+
+lemma affine_hull_subset_span: "(affine hull s) \<subseteq> (span s)"
+  unfolding span_def apply(rule hull_antimono) unfolding subset_eq Ball_def mem_def
+  using subspace_imp_affine  by auto
+
+lemma convex_hull_subset_span: "(convex hull s) \<subseteq> (span s)"
+  unfolding span_def apply(rule hull_antimono) unfolding subset_eq Ball_def mem_def
+  using subspace_imp_convex by auto
+
+lemma convex_hull_subset_affine_hull: "(convex hull s) \<subseteq> (affine hull s)"
+  unfolding span_def apply(rule hull_antimono) unfolding subset_eq Ball_def mem_def
+  using affine_imp_convex by auto
+
+lemma affine_dependent_imp_dependent: "affine_dependent s \<Longrightarrow> dependent s"
+  unfolding affine_dependent_def dependent_def 
+  using affine_hull_subset_span by auto
+
+lemma dependent_imp_affine_dependent:
+  assumes "dependent {x - a| x . x \<in> s}" "a \<notin> s"
+  shows "affine_dependent (insert a s)"
+proof-
+  from assms(1)[unfolded dependent_explicit] obtain S u v 
+    where obt:"finite S" "S \<subseteq> {x - a |x. x \<in> s}" "v\<in>S" "u v  \<noteq> 0" "(\<Sum>v\<in>S. u v *s v) = 0" by auto
+  def t \<equiv> "(\<lambda>x. x + a) ` S"
+
+  have inj:"inj_on (\<lambda>x. x + a) S" unfolding inj_on_def by auto
+  have "0\<notin>S" using obt(2) assms(2) unfolding subset_eq by auto
+  have fin:"finite t" and  "t\<subseteq>s" unfolding t_def using obt(1,2) by auto 
+
+  hence "finite (insert a t)" and "insert a t \<subseteq> insert a s" by auto 
+  moreover have *:"\<And>P Q. (\<Sum>x\<in>t. (if x = a then P x else Q x)) = (\<Sum>x\<in>t. Q x)"
+    apply(rule setsum_cong2) using `a\<notin>s` `t\<subseteq>s` by auto
+  have "(\<Sum>x\<in>insert a t. if x = a then - (\<Sum>x\<in>t. u (x - a)) else u (x - a)) = 0"
+    unfolding setsum_clauses(2)[OF fin] using `a\<notin>s` `t\<subseteq>s` apply auto unfolding * by auto
+  moreover have "\<exists>v\<in>insert a t. (if v = a then - (\<Sum>x\<in>t. u (x - a)) else u (v - a)) \<noteq> 0"
+    apply(rule_tac x="v + a" in bexI) using obt(3,4) and `0\<notin>S` unfolding t_def by auto
+  moreover have *:"\<And>P Q. (\<Sum>x\<in>t. (if x = a then P x else Q x) *s x) = (\<Sum>x\<in>t. Q x *s x)"
+    apply(rule setsum_cong2) using `a\<notin>s` `t\<subseteq>s` by auto
+  have "(\<Sum>x\<in>t. u (x - a)) *s a = (\<Sum>v\<in>t. u (v - a) *s v)" 
+    unfolding setsum_vmul[OF fin(1)] unfolding t_def and setsum_reindex[OF inj] and o_def
+    using obt(5) by (auto simp add: setsum_addf)
+  hence "(\<Sum>v\<in>insert a t. (if v = a then - (\<Sum>x\<in>t. u (x - a)) else u (v - a)) *s v) = 0"
+    unfolding setsum_clauses(2)[OF fin] using `a\<notin>s` `t\<subseteq>s` by (auto simp add: *  vector_smult_lneg) 
+  ultimately show ?thesis unfolding affine_dependent_explicit
+    apply(rule_tac x="insert a t" in exI) by auto 
+qed
+
+lemma convex_cone:
+  "convex s \<and> cone s \<longleftrightarrow> (\<forall>x\<in>s. \<forall>y\<in>s. (x + y) \<in> s) \<and> (\<forall>x\<in>s. \<forall>c\<ge>0. (c *s x) \<in> s)" (is "?lhs = ?rhs")
+proof-
+  { fix x y assume "x\<in>s" "y\<in>s" and ?lhs
+    hence "2 *s x \<in>s" "2 *s y \<in> s" unfolding cone_def by auto
+    hence "x + y \<in> s" using `?lhs`[unfolded convex_def, THEN conjunct1]
+      apply(erule_tac x="2*s x" in ballE) apply(erule_tac x="2*s y" in ballE)
+      apply(erule_tac x="1/2" in allE) apply simp apply(erule_tac x="1/2" in allE) by auto  }
+  thus ?thesis unfolding convex_def cone_def by blast
+qed
+
+lemma affine_dependent_biggerset: fixes s::"(real^'n::finite) set"
+  assumes "finite s" "card s \<ge> CARD('n) + 2"
+  shows "affine_dependent s"
+proof-
+  have "s\<noteq>{}" using assms by auto then obtain a where "a\<in>s" by auto
+  have *:"{x - a |x. x \<in> s - {a}} = (\<lambda>x. x - a) ` (s - {a})" by auto
+  have "card {x - a |x. x \<in> s - {a}} = card (s - {a})" unfolding * 
+    apply(rule card_image) unfolding inj_on_def by auto
+  also have "\<dots> > CARD('n)" using assms(2)
+    unfolding card_Diff_singleton[OF assms(1) `a\<in>s`] by auto
+  finally show ?thesis apply(subst insert_Diff[OF `a\<in>s`, THEN sym])
+    apply(rule dependent_imp_affine_dependent)
+    apply(rule dependent_biggerset) by auto qed
+
+lemma affine_dependent_biggerset_general:
+  assumes "finite (s::(real^'n::finite) set)" "card s \<ge> dim s + 2"
+  shows "affine_dependent s"
+proof-
+  from assms(2) have "s \<noteq> {}" by auto
+  then obtain a where "a\<in>s" by auto
+  have *:"{x - a |x. x \<in> s - {a}} = (\<lambda>x. x - a) ` (s - {a})" by auto
+  have **:"card {x - a |x. x \<in> s - {a}} = card (s - {a})" unfolding * 
+    apply(rule card_image) unfolding inj_on_def by auto
+  have "dim {x - a |x. x \<in> s - {a}} \<le> dim s"
+    apply(rule subset_le_dim) unfolding subset_eq
+    using `a\<in>s` by (auto simp add:span_superset span_sub)
+  also have "\<dots> < dim s + 1" by auto
+  also have "\<dots> \<le> card (s - {a})" using assms
+    using card_Diff_singleton[OF assms(1) `a\<in>s`] by auto
+  finally show ?thesis apply(subst insert_Diff[OF `a\<in>s`, THEN sym])
+    apply(rule dependent_imp_affine_dependent) apply(rule dependent_biggerset_general) unfolding ** by auto qed
+
+subsection {* Caratheodory's theorem. *}
+
+lemma convex_hull_caratheodory: fixes p::"(real^'n::finite) set"
+  shows "convex hull p = {y. \<exists>s u. finite s \<and> s \<subseteq> p \<and> card s \<le> CARD('n) + 1 \<and>
+  (\<forall>x\<in>s. 0 \<le> u x) \<and> setsum u s = 1 \<and> setsum (\<lambda>v. u v *s v) s = y}"
+  unfolding convex_hull_explicit expand_set_eq mem_Collect_eq
+proof(rule,rule)
+  fix y let ?P = "\<lambda>n. \<exists>s u. finite s \<and> card s = n \<and> s \<subseteq> p \<and> (\<forall>x\<in>s. 0 \<le> u x) \<and> setsum u s = 1 \<and> (\<Sum>v\<in>s. u v *s v) = y"
+  assume "\<exists>s u. finite s \<and> s \<subseteq> p \<and> (\<forall>x\<in>s. 0 \<le> u x) \<and> setsum u s = 1 \<and> (\<Sum>v\<in>s. u v *s v) = y"
+  then obtain N where "?P N" by auto
+  hence "\<exists>n\<le>N. (\<forall>k<n. \<not> ?P k) \<and> ?P n" apply(rule_tac ex_least_nat_le) by auto
+  then obtain n where "?P n" and smallest:"\<forall>k<n. \<not> ?P k" by blast
+  then obtain s u where obt:"finite s" "card s = n" "s\<subseteq>p" "\<forall>x\<in>s. 0 \<le> u x" "setsum u s = 1"  "(\<Sum>v\<in>s. u v *s v) = y" by auto
+
+  have "card s \<le> CARD('n) + 1" proof(rule ccontr, simp only: not_le)
+    assume "CARD('n) + 1 < card s"
+    hence "affine_dependent s" using affine_dependent_biggerset[OF obt(1)] by auto
+    then obtain w v where wv:"setsum w s = 0" "v\<in>s" "w v \<noteq> 0" "(\<Sum>v\<in>s. w v *s v) = 0"
+      using affine_dependent_explicit_finite[OF obt(1)] by auto
+    def i \<equiv> "(\<lambda>v. (u v) / (- w v)) ` {v\<in>s. w v < 0}"  def t \<equiv> "Min i"
+    have "\<exists>x\<in>s. w x < 0" proof(rule ccontr, simp add: not_less)
+      assume as:"\<forall>x\<in>s. 0 \<le> w x"
+      hence "setsum w (s - {v}) \<ge> 0" apply(rule_tac setsum_nonneg) by auto
+      hence "setsum w s > 0" unfolding setsum_diff1'[OF obt(1) `v\<in>s`]
+	using as[THEN bspec[where x=v]] and `v\<in>s` using `w v \<noteq> 0` by auto
+      thus False using wv(1) by auto
+    qed hence "i\<noteq>{}" unfolding i_def by auto
+
+    hence "t \<ge> 0" using Min_ge_iff[of i 0 ] and obt(1) unfolding t_def i_def
+      using obt(4)[unfolded le_less] apply auto unfolding divide_le_0_iff by auto 
+    have t:"\<forall>v\<in>s. u v + t * w v \<ge> 0" proof
+      fix v assume "v\<in>s" hence v:"0\<le>u v" using obt(4)[THEN bspec[where x=v]] by auto
+      show"0 \<le> u v + t * w v" proof(cases "w v < 0")
+	case False thus ?thesis apply(rule_tac add_nonneg_nonneg) 
+	  using v apply simp apply(rule mult_nonneg_nonneg) using `t\<ge>0` by auto next
+	case True hence "t \<le> u v / (- w v)" using `v\<in>s`
+	  unfolding t_def i_def apply(rule_tac Min_le) using obt(1) by auto 
+	thus ?thesis unfolding real_0_le_add_iff
+	  using pos_le_divide_eq[OF True[unfolded neg_0_less_iff_less[THEN sym]]] by auto
+      qed qed
+
+    obtain a where "a\<in>s" and "t = (\<lambda>v. (u v) / (- w v)) a" and "w a < 0"
+      using Min_in[OF _ `i\<noteq>{}`] and obt(1) unfolding i_def t_def by auto
+    hence a:"a\<in>s" "u a + t * w a = 0" by auto
+    have *:"\<And>f. setsum f (s - {a}) = setsum f s - ((f a)::'a::ring)" unfolding setsum_diff1'[OF obt(1) `a\<in>s`] by auto 
+    have "(\<Sum>v\<in>s. u v + t * w v) = 1"
+      unfolding setsum_addf wv(1) setsum_right_distrib[THEN sym] obt(5) by auto
+    moreover have "(\<Sum>v\<in>s. u v *s v + (t * w v) *s v) - (u a *s a + (t * w a) *s a) = y" 
+      unfolding setsum_addf obt(6) vector_smult_assoc[THEN sym] setsum_cmul wv(4)
+      by (metis diff_0_right a(2) pth_5 pth_8 pth_d vector_mul_eq_0)
+    ultimately have "?P (n - 1)" apply(rule_tac x="(s - {a})" in exI)
+      apply(rule_tac x="\<lambda>v. u v + t * w v" in exI) using obt(1-3) and t and a by (auto simp add: *)
+    thus False using smallest[THEN spec[where x="n - 1"]] by auto qed
+  thus "\<exists>s u. finite s \<and> s \<subseteq> p \<and> card s \<le> CARD('n) + 1
+    \<and> (\<forall>x\<in>s. 0 \<le> u x) \<and> setsum u s = 1 \<and> (\<Sum>v\<in>s. u v *s v) = y" using obt by auto
+qed auto
+
+lemma caratheodory:
+ "convex hull p = {x::real^'n::finite. \<exists>s. finite s \<and> s \<subseteq> p \<and>
+      card s \<le> CARD('n) + 1 \<and> x \<in> convex hull s}"
+  unfolding expand_set_eq apply(rule, rule) unfolding mem_Collect_eq proof-
+  fix x assume "x \<in> convex hull p"
+  then obtain s u where "finite s" "s \<subseteq> p" "card s \<le> CARD('n) + 1"
+     "\<forall>x\<in>s. 0 \<le> u x" "setsum u s = 1" "(\<Sum>v\<in>s. u v *s v) = x"unfolding convex_hull_caratheodory by auto
+  thus "\<exists>s. finite s \<and> s \<subseteq> p \<and> card s \<le> CARD('n) + 1 \<and> x \<in> convex hull s"
+    apply(rule_tac x=s in exI) using hull_subset[of s convex]
+  using convex_convex_hull[unfolded convex_explicit, of s, THEN spec[where x=s], THEN spec[where x=u]] by auto
+next
+  fix x assume "\<exists>s. finite s \<and> s \<subseteq> p \<and> card s \<le> CARD('n) + 1 \<and> x \<in> convex hull s"
+  then obtain s where "finite s" "s \<subseteq> p" "card s \<le> CARD('n) + 1" "x \<in> convex hull s" by auto
+  thus "x \<in> convex hull p" using hull_mono[OF `s\<subseteq>p`] by auto
+qed
+
+subsection {* Openness and compactness are preserved by convex hull operation. *}
+
+lemma open_convex_hull:
+  assumes "open s"
+  shows "open(convex hull s)"
+  unfolding open_contains_cball convex_hull_explicit unfolding mem_Collect_eq ball_simps(10) 
+proof(rule, rule) fix a
+  assume "\<exists>sa u. finite sa \<and> sa \<subseteq> s \<and> (\<forall>x\<in>sa. 0 \<le> u x) \<and> setsum u sa = 1 \<and> (\<Sum>v\<in>sa. u v *s v) = a"
+  then obtain t u where obt:"finite t" "t\<subseteq>s" "\<forall>x\<in>t. 0 \<le> u x" "setsum u t = 1" "(\<Sum>v\<in>t. u v *s v) = a" by auto
+
+  from assms[unfolded open_contains_cball] obtain b where b:"\<forall>x\<in>s. 0 < b x \<and> cball x (b x) \<subseteq> s"
+    using bchoice[of s "\<lambda>x e. e>0 \<and> cball x e \<subseteq> s"] by auto
+  have "b ` t\<noteq>{}" unfolding i_def using obt by auto  def i \<equiv> "b ` t"
+
+  show "\<exists>e>0. cball a e \<subseteq> {y. \<exists>sa u. finite sa \<and> sa \<subseteq> s \<and> (\<forall>x\<in>sa. 0 \<le> u x) \<and> setsum u sa = 1 \<and> (\<Sum>v\<in>sa. u v *s v) = y}"
+    apply(rule_tac x="Min i" in exI) unfolding subset_eq apply rule defer apply rule unfolding mem_Collect_eq
+  proof-
+    show "0 < Min i" unfolding i_def and Min_gr_iff[OF finite_imageI[OF obt(1)] `b \` t\<noteq>{}`]
+      using b apply simp apply rule apply(erule_tac x=x in ballE) using `t\<subseteq>s` by auto
+  next  fix y assume "y \<in> cball a (Min i)"
+    hence y:"norm (a - y) \<le> Min i" unfolding dist_norm[THEN sym] by auto
+    { fix x assume "x\<in>t"
+      hence "Min i \<le> b x" unfolding i_def apply(rule_tac Min_le) using obt(1) by auto
+      hence "x + (y - a) \<in> cball x (b x)" using y unfolding mem_cball dist_norm by auto
+      moreover from `x\<in>t` have "x\<in>s" using obt(2) by auto
+      ultimately have "x + (y - a) \<in> s" using y and b[THEN bspec[where x=x]] unfolding subset_eq by auto }
+    moreover
+    have *:"inj_on (\<lambda>v. v + (y - a)) t" unfolding inj_on_def by auto
+    have "(\<Sum>v\<in>(\<lambda>v. v + (y - a)) ` t. u (v - (y - a))) = 1"
+      unfolding setsum_reindex[OF *] o_def using obt(4) by auto
+    moreover have "(\<Sum>v\<in>(\<lambda>v. v + (y - a)) ` t. u (v - (y - a)) *s v) = y"
+      unfolding setsum_reindex[OF *] o_def using obt(4,5)
+      by (simp add: setsum_addf setsum_subtractf setsum_vmul[OF obt(1), THEN sym]) 
+    ultimately show "\<exists>sa u. finite sa \<and> (\<forall>x\<in>sa. x \<in> s) \<and> (\<forall>x\<in>sa. 0 \<le> u x) \<and> setsum u sa = 1 \<and> (\<Sum>v\<in>sa. u v *s v) = y"
+      apply(rule_tac x="(\<lambda>v. v + (y - a)) ` t" in exI) apply(rule_tac x="\<lambda>v. u (v - (y - a))" in exI)
+      using obt(1, 3) by auto
+  qed
+qed
+
+
+lemma compact_convex_combinations:
+  assumes "compact s" "compact t"
+  shows "compact { (1 - u) *s x + u *s y | x y u. 0 \<le> u \<and> u \<le> 1 \<and> x \<in> s \<and> y \<in> t}"
+proof-
+  let ?X = "{ pastecart u w | u w. u \<in> {vec1 0 .. vec1 1} \<and> w \<in> { pastecart x y |x y. x \<in> s \<and> y \<in> t} }"
+  let ?h = "(\<lambda>z. (1 - dest_vec1(fstcart z)) *s fstcart(sndcart z) + dest_vec1(fstcart z) *s sndcart(sndcart z))"
+  have *:"{ (1 - u) *s x + u *s y | x y u. 0 \<le> u \<and> u \<le> 1 \<and> x \<in> s \<and> y \<in> t} = ?h ` ?X"
+    apply(rule set_ext) unfolding image_iff mem_Collect_eq unfolding mem_interval_1 vec1_dest_vec1
+    apply rule apply auto apply(rule_tac x="pastecart (vec1 u) (pastecart xa y)" in exI) apply simp
+    apply(rule_tac x="vec1 u" in exI) apply(rule_tac x="pastecart xa y" in exI) by auto 
+  { fix u::"real^1" fix x y assume as:"0 \<le> dest_vec1 u" "dest_vec1 u \<le> 1" "x \<in> s" "y \<in> t"
+    hence "continuous (at (pastecart u (pastecart x y)))
+           (\<lambda>z. fstcart (sndcart z) - dest_vec1 (fstcart z) *s fstcart (sndcart z) +
+                dest_vec1 (fstcart z) *s sndcart (sndcart z))"
+      apply (auto intro!: continuous_add continuous_sub continuous_mul simp add: o_def vec1_dest_vec1)
+      using linear_continuous_at linear_fstcart linear_sndcart linear_sndcart
+      using linear_compose[unfolded o_def] by auto }
+  hence "continuous_on {pastecart u w |u w. u \<in> {vec1 0..vec1 1} \<and> w \<in> {pastecart x y |x y. x \<in> s \<and> y \<in> t}}
+     (\<lambda>z. (1 - dest_vec1 (fstcart z)) *s fstcart (sndcart z) + dest_vec1 (fstcart z) *s sndcart (sndcart z))"
+    apply(rule_tac continuous_at_imp_continuous_on) unfolding mem_Collect_eq
+    unfolding mem_interval_1 vec1_dest_vec1 by auto
+ thus ?thesis unfolding * apply(rule compact_continuous_image)
+    defer apply(rule compact_pastecart) defer apply(rule compact_pastecart)
+    using compact_interval assms by auto
+qed
+
+lemma compact_convex_hull: fixes s::"(real^'n::finite) set"
+  assumes "compact s"  shows "compact(convex hull s)"
+proof(cases "s={}")
+  case True thus ?thesis using compact_empty by simp
+next
+  case False then obtain w where "w\<in>s" by auto
+  show ?thesis unfolding caratheodory[of s]
+  proof(induct "CARD('n) + 1")
+    have *:"{x.\<exists>sa. finite sa \<and> sa \<subseteq> s \<and> card sa \<le> 0 \<and> x \<in> convex hull sa} = {}" 
+      using compact_empty by (auto simp add: convex_hull_empty)
+    case 0 thus ?case unfolding * by simp
+  next
+    case (Suc n)
+    show ?case proof(cases "n=0")
+      case True have "{x. \<exists>t. finite t \<and> t \<subseteq> s \<and> card t \<le> Suc n \<and> x \<in> convex hull t} = s"
+	unfolding expand_set_eq and mem_Collect_eq proof(rule, rule)
+	fix x assume "\<exists>t. finite t \<and> t \<subseteq> s \<and> card t \<le> Suc n \<and> x \<in> convex hull t"
+	then obtain t where t:"finite t" "t \<subseteq> s" "card t \<le> Suc n" "x \<in> convex hull t" by auto
+	show "x\<in>s" proof(cases "card t = 0")
+	  case True thus ?thesis using t(4) unfolding card_0_eq[OF t(1)] by(simp add: convex_hull_empty)
+	next
+	  case False hence "card t = Suc 0" using t(3) `n=0` by auto
+	  then obtain a where "t = {a}" unfolding card_Suc_eq by auto
+	  thus ?thesis using t(2,4) by (simp add: convex_hull_singleton)
+	qed
+      next
+	fix x assume "x\<in>s"
+	thus "\<exists>t. finite t \<and> t \<subseteq> s \<and> card t \<le> Suc n \<and> x \<in> convex hull t"
+	  apply(rule_tac x="{x}" in exI) unfolding convex_hull_singleton by auto 
+      qed thus ?thesis using assms by simp
+    next
+      case False have "{x. \<exists>t. finite t \<and> t \<subseteq> s \<and> card t \<le> Suc n \<and> x \<in> convex hull t} =
+	{ (1 - u) *s x + u *s y | x y u. 
+	0 \<le> u \<and> u \<le> 1 \<and> x \<in> s \<and> y \<in> {x. \<exists>t. finite t \<and> t \<subseteq> s \<and> card t \<le> n \<and> x \<in> convex hull t}}"
+	unfolding expand_set_eq and mem_Collect_eq proof(rule,rule)
+	fix x assume "\<exists>u v c. x = (1 - c) *s u + c *s v \<and>
+          0 \<le> c \<and> c \<le> 1 \<and> u \<in> s \<and> (\<exists>t. finite t \<and> t \<subseteq> s \<and> card t \<le> n \<and> v \<in> convex hull t)"
+	then obtain u v c t where obt:"x = (1 - c) *s u + c *s v"
+          "0 \<le> c \<and> c \<le> 1" "u \<in> s" "finite t" "t \<subseteq> s" "card t \<le> n"  "v \<in> convex hull t" by auto
+	moreover have "(1 - c) *s u + c *s v \<in> convex hull insert u t"
+	  apply(rule mem_convex) using obt(2) and convex_convex_hull and hull_subset[of "insert u t" convex]
+	  using obt(7) and hull_mono[of t "insert u t"] by auto
+	ultimately show "\<exists>t. finite t \<and> t \<subseteq> s \<and> card t \<le> Suc n \<and> x \<in> convex hull t"
+	  apply(rule_tac x="insert u t" in exI) by (auto simp add: card_insert_if)
+      next
+	fix x assume "\<exists>t. finite t \<and> t \<subseteq> s \<and> card t \<le> Suc n \<and> x \<in> convex hull t"
+	then obtain t where t:"finite t" "t \<subseteq> s" "card t \<le> Suc n" "x \<in> convex hull t" by auto
+	let ?P = "\<exists>u v c. x = (1 - c) *s u + c *s v \<and>
+          0 \<le> c \<and> c \<le> 1 \<and> u \<in> s \<and> (\<exists>t. finite t \<and> t \<subseteq> s \<and> card t \<le> n \<and> v \<in> convex hull t)"
+	show ?P proof(cases "card t = Suc n")
+	  case False hence "card t \<le> n" using t(3) by auto
+	  thus ?P apply(rule_tac x=w in exI, rule_tac x=x in exI, rule_tac x=1 in exI) using `w\<in>s` and t
+	    by(auto intro!: exI[where x=t])
+	next
+	  case True then obtain a u where au:"t = insert a u" "a\<notin>u" apply(drule_tac card_eq_SucD) by auto
+	  show ?P proof(cases "u={}")
+	    case True hence "x=a" using t(4)[unfolded au] by auto
+	    show ?P unfolding `x=a` apply(rule_tac x=a in exI, rule_tac x=a in exI, rule_tac x=1 in exI)
+	      using t and `n\<noteq>0` unfolding au by(auto intro!: exI[where x="{a}"] simp add: convex_hull_singleton)
+	  next
+	    case False obtain ux vx b where obt:"ux\<ge>0" "vx\<ge>0" "ux + vx = 1" "b \<in> convex hull u" "x = ux *s a + vx *s b"
+	      using t(4)[unfolded au convex_hull_insert[OF False]] by auto
+	    have *:"1 - vx = ux" using obt(3) by auto
+	    show ?P apply(rule_tac x=a in exI, rule_tac x=b in exI, rule_tac x=vx in exI)
+	      using obt and t(1-3) unfolding au and * using card_insert_disjoint[OF _ au(2)]
+	      by(auto intro!: exI[where x=u])
+	  qed
+	qed
+      qed
+      thus ?thesis using compact_convex_combinations[OF assms Suc] by simp 
+    qed
+  qed 
+qed
+
+lemma finite_imp_compact_convex_hull:
+ "finite s \<Longrightarrow> compact(convex hull s)"
+  apply(drule finite_imp_compact, drule compact_convex_hull) by assumption
+
+subsection {* Extremal points of a simplex are some vertices. *}
+
+lemma dist_increases_online:
+  fixes a b d :: "real ^ 'n::finite"
+  assumes "d \<noteq> 0"
+  shows "dist a (b + d) > dist a b \<or> dist a (b - d) > dist a b"
+proof(cases "a \<bullet> d - b \<bullet> d > 0")
+  case True hence "0 < d \<bullet> d + (a \<bullet> d * 2 - b \<bullet> d * 2)" 
+    apply(rule_tac add_pos_pos) using assms by auto
+  thus ?thesis apply(rule_tac disjI2) unfolding dist_norm and real_vector_norm_def and real_sqrt_less_iff
+    by(simp add: dot_rsub dot_radd dot_lsub dot_ladd dot_sym field_simps)
+next
+  case False hence "0 < d \<bullet> d + (b \<bullet> d * 2 - a \<bullet> d * 2)" 
+    apply(rule_tac add_pos_nonneg) using assms by auto
+  thus ?thesis apply(rule_tac disjI1) unfolding dist_norm and real_vector_norm_def and real_sqrt_less_iff
+    by(simp add: dot_rsub dot_radd dot_lsub dot_ladd dot_sym field_simps)
+qed
+
+lemma norm_increases_online:
+ "(d::real^'n::finite) \<noteq> 0 \<Longrightarrow> norm(a + d) > norm a \<or> norm(a - d) > norm a"
+  using dist_increases_online[of d a 0] unfolding dist_norm by auto
+
+lemma simplex_furthest_lt:
+  fixes s::"(real^'n::finite) set" assumes "finite s"
+  shows "\<forall>x \<in> (convex hull s).  x \<notin> s \<longrightarrow> (\<exists>y\<in>(convex hull s). norm(x - a) < norm(y - a))"
+proof(induct_tac rule: finite_induct[of s])
+  fix x s assume as:"finite s" "x\<notin>s" "\<forall>x\<in>convex hull s. x \<notin> s \<longrightarrow> (\<exists>y\<in>convex hull s. norm (x - a) < norm (y - a))"
+  show "\<forall>xa\<in>convex hull insert x s. xa \<notin> insert x s \<longrightarrow> (\<exists>y\<in>convex hull insert x s. norm (xa - a) < norm (y - a))"
+  proof(rule,rule,cases "s = {}")
+    case False fix y assume y:"y \<in> convex hull insert x s" "y \<notin> insert x s"
+    obtain u v b where obt:"u\<ge>0" "v\<ge>0" "u + v = 1" "b \<in> convex hull s" "y = u *s x + v *s b"
+      using y(1)[unfolded convex_hull_insert[OF False]] by auto
+    show "\<exists>z\<in>convex hull insert x s. norm (y - a) < norm (z - a)"
+    proof(cases "y\<in>convex hull s")
+      case True then obtain z where "z\<in>convex hull s" "norm (y - a) < norm (z - a)"
+	using as(3)[THEN bspec[where x=y]] and y(2) by auto
+      thus ?thesis apply(rule_tac x=z in bexI) unfolding convex_hull_insert[OF False] by auto
+    next
+      case False show ?thesis  using obt(3) proof(cases "u=0", case_tac[!] "v=0")
+	assume "u=0" "v\<noteq>0" hence "y = b" using obt by auto
+	thus ?thesis using False and obt(4) by auto
+      next
+	assume "u\<noteq>0" "v=0" hence "y = x" using obt by auto
+	thus ?thesis using y(2) by auto
+      next
+	assume "u\<noteq>0" "v\<noteq>0"
+	then obtain w where w:"w>0" "w<u" "w<v" using real_lbound_gt_zero[of u v] and obt(1,2) by auto
+	have "x\<noteq>b" proof(rule ccontr) 
+	  assume "\<not> x\<noteq>b" hence "y=b" unfolding obt(5)
+	    using obt(3) by(auto simp add: vector_sadd_rdistrib[THEN sym])
+	  thus False using obt(4) and False by simp qed
+	hence *:"w *s (x - b) \<noteq> 0" using w(1) by auto
+	show ?thesis using dist_increases_online[OF *, of a y]
+ 	proof(erule_tac disjE)
+	  assume "dist a y < dist a (y + w *s (x - b))"
+	  hence "norm (y - a) < norm ((u + w) *s x + (v - w) *s b - a)"
+	    unfolding dist_commute[of a] unfolding dist_norm obt(5) by (simp add: ring_simps)
+	  moreover have "(u + w) *s x + (v - w) *s b \<in> convex hull insert x s"
+	    unfolding convex_hull_insert[OF `s\<noteq>{}`] and mem_Collect_eq
+	    apply(rule_tac x="u + w" in exI) apply rule defer 
+	    apply(rule_tac x="v - w" in exI) using `u\<ge>0` and w and obt(3,4) by auto
+	  ultimately show ?thesis by auto
+	next
+	  assume "dist a y < dist a (y - w *s (x - b))"
+	  hence "norm (y - a) < norm ((u - w) *s x + (v + w) *s b - a)"
+	    unfolding dist_commute[of a] unfolding dist_norm obt(5) by (simp add: ring_simps)
+	  moreover have "(u - w) *s x + (v + w) *s b \<in> convex hull insert x s"
+	    unfolding convex_hull_insert[OF `s\<noteq>{}`] and mem_Collect_eq
+	    apply(rule_tac x="u - w" in exI) apply rule defer 
+	    apply(rule_tac x="v + w" in exI) using `u\<ge>0` and w and obt(3,4) by auto
+	  ultimately show ?thesis by auto
+	qed
+      qed auto
+    qed
+  qed auto
+qed (auto simp add: assms)
+
+lemma simplex_furthest_le:
+  assumes "finite s" "s \<noteq> {}"
+  shows "\<exists>y\<in>s. \<forall>x\<in>(convex hull s). norm(x - a) \<le> norm(y - a)"
+proof-
+  have "convex hull s \<noteq> {}" using hull_subset[of s convex] and assms(2) by auto
+  then obtain x where x:"x\<in>convex hull s" "\<forall>y\<in>convex hull s. norm (y - a) \<le> norm (x - a)"
+    using distance_attains_sup[OF finite_imp_compact_convex_hull[OF assms(1)], of a]
+    unfolding dist_commute[of a] unfolding dist_norm by auto
+  thus ?thesis proof(cases "x\<in>s")
+    case False then obtain y where "y\<in>convex hull s" "norm (x - a) < norm (y - a)"
+      using simplex_furthest_lt[OF assms(1), THEN bspec[where x=x]] and x(1) by auto
+    thus ?thesis using x(2)[THEN bspec[where x=y]] by auto
+  qed auto
+qed
+
+lemma simplex_furthest_le_exists:
+  "finite s \<Longrightarrow> (\<forall>x\<in>(convex hull s). \<exists>y\<in>s. norm(x - a) \<le> norm(y - a))"
+  using simplex_furthest_le[of s] by (cases "s={}")auto
+
+lemma simplex_extremal_le:
+  assumes "finite s" "s \<noteq> {}"
+  shows "\<exists>u\<in>s. \<exists>v\<in>s. \<forall>x\<in>convex hull s. \<forall>y \<in> convex hull s. norm(x - y) \<le> norm(u - v)"
+proof-
+  have "convex hull s \<noteq> {}" using hull_subset[of s convex] and assms(2) by auto
+  then obtain u v where obt:"u\<in>convex hull s" "v\<in>convex hull s"
+    "\<forall>x\<in>convex hull s. \<forall>y\<in>convex hull s. norm (x - y) \<le> norm (u - v)"
+    using compact_sup_maxdistance[OF finite_imp_compact_convex_hull[OF assms(1)]] by auto
+  thus ?thesis proof(cases "u\<notin>s \<or> v\<notin>s", erule_tac disjE)
+    assume "u\<notin>s" then obtain y where "y\<in>convex hull s" "norm (u - v) < norm (y - v)"
+      using simplex_furthest_lt[OF assms(1), THEN bspec[where x=u]] and obt(1) by auto
+    thus ?thesis using obt(3)[THEN bspec[where x=y], THEN bspec[where x=v]] and obt(2) by auto
+  next
+    assume "v\<notin>s" then obtain y where "y\<in>convex hull s" "norm (v - u) < norm (y - u)"
+      using simplex_furthest_lt[OF assms(1), THEN bspec[where x=v]] and obt(2) by auto
+    thus ?thesis using obt(3)[THEN bspec[where x=u], THEN bspec[where x=y]] and obt(1)
+      by (auto simp add: norm_minus_commute)
+  qed auto
+qed 
+
+lemma simplex_extremal_le_exists:
+  "finite s \<Longrightarrow> x \<in> convex hull s \<Longrightarrow> y \<in> convex hull s
+  \<Longrightarrow> (\<exists>u\<in>s. \<exists>v\<in>s. norm(x - y) \<le> norm(u - v))"
+  using convex_hull_empty simplex_extremal_le[of s] by(cases "s={}")auto
+
+subsection {* Closest point of a convex set is unique, with a continuous projection. *}
+
+definition
+  closest_point :: "(real ^ 'n::finite) set \<Rightarrow> real ^ 'n \<Rightarrow> real ^ 'n" where
+ "closest_point s a = (SOME x. x \<in> s \<and> (\<forall>y\<in>s. dist a x \<le> dist a y))"
+
+lemma closest_point_exists:
+  assumes "closed s" "s \<noteq> {}"
+  shows  "closest_point s a \<in> s" "\<forall>y\<in>s. dist a (closest_point s a) \<le> dist a y"
+  unfolding closest_point_def apply(rule_tac[!] someI2_ex) 
+  using distance_attains_inf[OF assms(1,2), of a] by auto
+
+lemma closest_point_in_set:
+  "closed s \<Longrightarrow> s \<noteq> {} \<Longrightarrow> (closest_point s a) \<in> s"
+  by(meson closest_point_exists)
+
+lemma closest_point_le:
+  "closed s \<Longrightarrow> x \<in> s \<Longrightarrow> dist a (closest_point s a) \<le> dist a x"
+  using closest_point_exists[of s] by auto
+
+lemma closest_point_self:
+  assumes "x \<in> s"  shows "closest_point s x = x"
+  unfolding closest_point_def apply(rule some1_equality, rule ex1I[of _ x]) 
+  using assms by auto
+
+lemma closest_point_refl:
+ "closed s \<Longrightarrow> s \<noteq> {} \<Longrightarrow> (closest_point s x = x \<longleftrightarrow> x \<in> s)"
+  using closest_point_in_set[of s x] closest_point_self[of x s] by auto
+
+lemma closer_points_lemma: fixes y::"real^'n::finite"
+  assumes "y \<bullet> z > 0"
+  shows "\<exists>u>0. \<forall>v>0. v \<le> u \<longrightarrow> norm(v *s z - y) < norm y"
+proof- have z:"z \<bullet> z > 0" unfolding dot_pos_lt using assms by auto
+  thus ?thesis using assms apply(rule_tac x="(y \<bullet> z) / (z \<bullet> z)" in exI) apply(rule) defer proof(rule+)
+    fix v assume "0<v" "v \<le> y \<bullet> z / (z \<bullet> z)"
+    thus "norm (v *s z - y) < norm y" unfolding norm_lt using z and assms
+      by (simp add: field_simps dot_sym  mult_strict_left_mono[OF _ `0<v`])
+  qed(rule divide_pos_pos, auto) qed
+
+lemma closer_point_lemma:
+  fixes x y z :: "real ^ 'n::finite"
+  assumes "(y - x) \<bullet> (z - x) > 0"
+  shows "\<exists>u>0. u \<le> 1 \<and> dist (x + u *s (z - x)) y < dist x y"
+proof- obtain u where "u>0" and u:"\<forall>v>0. v \<le> u \<longrightarrow> norm (v *s (z - x) - (y - x)) < norm (y - x)"
+    using closer_points_lemma[OF assms] by auto
+  show ?thesis apply(rule_tac x="min u 1" in exI) using u[THEN spec[where x="min u 1"]] and `u>0`
+    unfolding dist_norm by(auto simp add: norm_minus_commute field_simps) qed
+
+lemma any_closest_point_dot:
+  assumes "convex s" "closed s" "x \<in> s" "y \<in> s" "\<forall>z\<in>s. dist a x \<le> dist a z"
+  shows "(a - x) \<bullet> (y - x) \<le> 0"
+proof(rule ccontr) assume "\<not> (a - x) \<bullet> (y - x) \<le> 0"
+  then obtain u where u:"u>0" "u\<le>1" "dist (x + u *s (y - x)) a < dist x a" using closer_point_lemma[of a x y] by auto
+  let ?z = "(1 - u) *s x + u *s y" have "?z \<in> s" using mem_convex[OF assms(1,3,4), of u] using u by auto
+  thus False using assms(5)[THEN bspec[where x="?z"]] and u(3) by (auto simp add: dist_commute field_simps) qed
+
+lemma any_closest_point_unique:
+  assumes "convex s" "closed s" "x \<in> s" "y \<in> s"
+  "\<forall>z\<in>s. dist a x \<le> dist a z" "\<forall>z\<in>s. dist a y \<le> dist a z"
+  shows "x = y" using any_closest_point_dot[OF assms(1-4,5)] and any_closest_point_dot[OF assms(1-2,4,3,6)]
+  unfolding norm_pths(1) and norm_le_square by auto
+
+lemma closest_point_unique:
+  assumes "convex s" "closed s" "x \<in> s" "\<forall>z\<in>s. dist a x \<le> dist a z"
+  shows "x = closest_point s a"
+  using any_closest_point_unique[OF assms(1-3) _ assms(4), of "closest_point s a"] 
+  using closest_point_exists[OF assms(2)] and assms(3) by auto
+
+lemma closest_point_dot:
+  assumes "convex s" "closed s" "x \<in> s"
+  shows "(a - closest_point s a) \<bullet> (x - closest_point s a) \<le> 0"
+  apply(rule any_closest_point_dot[OF assms(1,2) _ assms(3)])
+  using closest_point_exists[OF assms(2)] and assms(3) by auto
+
+lemma closest_point_lt:
+  assumes "convex s" "closed s" "x \<in> s" "x \<noteq> closest_point s a"
+  shows "dist a (closest_point s a) < dist a x"
+  apply(rule ccontr) apply(rule_tac notE[OF assms(4)])
+  apply(rule closest_point_unique[OF assms(1-3), of a])
+  using closest_point_le[OF assms(2), of _ a] by fastsimp
+
+lemma closest_point_lipschitz:
+  assumes "convex s" "closed s" "s \<noteq> {}"
+  shows "dist (closest_point s x) (closest_point s y) \<le> dist x y"
+proof-
+  have "(x - closest_point s x) \<bullet> (closest_point s y - closest_point s x) \<le> 0"
+       "(y - closest_point s y) \<bullet> (closest_point s x - closest_point s y) \<le> 0"
+    apply(rule_tac[!] any_closest_point_dot[OF assms(1-2)])
+    using closest_point_exists[OF assms(2-3)] by auto
+  thus ?thesis unfolding dist_norm and norm_le
+    using dot_pos_le[of "(x - closest_point s x) - (y - closest_point s y)"]
+    by (auto simp add: dot_sym dot_ladd dot_radd) qed
+
+lemma continuous_at_closest_point:
+  assumes "convex s" "closed s" "s \<noteq> {}"
+  shows "continuous (at x) (closest_point s)"
+  unfolding continuous_at_eps_delta 
+  using le_less_trans[OF closest_point_lipschitz[OF assms]] by auto
+
+lemma continuous_on_closest_point:
+  assumes "convex s" "closed s" "s \<noteq> {}"
+  shows "continuous_on t (closest_point s)"
+  apply(rule continuous_at_imp_continuous_on) using continuous_at_closest_point[OF assms] by auto
+
+subsection {* Various point-to-set separating/supporting hyperplane theorems. *}
+
+lemma supporting_hyperplane_closed_point:
+  assumes "convex s" "closed s" "s \<noteq> {}" "z \<notin> s"
+  shows "\<exists>a b. \<exists>y\<in>s. a \<bullet> z < b \<and> (a \<bullet> y = b) \<and> (\<forall>x\<in>s. a \<bullet> x \<ge> b)"
+proof-
+  from distance_attains_inf[OF assms(2-3)] obtain y where "y\<in>s" and y:"\<forall>x\<in>s. dist z y \<le> dist z x" by auto
+  show ?thesis apply(rule_tac x="y - z" in exI, rule_tac x="(y - z) \<bullet> y" in exI, rule_tac x=y in bexI)
+    apply rule defer apply rule defer apply(rule, rule ccontr) using `y\<in>s` proof-
+    show "(y - z) \<bullet> z < (y - z) \<bullet> y" apply(subst diff_less_iff(1)[THEN sym])
+      unfolding dot_rsub[THEN sym] and dot_pos_lt using `y\<in>s` `z\<notin>s` by auto
+  next
+    fix x assume "x\<in>s" have *:"\<forall>u. 0 \<le> u \<and> u \<le> 1 \<longrightarrow> dist z y \<le> dist z ((1 - u) *s y + u *s x)"
+      using assms(1)[unfolded convex_alt] and y and `x\<in>s` and `y\<in>s` by auto
+    assume "\<not> (y - z) \<bullet> y \<le> (y - z) \<bullet> x" then obtain v where
+      "v>0" "v\<le>1" "dist (y + v *s (x - y)) z < dist y z" using closer_point_lemma[of z y x] by auto
+    thus False using *[THEN spec[where x=v]] by(auto simp add: dist_commute field_simps)
+  qed auto
+qed
+
+lemma separating_hyperplane_closed_point:
+  assumes "convex s" "closed s" "z \<notin> s"
+  shows "\<exists>a b. a \<bullet> z < b \<and> (\<forall>x\<in>s. a \<bullet> x > b)"
+proof(cases "s={}")
+  case True thus ?thesis apply(rule_tac x="-z" in exI, rule_tac x=1 in exI)
+    using less_le_trans[OF _ dot_pos_le[of z]] by auto
+next
+  case False obtain y where "y\<in>s" and y:"\<forall>x\<in>s. dist z y \<le> dist z x"
+    using distance_attains_inf[OF assms(2) False] by auto
+  show ?thesis apply(rule_tac x="y - z" in exI, rule_tac x="(y - z) \<bullet> z + (norm(y - z))\<twosuperior> / 2" in exI)
+    apply rule defer apply rule proof-
+    fix x assume "x\<in>s"
+    have "\<not> 0 < (z - y) \<bullet> (x - y)" apply(rule_tac notI) proof(drule closer_point_lemma)
+      assume "\<exists>u>0. u \<le> 1 \<and> dist (y + u *s (x - y)) z < dist y z"
+      then obtain u where "u>0" "u\<le>1" "dist (y + u *s (x - y)) z < dist y z" by auto
+      thus False using y[THEN bspec[where x="y + u *s (x - y)"]]
+	using assms(1)[unfolded convex_alt, THEN bspec[where x=y]]
+	using `x\<in>s` `y\<in>s` by (auto simp add: dist_commute field_simps) qed
+    moreover have "0 < norm (y - z) ^ 2" using `y\<in>s` `z\<notin>s` by auto
+    hence "0 < (y - z) \<bullet> (y - z)" unfolding norm_pow_2 by simp
+    ultimately show "(y - z) \<bullet> z + (norm (y - z))\<twosuperior> / 2 < (y - z) \<bullet> x"
+      unfolding norm_pow_2 and dlo_simps(3) by (auto simp add: field_simps dot_sym)
+  qed(insert `y\<in>s` `z\<notin>s`, auto)
+qed
+
+lemma separating_hyperplane_closed_0:
+  assumes "convex (s::(real^'n::finite) set)" "closed s" "0 \<notin> s"
+  shows "\<exists>a b. a \<noteq> 0 \<and> 0 < b \<and> (\<forall>x\<in>s. a \<bullet> x > b)"
+  proof(cases "s={}") guess a using UNIV_witness[where 'a='n] ..
+  case True have "norm ((basis a)::real^'n::finite) = 1" 
+    using norm_basis and dimindex_ge_1 by auto
+  thus ?thesis apply(rule_tac x="basis a" in exI, rule_tac x=1 in exI) using True by auto
+next case False thus ?thesis using False using separating_hyperplane_closed_point[OF assms]
+    apply - apply(erule exE)+ unfolding dot_rzero apply(rule_tac x=a in exI, rule_tac x=b in exI) by auto qed
+
+subsection {* Now set-to-set for closed/compact sets. *}
+
+lemma separating_hyperplane_closed_compact:
+  assumes "convex (s::(real^'n::finite) set)" "closed s" "convex t" "compact t" "t \<noteq> {}" "s \<inter> t = {}"
+  shows "\<exists>a b. (\<forall>x\<in>s. a \<bullet> x < b) \<and> (\<forall>x\<in>t. a \<bullet> x > b)"
+proof(cases "s={}")
+  case True
+  obtain b where b:"b>0" "\<forall>x\<in>t. norm x \<le> b" using compact_imp_bounded[OF assms(4)] unfolding bounded_pos by auto
+  obtain z::"real^'n" where z:"norm z = b + 1" using vector_choose_size[of "b + 1"] and b(1) by auto
+  hence "z\<notin>t" using b(2)[THEN bspec[where x=z]] by auto
+  then obtain a b where ab:"a \<bullet> z < b" "\<forall>x\<in>t. b < a \<bullet> x"
+    using separating_hyperplane_closed_point[OF assms(3) compact_imp_closed[OF assms(4)], of z] by auto
+  thus ?thesis using True by auto
+next
+  case False then obtain y where "y\<in>s" by auto
+  obtain a b where "0 < b" "\<forall>x\<in>{x - y |x y. x \<in> s \<and> y \<in> t}. b < a \<bullet> x"
+    using separating_hyperplane_closed_point[OF convex_differences[OF assms(1,3)], of 0]
+    using closed_compact_differences[OF assms(2,4)] using assms(6) by(auto, blast)
+  hence ab:"\<forall>x\<in>s. \<forall>y\<in>t. b + a \<bullet> y < a \<bullet> x" apply- apply(rule,rule) apply(erule_tac x="x - y" in ballE) by auto
+  def k \<equiv> "rsup ((\<lambda>x. a \<bullet> x) ` t)"
+  show ?thesis apply(rule_tac x="-a" in exI, rule_tac x="-(k + b / 2)" in exI)
+    apply(rule,rule) defer apply(rule) unfolding dot_lneg and neg_less_iff_less proof-
+    from ab have "((\<lambda>x. a \<bullet> x) ` t) *<= (a \<bullet> y - b)"
+      apply(erule_tac x=y in ballE) apply(rule setleI) using `y\<in>s` by auto
+    hence k:"isLub UNIV ((\<lambda>x. a \<bullet> x) ` t) k" unfolding k_def apply(rule_tac rsup) using assms(5) by auto
+    fix x assume "x\<in>t" thus "a \<bullet> x < (k + b / 2)" using `0<b` and isLubD2[OF k, of "a \<bullet> x"] by auto
+  next
+    fix x assume "x\<in>s" 
+    hence "k \<le> a \<bullet> x - b" unfolding k_def apply(rule_tac rsup_le) using assms(5)
+      unfolding setle_def
+      using ab[THEN bspec[where x=x]] by auto
+    thus "k + b / 2 < a \<bullet> x" using `0 < b` by auto
+  qed
+qed
+
+lemma separating_hyperplane_compact_closed:
+  assumes "convex s" "compact s" "s \<noteq> {}" "convex t" "closed t" "s \<inter> t = {}"
+  shows "\<exists>a b. (\<forall>x\<in>s. a \<bullet> x < b) \<and> (\<forall>x\<in>t. a \<bullet> x > b)"
+proof- obtain a b where "(\<forall>x\<in>t. a \<bullet> x < b) \<and> (\<forall>x\<in>s. b < a \<bullet> x)"
+    using separating_hyperplane_closed_compact[OF assms(4-5,1-2,3)] and assms(6) by auto
+  thus ?thesis apply(rule_tac x="-a" in exI, rule_tac x="-b" in exI) by auto qed
+
+subsection {* General case without assuming closure and getting non-strict separation. *}
+
+lemma separating_hyperplane_set_0:
+  assumes "convex s" "(0::real^'n::finite) \<notin> s"
+  shows "\<exists>a. a \<noteq> 0 \<and> (\<forall>x\<in>s. 0 \<le> a \<bullet> x)"
+proof- let ?k = "\<lambda>c. {x::real^'n. 0 \<le> c \<bullet> x}"
+  have "frontier (cball 0 1) \<inter> (\<Inter> (?k ` s)) \<noteq> {}"
+    apply(rule compact_imp_fip) apply(rule compact_frontier[OF compact_cball])
+    defer apply(rule,rule,erule conjE) proof-
+    fix f assume as:"f \<subseteq> ?k ` s" "finite f"
+    obtain c where c:"f = ?k ` c" "c\<subseteq>s" "finite c" using finite_subset_image[OF as] by auto
+    then obtain a b where ab:"a \<noteq> 0" "0 < b"  "\<forall>x\<in>convex hull c. b < a \<bullet> x"
+      using separating_hyperplane_closed_0[OF convex_convex_hull, of c]
+      using finite_imp_compact_convex_hull[OF c(3), THEN compact_imp_closed] and assms(2)
+      using subset_hull[unfolded mem_def, of convex, OF assms(1), THEN sym, of c] by auto
+    hence "\<exists>x. norm x = 1 \<and> (\<forall>y\<in>c. 0 \<le> y \<bullet> x)" apply(rule_tac x="inverse(norm a) *s a" in exI)
+       using hull_subset[of c convex] unfolding subset_eq and dot_rmult
+       apply- apply rule defer apply rule apply(rule mult_nonneg_nonneg)
+       by(auto simp add: dot_sym elim!: ballE) 
+    thus "frontier (cball 0 1) \<inter> \<Inter>f \<noteq> {}" unfolding c(1) frontier_cball dist_norm by auto
+  qed(insert closed_halfspace_ge, auto)
+  then obtain x where "norm x = 1" "\<forall>y\<in>s. x\<in>?k y" unfolding frontier_cball dist_norm by auto
+  thus ?thesis apply(rule_tac x=x in exI) by(auto simp add: dot_sym) qed
+
+lemma separating_hyperplane_sets:
+  assumes "convex s" "convex (t::(real^'n::finite) set)" "s \<noteq> {}" "t \<noteq> {}" "s \<inter> t = {}"
+  shows "\<exists>a b. a \<noteq> 0 \<and> (\<forall>x\<in>s. a \<bullet> x \<le> b) \<and> (\<forall>x\<in>t. a \<bullet> x \<ge> b)"
+proof- from separating_hyperplane_set_0[OF convex_differences[OF assms(2,1)]]
+  obtain a where "a\<noteq>0" "\<forall>x\<in>{x - y |x y. x \<in> t \<and> y \<in> s}. 0 \<le> a \<bullet> x"  using assms(3-5) by auto 
+  hence "\<forall>x\<in>t. \<forall>y\<in>s. a \<bullet> y \<le> a \<bullet> x" apply- apply(rule, rule) apply(erule_tac x="x - y" in ballE) by auto
+  thus ?thesis apply(rule_tac x=a in exI, rule_tac x="rsup ((\<lambda>x. a \<bullet> x) ` s)" in exI) using `a\<noteq>0`
+    apply(rule) apply(rule,rule) apply(rule rsup[THEN isLubD2]) prefer 4 apply(rule,rule rsup_le) unfolding setle_def
+    prefer 4 using assms(3-5) by blast+ qed
+
+subsection {* More convexity generalities. *}
+
+lemma convex_closure: assumes "convex s" shows "convex(closure s)"
+  unfolding convex_def Ball_def closure_sequential
+  apply(rule,rule,rule,rule,rule,rule,rule,rule,rule) apply(erule_tac exE)+
+  apply(rule_tac x="\<lambda>n. u *s xb n + v *s xc n" in exI) apply(rule,rule)
+  apply(rule assms[unfolded convex_def, rule_format]) prefer 6
+  apply(rule Lim_add) apply(rule_tac [1-2] Lim_cmul) by auto
+
+lemma convex_interior: assumes "convex s" shows "convex(interior s)"
+  unfolding convex_alt Ball_def mem_interior apply(rule,rule,rule,rule,rule,rule) apply(erule exE | erule conjE)+ proof-
+  fix x y u assume u:"0 \<le> u" "u \<le> (1::real)"
+  fix e d assume ed:"ball x e \<subseteq> s" "ball y d \<subseteq> s" "0<d" "0<e" 
+  show "\<exists>e>0. ball ((1 - u) *s x + u *s y) e \<subseteq> s" apply(rule_tac x="min d e" in exI)
+    apply rule unfolding subset_eq defer apply rule proof-
+    fix z assume "z \<in> ball ((1 - u) *s x + u *s y) (min d e)"
+    hence "(1- u) *s (z - u *s (y - x)) + u *s (z + (1 - u) *s (y - x)) \<in> s"
+      apply(rule_tac assms[unfolded convex_alt, rule_format])
+      using ed(1,2) and u unfolding subset_eq mem_ball Ball_def dist_norm by(auto simp add: ring_simps)
+    thus "z \<in> s" using u by (auto simp add: ring_simps) qed(insert u ed(3-4), auto) qed
+
+lemma convex_hull_eq_empty: "convex hull s = {} \<longleftrightarrow> s = {}"
+  using hull_subset[of s convex] convex_hull_empty by auto
+
+subsection {* Moving and scaling convex hulls. *}
+
+lemma convex_hull_translation_lemma:
+  "convex hull ((\<lambda>x. a + x) ` s) \<subseteq> (\<lambda>x. a + x) ` (convex hull s)"
+  apply(rule hull_minimal, rule image_mono, rule hull_subset) unfolding mem_def
+  using convex_translation[OF convex_convex_hull, of a s] by assumption
+
+lemma convex_hull_bilemma: fixes neg
+  assumes "(\<forall>s a. (convex hull (up a s)) \<subseteq> up a (convex hull s))"
+  shows "(\<forall>s. up a (up (neg a) s) = s) \<and> (\<forall>s. up (neg a) (up a s) = s) \<and> (\<forall>s t a. s \<subseteq> t \<longrightarrow> up a s \<subseteq> up a t)
+  \<Longrightarrow> \<forall>s. (convex hull (up a s)) = up a (convex hull s)"
+  using assms by(metis subset_antisym) 
+
+lemma convex_hull_translation:
+  "convex hull ((\<lambda>x. a + x) ` s) = (\<lambda>x. a + x) ` (convex hull s)"
+  apply(rule convex_hull_bilemma[rule_format, of _ _ "\<lambda>a. -a"], rule convex_hull_translation_lemma) unfolding image_image by auto
+
+lemma convex_hull_scaling_lemma:
+ "(convex hull ((\<lambda>x. c *s x) ` s)) \<subseteq> (\<lambda>x. c *s x) ` (convex hull s)"
+  apply(rule hull_minimal, rule image_mono, rule hull_subset)
+  unfolding mem_def by(rule convex_scaling, rule convex_convex_hull)
+
+lemma convex_hull_scaling:
+  "convex hull ((\<lambda>x. c *s x) ` s) = (\<lambda>x. c *s x) ` (convex hull s)"
+  apply(cases "c=0") defer apply(rule convex_hull_bilemma[rule_format, of _ _ inverse]) apply(rule convex_hull_scaling_lemma)
+  unfolding image_image vector_smult_assoc by(auto simp add:image_constant_conv convex_hull_eq_empty)
+
+lemma convex_hull_affinity:
+  "convex hull ((\<lambda>x. a + c *s x) ` s) = (\<lambda>x. a + c *s x) ` (convex hull s)"
+  unfolding image_image[THEN sym] convex_hull_scaling convex_hull_translation  ..
+
+subsection {* Convex set as intersection of halfspaces. *}
+
+lemma convex_halfspace_intersection:
+  assumes "closed s" "convex s"
+  shows "s = \<Inter> {h. s \<subseteq> h \<and> (\<exists>a b. h = {x. a \<bullet> x \<le> b})}"
+  apply(rule set_ext, rule) unfolding Inter_iff Ball_def mem_Collect_eq apply(rule,rule,erule conjE) proof- 
+  fix x  assume "\<forall>xa. s \<subseteq> xa \<and> (\<exists>a b. xa = {x. a \<bullet> x \<le> b}) \<longrightarrow> x \<in> xa"
+  hence "\<forall>a b. s \<subseteq> {x. a \<bullet> x \<le> b} \<longrightarrow> x \<in> {x. a \<bullet> x \<le> b}" by blast
+  thus "x\<in>s" apply(rule_tac ccontr) apply(drule separating_hyperplane_closed_point[OF assms(2,1)])
+    apply(erule exE)+ apply(erule_tac x="-a" in allE, erule_tac x="-b" in allE) by auto
+qed auto
+
+subsection {* Radon's theorem (from Lars Schewe). *}
+
+lemma radon_ex_lemma:
+  assumes "finite c" "affine_dependent c"
+  shows "\<exists>u. setsum u c = 0 \<and> (\<exists>v\<in>c. u v \<noteq> 0) \<and> setsum (\<lambda>v. u v *s v) c = 0"
+proof- from assms(2)[unfolded affine_dependent_explicit] guess s .. then guess u ..
+  thus ?thesis apply(rule_tac x="\<lambda>v. if v\<in>s then u v else 0" in exI) unfolding if_smult vector_smult_lzero
+    and setsum_restrict_set[OF assms(1), THEN sym] by(auto simp add: Int_absorb1) qed
+
+lemma radon_s_lemma:
+  assumes "finite s" "setsum f s = (0::real)"
+  shows "setsum f {x\<in>s. 0 < f x} = - setsum f {x\<in>s. f x < 0}"
+proof- have *:"\<And>x. (if f x < 0 then f x else 0) + (if 0 < f x then f x else 0) = f x" by auto
+  show ?thesis unfolding real_add_eq_0_iff[THEN sym] and setsum_restrict_set''[OF assms(1)] and setsum_addf[THEN sym] and *
+    using assms(2) by assumption qed
+
+lemma radon_v_lemma:
+  assumes "finite s" "setsum f s = 0" "\<forall>x. g x = (0::real) \<longrightarrow> f x = (0::real^'n)"
+  shows "(setsum f {x\<in>s. 0 < g x}) = - setsum f {x\<in>s. g x < 0}"
+proof-
+  have *:"\<And>x. (if 0 < g x then f x else 0) + (if g x < 0 then f x else 0) = f x" using assms(3) by auto 
+  show ?thesis unfolding eq_neg_iff_add_eq_0 and setsum_restrict_set''[OF assms(1)] and setsum_addf[THEN sym] and *
+    using assms(2) by assumption qed
+
+lemma radon_partition:
+  assumes "finite c" "affine_dependent c"
+  shows "\<exists>m p. m \<inter> p = {} \<and> m \<union> p = c \<and> (convex hull m) \<inter> (convex hull p) \<noteq> {}" proof-
+  obtain u v where uv:"setsum u c = 0" "v\<in>c" "u v \<noteq> 0"  "(\<Sum>v\<in>c. u v *s v) = 0" using radon_ex_lemma[OF assms] by auto
+  have fin:"finite {x \<in> c. 0 < u x}" "finite {x \<in> c. 0 > u x}" using assms(1) by auto
+  def z \<equiv> "(inverse (setsum u {x\<in>c. u x > 0})) *s setsum (\<lambda>x. u x *s x) {x\<in>c. u x > 0}"
+  have "setsum u {x \<in> c. 0 < u x} \<noteq> 0" proof(cases "u v \<ge> 0")
+    case False hence "u v < 0" by auto
+    thus ?thesis proof(cases "\<exists>w\<in>{x \<in> c. 0 < u x}. u w > 0") 
+      case True thus ?thesis using setsum_nonneg_eq_0_iff[of _ u, OF fin(1)] by auto
+    next
+      case False hence "setsum u c \<le> setsum (\<lambda>x. if x=v then u v else 0) c" apply(rule_tac setsum_mono) by auto
+      thus ?thesis unfolding setsum_delta[OF assms(1)] using uv(2) and `u v < 0` and uv(1) by auto qed
+  qed (insert setsum_nonneg_eq_0_iff[of _ u, OF fin(1)] uv(2-3), auto)
+
+  hence *:"setsum u {x\<in>c. u x > 0} > 0" unfolding real_less_def apply(rule_tac conjI, rule_tac setsum_nonneg) by auto
+  moreover have "setsum u ({x \<in> c. 0 < u x} \<union> {x \<in> c. u x < 0}) = setsum u c"
+    "(\<Sum>x\<in>{x \<in> c. 0 < u x} \<union> {x \<in> c. u x < 0}. u x *s x) = (\<Sum>x\<in>c. u x *s x)"
+    using assms(1) apply(rule_tac[!] setsum_mono_zero_left) by auto
+  hence "setsum u {x \<in> c. 0 < u x} = - setsum u {x \<in> c. 0 > u x}"
+   "(\<Sum>x\<in>{x \<in> c. 0 < u x}. u x *s x) = - (\<Sum>x\<in>{x \<in> c. 0 > u x}. u x *s x)" 
+    unfolding eq_neg_iff_add_eq_0 using uv(1,4) by (auto simp add:  setsum_Un_zero[OF fin, THEN sym]) 
+  moreover have "\<forall>x\<in>{v \<in> c. u v < 0}. 0 \<le> inverse (setsum u {x \<in> c. 0 < u x}) * - u x" 
+    apply (rule) apply (rule mult_nonneg_nonneg) using * by auto
+
+  ultimately have "z \<in> convex hull {v \<in> c. u v \<le> 0}" unfolding convex_hull_explicit mem_Collect_eq
+    apply(rule_tac x="{v \<in> c. u v < 0}" in exI, rule_tac x="\<lambda>y. inverse (setsum u {x\<in>c. u x > 0}) * - u y" in exI)
+    using assms(1) unfolding vector_smult_assoc[THEN sym] setsum_cmul and z_def
+    by(auto simp add: setsum_negf vector_smult_lneg mult_right.setsum[THEN sym])
+  moreover have "\<forall>x\<in>{v \<in> c. 0 < u v}. 0 \<le> inverse (setsum u {x \<in> c. 0 < u x}) * u x" 
+    apply (rule) apply (rule mult_nonneg_nonneg) using * by auto 
+  hence "z \<in> convex hull {v \<in> c. u v > 0}" unfolding convex_hull_explicit mem_Collect_eq
+    apply(rule_tac x="{v \<in> c. 0 < u v}" in exI, rule_tac x="\<lambda>y. inverse (setsum u {x\<in>c. u x > 0}) * u y" in exI)
+    using assms(1) unfolding vector_smult_assoc[THEN sym] setsum_cmul and z_def using *
+    by(auto simp add: setsum_negf vector_smult_lneg mult_right.setsum[THEN sym])
+  ultimately show ?thesis apply(rule_tac x="{v\<in>c. u v \<le> 0}" in exI, rule_tac x="{v\<in>c. u v > 0}" in exI) by auto
+qed
+
+lemma radon: assumes "affine_dependent c"
+  obtains m p where "m\<subseteq>c" "p\<subseteq>c" "m \<inter> p = {}" "(convex hull m) \<inter> (convex hull p) \<noteq> {}"
+proof- from assms[unfolded affine_dependent_explicit] guess s .. then guess u ..
+  hence *:"finite s" "affine_dependent s" and s:"s \<subseteq> c" unfolding affine_dependent_explicit by auto
+  from radon_partition[OF *] guess m .. then guess p ..
+  thus ?thesis apply(rule_tac that[of p m]) using s by auto qed
+
+subsection {* Helly's theorem. *}
+
+lemma helly_induct: fixes f::"(real^'n::finite) set set"
+  assumes "f hassize n" "n \<ge> CARD('n) + 1"
+  "\<forall>s\<in>f. convex s" "\<forall>t\<subseteq>f. card t = CARD('n) + 1 \<longrightarrow> \<Inter> t \<noteq> {}"
+  shows "\<Inter> f \<noteq> {}"
+  using assms unfolding hassize_def apply(erule_tac conjE) proof(induct n arbitrary: f)
+case (Suc n)
+show "\<Inter> f \<noteq> {}" apply(cases "n = CARD('n)") apply(rule Suc(4)[rule_format])
+  unfolding card_Diff_singleton_if[OF Suc(5)] and Suc(6) proof-
+  assume ng:"n \<noteq> CARD('n)" hence "\<exists>X. \<forall>s\<in>f. X s \<in> \<Inter>(f - {s})" apply(rule_tac bchoice) unfolding ex_in_conv
+    apply(rule, rule Suc(1)[rule_format])  unfolding card_Diff_singleton_if[OF Suc(5)] and Suc(6)
+    defer apply(rule Suc(3)[rule_format]) defer apply(rule Suc(4)[rule_format]) using Suc(2,5) by auto
+  then obtain X where X:"\<forall>s\<in>f. X s \<in> \<Inter>(f - {s})" by auto
+  show ?thesis proof(cases "inj_on X f")
+    case False then obtain s t where st:"s\<noteq>t" "s\<in>f" "t\<in>f" "X s = X t" unfolding inj_on_def by auto
+    hence *:"\<Inter> f = \<Inter> (f - {s}) \<inter> \<Inter> (f - {t})" by auto
+    show ?thesis unfolding * unfolding ex_in_conv[THEN sym] apply(rule_tac x="X s" in exI)
+      apply(rule, rule X[rule_format]) using X st by auto
+  next case True then obtain m p where mp:"m \<inter> p = {}" "m \<union> p = X ` f" "convex hull m \<inter> convex hull p \<noteq> {}"
+      using radon_partition[of "X ` f"] and affine_dependent_biggerset[of "X ` f"]
+      unfolding card_image[OF True] and Suc(6) using Suc(2,5) and ng by auto
+    have "m \<subseteq> X ` f" "p \<subseteq> X ` f" using mp(2) by auto
+    then obtain g h where gh:"m = X ` g" "p = X ` h" "g \<subseteq> f" "h \<subseteq> f" unfolding subset_image_iff by auto 
+    hence "f \<union> (g \<union> h) = f" by auto
+    hence f:"f = g \<union> h" using inj_on_image_eq_iff[of X f "g \<union> h"] and True
+      unfolding mp(2)[unfolded image_Un[THEN sym] gh] by auto
+    have *:"g \<inter> h = {}" using mp(1) unfolding gh using inj_on_image_Int[OF True gh(3,4)] by auto
+    have "convex hull (X ` h) \<subseteq> \<Inter> g" "convex hull (X ` g) \<subseteq> \<Inter> h"
+      apply(rule_tac [!] hull_minimal) using Suc(3) gh(3-4)  unfolding mem_def unfolding subset_eq
+      apply(rule_tac [2] convex_Inter, rule_tac [4] convex_Inter) apply rule prefer 3 apply rule proof-
+      fix x assume "x\<in>X ` g" then guess y unfolding image_iff ..
+      thus "x\<in>\<Inter>h" using X[THEN bspec[where x=y]] using * f by auto next
+      fix x assume "x\<in>X ` h" then guess y unfolding image_iff ..
+      thus "x\<in>\<Inter>g" using X[THEN bspec[where x=y]] using * f by auto
+    qed(auto)
+    thus ?thesis unfolding f using mp(3)[unfolded gh] by blast qed
+qed(insert dimindex_ge_1, auto) qed(auto)
+
+lemma helly: fixes f::"(real^'n::finite) set set"
+  assumes "finite f" "card f \<ge> CARD('n) + 1" "\<forall>s\<in>f. convex s"
+          "\<forall>t\<subseteq>f. card t = CARD('n) + 1 \<longrightarrow> \<Inter> t \<noteq> {}"
+  shows "\<Inter> f \<noteq>{}"
+  apply(rule helly_induct) unfolding hassize_def using assms by auto
+
+subsection {* Convex hull is "preserved" by a linear function. *}
+
+lemma convex_hull_linear_image:
+  assumes "linear f"
+  shows "f ` (convex hull s) = convex hull (f ` s)"
+  apply rule unfolding subset_eq ball_simps apply(rule_tac[!] hull_induct, rule hull_inc) prefer 3  
+  apply(erule imageE)apply(rule_tac x=xa in image_eqI) apply assumption
+  apply(rule hull_subset[unfolded subset_eq, rule_format]) apply assumption
+proof- show "convex {x. f x \<in> convex hull f ` s}" 
+  unfolding convex_def by(auto simp add: linear_cmul[OF assms]  linear_add[OF assms]
+    convex_convex_hull[unfolded convex_def, rule_format]) next
+  show "convex {x. x \<in> f ` (convex hull s)}" using  convex_convex_hull[unfolded convex_def, of s] 
+    unfolding convex_def by (auto simp add: linear_cmul[OF assms, THEN sym]  linear_add[OF assms, THEN sym])
+qed auto
+
+lemma in_convex_hull_linear_image:
+  assumes "linear f" "x \<in> convex hull s" shows "(f x) \<in> convex hull (f ` s)"
+using convex_hull_linear_image[OF assms(1)] assms(2) by auto
+
+subsection {* Homeomorphism of all convex compact sets with nonempty interior. *}
+
+lemma compact_frontier_line_lemma:
+  assumes "compact s" "0 \<in> s" "x \<noteq> 0" 
+  obtains u where "0 \<le> u" "(u *s x) \<in> frontier s" "\<forall>v>u. (v *s x) \<notin> s"
+proof-
+  obtain b where b:"b>0" "\<forall>x\<in>s. norm x \<le> b" using compact_imp_bounded[OF assms(1), unfolded bounded_pos] by auto
+  let ?A = "{y. \<exists>u. 0 \<le> u \<and> u \<le> b / norm(x) \<and> (y = u *s x)}"
+  have A:"?A = (\<lambda>u. dest_vec1 u *s x) ` {0 .. vec1 (b / norm x)}"
+    unfolding image_image[of "\<lambda>u. u *s x" "\<lambda>x. dest_vec1 x", THEN sym]
+    unfolding dest_vec1_inverval vec1_dest_vec1 by auto
+  have "compact ?A" unfolding A apply(rule compact_continuous_image, rule continuous_at_imp_continuous_on)
+    apply(rule, rule continuous_vmul) unfolding o_def vec1_dest_vec1 apply(rule continuous_at_id) by(rule compact_interval)
+  moreover have "{y. \<exists>u\<ge>0. u \<le> b / norm x \<and> y = u *s x} \<inter> s \<noteq> {}" apply(rule not_disjointI[OF _ assms(2)])
+    unfolding mem_Collect_eq using `b>0` assms(3) by(auto intro!: divide_nonneg_pos)
+  ultimately obtain u y where obt: "u\<ge>0" "u \<le> b / norm x" "y = u *s x"
+    "y\<in>?A" "y\<in>s" "\<forall>z\<in>?A \<inter> s. dist 0 z \<le> dist 0 y" using distance_attains_sup[OF compact_inter[OF _ assms(1), of ?A], of 0] by auto
+
+  have "norm x > 0" using assms(3)[unfolded zero_less_norm_iff[THEN sym]] by auto
+  { fix v assume as:"v > u" "v *s x \<in> s"
+    hence "v \<le> b / norm x" using b(2)[rule_format, OF as(2)] 
+      using `u\<ge>0` unfolding pos_le_divide_eq[OF `norm x > 0`] and norm_mul by auto
+    hence "norm (v *s x) \<le> norm y" apply(rule_tac obt(6)[rule_format, unfolded dist_0_norm]) apply(rule IntI) defer 
+      apply(rule as(2)) unfolding mem_Collect_eq apply(rule_tac x=v in exI) 
+      using as(1) `u\<ge>0` by(auto simp add:field_simps) 
+    hence False unfolding obt(3) unfolding norm_mul using `u\<ge>0` `norm x > 0` `v>u` by(auto simp add:field_simps)
+  } note u_max = this
+
+  have "u *s x \<in> frontier s" unfolding frontier_straddle apply(rule,rule,rule) apply(rule_tac x="u *s x" in bexI) unfolding obt(3)[THEN sym]
+    prefer 3 apply(rule_tac x="(u + (e / 2) / norm x) *s x" in exI) apply(rule, rule) proof-
+    fix e  assume "0 < e" and as:"(u + e / 2 / norm x) *s x \<in> s"
+    hence "u + e / 2 / norm x > u" using`norm x > 0` by(auto simp del:zero_less_norm_iff intro!: divide_pos_pos)
+    thus False using u_max[OF _ as] by auto
+  qed(insert `y\<in>s`, auto simp add: dist_norm obt(3))
+  thus ?thesis apply(rule_tac that[of u]) apply(rule obt(1), assumption)
+    apply(rule,rule,rule ccontr) apply(rule u_max) by auto qed
+
+lemma starlike_compact_projective:
+  assumes "compact s" "cball (0::real^'n::finite) 1 \<subseteq> s "
+  "\<forall>x\<in>s. \<forall>u. 0 \<le> u \<and> u < 1 \<longrightarrow> (u *s x) \<in> (s - frontier s )"
+  shows "s homeomorphic (cball (0::real^'n::finite) 1)"
+proof-
+  have fs:"frontier s \<subseteq> s" apply(rule frontier_subset_closed) using compact_imp_closed[OF assms(1)] by simp
+  def pi \<equiv> "\<lambda>x::real^'n. inverse (norm x) *s x"
+  have "0 \<notin> frontier s" unfolding frontier_straddle apply(rule ccontr) unfolding not_not apply(erule_tac x=1 in allE)
+    using assms(2)[unfolded subset_eq Ball_def mem_cball] by auto
+  have injpi:"\<And>x y. pi x = pi y \<and> norm x = norm y \<longleftrightarrow> x = y" unfolding pi_def by auto
+
+  have contpi:"continuous_on (UNIV - {0}) pi" apply(rule continuous_at_imp_continuous_on)
+    apply rule unfolding pi_def apply(rule continuous_mul) unfolding o_def
+    apply(rule continuous_at_inv[unfolded o_def]) unfolding continuous_at_vec1_range[unfolded o_def]
+    apply(rule,rule) apply(rule_tac x=e in exI) apply(rule,assumption,rule,rule)
+    proof- fix e x y assume "0 < e" "norm (y - x::real^'n) < e" 
+      thus "\<bar>norm y - norm x\<bar> < e" using norm_triangle_ineq3[of y x] by auto
+    qed(auto intro!:continuous_at_id)
+  def sphere \<equiv> "{x::real^'n. norm x = 1}"
+  have pi:"\<And>x. x \<noteq> 0 \<Longrightarrow> pi x \<in> sphere" "\<And>x u. u>0 \<Longrightarrow> pi (u *s x) = pi x" unfolding pi_def sphere_def by auto
+
+  have "0\<in>s" using assms(2) and centre_in_cball[of 0 1] by auto
+  have front_smul:"\<forall>x\<in>frontier s. \<forall>u\<ge>0. u *s x \<in> s \<longleftrightarrow> u \<le> 1" proof(rule,rule,rule)
+    fix x u assume x:"x\<in>frontier s" and "(0::real)\<le>u"
+    hence "x\<noteq>0" using `0\<notin>frontier s` by auto
+    obtain v where v:"0 \<le> v" "v *s x \<in> frontier s" "\<forall>w>v. w *s x \<notin> s"
+      using compact_frontier_line_lemma[OF assms(1) `0\<in>s` `x\<noteq>0`] by auto
+    have "v=1" apply(rule ccontr) unfolding neq_iff apply(erule disjE) proof-
+      assume "v<1" thus False using v(3)[THEN spec[where x=1]] using x and fs by auto next
+      assume "v>1" thus False using assms(3)[THEN bspec[where x="v *s x"], THEN spec[where x="inverse v"]]
+	using v and x and fs unfolding inverse_less_1_iff by auto qed
+    show "u *s x \<in> s \<longleftrightarrow> u \<le> 1" apply rule  using v(3)[unfolded `v=1`, THEN spec[where x=u]] proof-
+      assume "u\<le>1" thus "u *s x \<in> s" apply(cases "u=1")
+	using assms(3)[THEN bspec[where x=x], THEN spec[where x=u]] using `0\<le>u` and x and fs by auto qed auto qed
+
+  have "\<exists>surf. homeomorphism (frontier s) sphere pi surf"
+    apply(rule homeomorphism_compact) apply(rule compact_frontier[OF assms(1)])
+    apply(rule continuous_on_subset[OF contpi]) defer apply(rule set_ext,rule) 
+    unfolding inj_on_def prefer 3 apply(rule,rule,rule)
+  proof- fix x assume "x\<in>pi ` frontier s" then obtain y where "y\<in>frontier s" "x = pi y" by auto
+    thus "x \<in> sphere" using pi(1)[of y] and `0 \<notin> frontier s` by auto
+  next fix x assume "x\<in>sphere" hence "norm x = 1" "x\<noteq>0" unfolding sphere_def by auto
+    then obtain u where "0 \<le> u" "u *s x \<in> frontier s" "\<forall>v>u. v *s x \<notin> s"
+      using compact_frontier_line_lemma[OF assms(1) `0\<in>s`, of x] by auto
+    thus "x \<in> pi ` frontier s" unfolding image_iff le_less pi_def apply(rule_tac x="u *s x" in bexI) using `norm x = 1` `0\<notin>frontier s` by auto
+  next fix x y assume as:"x \<in> frontier s" "y \<in> frontier s" "pi x = pi y"
+    hence xys:"x\<in>s" "y\<in>s" using fs by auto
+    from as(1,2) have nor:"norm x \<noteq> 0" "norm y \<noteq> 0" using `0\<notin>frontier s` by auto 
+    from nor have x:"x = norm x *s ((inverse (norm y)) *s y)" unfolding as(3)[unfolded pi_def, THEN sym] by auto 
+    from nor have y:"y = norm y *s ((inverse (norm x)) *s x)" unfolding as(3)[unfolded pi_def] by auto 
+    have "0 \<le> norm y * inverse (norm x)" "0 \<le> norm x * inverse (norm y)"
+      unfolding divide_inverse[THEN sym] apply(rule_tac[!] divide_nonneg_pos) using nor by auto
+    hence "norm x = norm y" apply(rule_tac ccontr) unfolding neq_iff
+      using x y and front_smul[THEN bspec, OF as(1), THEN spec[where x="norm y * (inverse (norm x))"]]
+      using front_smul[THEN bspec, OF as(2), THEN spec[where x="norm x * (inverse (norm y))"]]
+      using xys nor by(auto simp add:field_simps divide_le_eq_1 divide_inverse[THEN sym])
+    thus "x = y" apply(subst injpi[THEN sym]) using as(3) by auto
+  qed(insert `0 \<notin> frontier s`, auto)
+  then obtain surf where surf:"\<forall>x\<in>frontier s. surf (pi x) = x"  "pi ` frontier s = sphere" "continuous_on (frontier s) pi"
+    "\<forall>y\<in>sphere. pi (surf y) = y" "surf ` sphere = frontier s" "continuous_on sphere surf" unfolding homeomorphism_def by auto
+  
+  have cont_surfpi:"continuous_on (UNIV -  {0}) (surf \<circ> pi)" apply(rule continuous_on_compose, rule contpi)
+    apply(rule continuous_on_subset[of sphere], rule surf(6)) using pi(1) by auto
+
+  { fix x assume as:"x \<in> cball (0::real^'n) 1"
+    have "norm x *s surf (pi x) \<in> s" proof(cases "x=0 \<or> norm x = 1") 
+      case False hence "pi x \<in> sphere" "norm x < 1" using pi(1)[of x] as by(auto simp add: dist_norm)
+      thus ?thesis apply(rule_tac assms(3)[rule_format, THEN DiffD1])
+	apply(rule_tac fs[unfolded subset_eq, rule_format])
+	unfolding surf(5)[THEN sym] by auto
+    next case True thus ?thesis apply rule defer unfolding pi_def apply(rule fs[unfolded subset_eq, rule_format])
+	unfolding  surf(5)[unfolded sphere_def, THEN sym] using `0\<in>s` by auto qed } note hom = this
+
+  { fix x assume "x\<in>s"
+    hence "x \<in> (\<lambda>x. norm x *s surf (pi x)) ` cball 0 1" proof(cases "x=0")
+      case True show ?thesis unfolding image_iff True apply(rule_tac x=0 in bexI) by auto
+    next let ?a = "inverse (norm (surf (pi x)))"
+      case False hence invn:"inverse (norm x) \<noteq> 0" by auto
+      from False have pix:"pi x\<in>sphere" using pi(1) by auto
+      hence "pi (surf (pi x)) = pi x" apply(rule_tac surf(4)[rule_format]) by assumption
+      hence **:"norm x *s (?a *s surf (pi x)) = x" apply(rule_tac vector_mul_lcancel_imp[OF invn]) unfolding pi_def by auto
+      hence *:"?a * norm x > 0" and"?a > 0" "?a \<noteq> 0" using surf(5) `0\<notin>frontier s` apply -
+	apply(rule_tac mult_pos_pos) using False[unfolded zero_less_norm_iff[THEN sym]] by auto
+      have "norm (surf (pi x)) \<noteq> 0" using ** False by auto
+      hence "norm x = norm ((?a * norm x) *s surf (pi x))"
+	unfolding norm_mul abs_mult abs_norm_cancel abs_of_pos[OF `?a > 0`] by auto
+      moreover have "pi x = pi ((inverse (norm (surf (pi x))) * norm x) *s surf (pi x))" 
+	unfolding pi(2)[OF *] surf(4)[rule_format, OF pix] ..
+      moreover have "surf (pi x) \<in> frontier s" using surf(5) pix by auto
+      hence "dist 0 (inverse (norm (surf (pi x))) *s x) \<le> 1" unfolding dist_norm
+	using ** and * using front_smul[THEN bspec[where x="surf (pi x)"], THEN spec[where x="norm x * ?a"]]
+	using False `x\<in>s` by(auto simp add:field_simps)
+      ultimately show ?thesis unfolding image_iff apply(rule_tac x="inverse (norm (surf(pi x))) *s x" in bexI)
+	apply(subst injpi[THEN sym]) unfolding norm_mul abs_mult abs_norm_cancel abs_of_pos[OF `?a > 0`]
+	unfolding pi(2)[OF `?a > 0`] by auto
+    qed } note hom2 = this
+
+  show ?thesis apply(subst homeomorphic_sym) apply(rule homeomorphic_compact[where f="\<lambda>x. norm x *s surf (pi x)"])
+    apply(rule compact_cball) defer apply(rule set_ext, rule, erule imageE, drule hom)
+    prefer 4 apply(rule continuous_at_imp_continuous_on, rule) apply(rule_tac [3] hom2) proof-
+    fix x::"real^'n" assume as:"x \<in> cball 0 1"
+    thus "continuous (at x) (\<lambda>x. norm x *s surf (pi x))" proof(cases "x=0")
+      case False thus ?thesis apply(rule_tac continuous_mul, rule_tac continuous_at_vec1_norm)
+	using cont_surfpi unfolding continuous_on_eq_continuous_at[OF open_delete[OF open_UNIV]] o_def by auto
+    next guess a using UNIV_witness[where 'a = 'n] ..
+      obtain B where B:"\<forall>x\<in>s. norm x \<le> B" using compact_imp_bounded[OF assms(1)] unfolding bounded_def by auto
+      hence "B > 0" using assms(2) unfolding subset_eq apply(erule_tac x="basis a" in ballE) defer apply(erule_tac x="basis a" in ballE)
+	unfolding Ball_def mem_cball dist_norm by (auto simp add: norm_basis[unfolded One_nat_def])
+      case True show ?thesis unfolding True continuous_at Lim_at apply(rule,rule) apply(rule_tac x="e / B" in exI)
+	apply(rule) apply(rule divide_pos_pos) prefer 3 apply(rule,rule,erule conjE)
+	unfolding norm_0 vector_smult_lzero dist_norm diff_0_right norm_mul abs_norm_cancel proof-
+	fix e and x::"real^'n" assume as:"norm x < e / B" "0 < norm x" "0<e"
+	hence "surf (pi x) \<in> frontier s" using pi(1)[of x] unfolding surf(5)[THEN sym] by auto
+	hence "norm (surf (pi x)) \<le> B" using B fs by auto
+	hence "norm x * norm (surf (pi x)) \<le> norm x * B" using as(2) by auto
+	also have "\<dots> < e / B * B" apply(rule mult_strict_right_mono) using as(1) `B>0` by auto
+	also have "\<dots> = e" using `B>0` by auto
+	finally show "norm x * norm (surf (pi x)) < e" by assumption
+      qed(insert `B>0`, auto) qed
+  next { fix x assume as:"surf (pi x) = 0"
+      have "x = 0" proof(rule ccontr)
+	assume "x\<noteq>0" hence "pi x \<in> sphere" using pi(1) by auto
+	hence "surf (pi x) \<in> frontier s" using surf(5) by auto
+	thus False using `0\<notin>frontier s` unfolding as by simp qed
+    } note surf_0 = this
+    show "inj_on (\<lambda>x. norm x *s surf (pi x)) (cball 0 1)" unfolding inj_on_def proof(rule,rule,rule)
+      fix x y assume as:"x \<in> cball 0 1" "y \<in> cball 0 1" "norm x *s surf (pi x) = norm y *s surf (pi y)"
+      thus "x=y" proof(cases "x=0 \<or> y=0") 
+	case True thus ?thesis using as by(auto elim: surf_0) next
+	case False
+	hence "pi (surf (pi x)) = pi (surf (pi y))" using as(3)
+	  using pi(2)[of "norm x" "surf (pi x)"] pi(2)[of "norm y" "surf (pi y)"] by auto
+	moreover have "pi x \<in> sphere" "pi y \<in> sphere" using pi(1) False by auto
+	ultimately have *:"pi x = pi y" using surf(4)[THEN bspec[where x="pi x"]] surf(4)[THEN bspec[where x="pi y"]] by auto 
+	moreover have "norm x = norm y" using as(3)[unfolded *] using False by(auto dest:surf_0)
+	ultimately show ?thesis using injpi by auto qed qed
+  qed auto qed
+
+lemma homeomorphic_convex_compact_lemma: fixes s::"(real^'n::finite) set"
+  assumes "convex s" "compact s" "cball 0 1 \<subseteq> s"
+  shows "s homeomorphic (cball (0::real^'n) 1)"
+  apply(rule starlike_compact_projective[OF assms(2-3)]) proof(rule,rule,rule,erule conjE)
+  fix x u assume as:"x \<in> s" "0 \<le> u" "u < (1::real)"
+  hence "u *s x \<in> interior s" unfolding interior_def mem_Collect_eq
+    apply(rule_tac x="ball (u *s x) (1 - u)" in exI) apply(rule, rule open_ball)
+    unfolding centre_in_ball apply rule defer apply(rule) unfolding mem_ball proof-
+    fix y assume "dist (u *s x) y < 1 - u"
+    hence "inverse (1 - u) *s (y - u *s x) \<in> s"
+      using assms(3) apply(erule_tac subsetD) unfolding mem_cball dist_commute dist_norm
+      unfolding group_add_class.diff_0 group_add_class.diff_0_right norm_minus_cancel norm_mul      
+      apply (rule mult_left_le_imp_le[of "1 - u"])
+      unfolding class_semiring.mul_a using `u<1` by auto
+    thus "y \<in> s" using assms(1)[unfolded convex_def, rule_format, of "inverse(1 - u) *s (y - u *s x)" x "1 - u" u]
+      using as unfolding vector_smult_assoc by auto qed auto
+  thus "u *s x \<in> s - frontier s" using frontier_def and interior_subset by auto qed
+
+lemma homeomorphic_convex_compact_cball: fixes e::real and s::"(real^'n::finite) set"
+  assumes "convex s" "compact s" "interior s \<noteq> {}" "0 < e"
+  shows "s homeomorphic (cball (b::real^'n::finite) e)"
+proof- obtain a where "a\<in>interior s" using assms(3) by auto
+  then obtain d where "d>0" and d:"cball a d \<subseteq> s" unfolding mem_interior_cball by auto
+  let ?d = "inverse d" and ?n = "0::real^'n"
+  have "cball ?n 1 \<subseteq> (\<lambda>x. inverse d *s (x - a)) ` s"
+    apply(rule, rule_tac x="d *s x + a" in image_eqI) defer
+    apply(rule d[unfolded subset_eq, rule_format]) using `d>0` unfolding mem_cball dist_norm
+    by(auto simp add: mult_right_le_one_le)
+  hence "(\<lambda>x. inverse d *s (x - a)) ` s homeomorphic cball ?n 1"
+    using homeomorphic_convex_compact_lemma[of "(\<lambda>x. ?d *s -a + ?d *s x) ` s", OF convex_affinity compact_affinity]
+    using assms(1,2) by(auto simp add: uminus_add_conv_diff)
+  thus ?thesis apply(rule_tac homeomorphic_trans[OF _ homeomorphic_balls(2)[of 1 _ ?n]])
+    apply(rule homeomorphic_trans[OF homeomorphic_affinity[of "?d" s "?d *s -a"]])
+    using `d>0` `e>0` by(auto simp add: uminus_add_conv_diff) qed
+
+lemma homeomorphic_convex_compact: fixes s::"(real^'n::finite) set" and t::"(real^'n) set"
+  assumes "convex s" "compact s" "interior s \<noteq> {}"
+          "convex t" "compact t" "interior t \<noteq> {}"
+  shows "s homeomorphic t"
+  using assms by(meson zero_less_one homeomorphic_trans homeomorphic_convex_compact_cball homeomorphic_sym)
+
+subsection {* Epigraphs of convex functions. *}
+
+definition "epigraph s (f::real^'n \<Rightarrow> real) = {xy. fstcart xy \<in> s \<and> f(fstcart xy) \<le> dest_vec1 (sndcart xy)}"
+
+lemma mem_epigraph: "(pastecart x (vec1 y)) \<in> epigraph s f \<longleftrightarrow> x \<in> s \<and> f x \<le> y" unfolding epigraph_def by auto
+
+lemma convex_epigraph: 
+  "convex(epigraph s f) \<longleftrightarrow> convex_on s f \<and> convex s"
+  unfolding convex_def convex_on_def unfolding Ball_def forall_pastecart epigraph_def
+  unfolding mem_Collect_eq fstcart_pastecart sndcart_pastecart sndcart_add sndcart_cmul fstcart_add fstcart_cmul
+  unfolding Ball_def[symmetric] unfolding dest_vec1_add dest_vec1_cmul
+  apply(subst forall_dest_vec1[THEN sym])+ by(meson real_le_refl real_le_trans add_mono mult_left_mono) 
+
+lemma convex_epigraphI: assumes "convex_on s f" "convex s"
+  shows "convex(epigraph s f)" using assms unfolding convex_epigraph by auto
+
+lemma convex_epigraph_convex: "convex s \<Longrightarrow> (convex_on s f \<longleftrightarrow> convex(epigraph s f))"
+  using convex_epigraph by auto
+
+subsection {* Use this to derive general bound property of convex function. *}
+
+lemma forall_of_pastecart:
+  "(\<forall>p. P (\<lambda>x. fstcart (p x)) (\<lambda>x. sndcart (p x))) \<longleftrightarrow> (\<forall>x y. P x y)" apply meson
+  apply(erule_tac x="\<lambda>a. pastecart (x a) (y a)" in allE) unfolding o_def by auto
+
+lemma forall_of_pastecart':
+  "(\<forall>p. P (fstcart p) (sndcart p)) \<longleftrightarrow> (\<forall>x y. P x y)" apply meson
+  apply(erule_tac x="pastecart x y" in allE) unfolding o_def by auto
+
+lemma forall_of_dest_vec1: "(\<forall>v. P (\<lambda>x. dest_vec1 (v x))) \<longleftrightarrow> (\<forall>x. P x)"
+  apply rule apply rule apply(erule_tac x="(vec1 \<circ> x)" in allE) unfolding o_def vec1_dest_vec1 by auto 
+
+lemma forall_of_dest_vec1': "(\<forall>v. P (dest_vec1 v)) \<longleftrightarrow> (\<forall>x. P x)"
+  apply rule apply rule apply(erule_tac x="(vec1 x)" in allE) defer apply rule 
+  apply(erule_tac x="dest_vec1 v" in allE) unfolding o_def vec1_dest_vec1 by auto
+
+lemma convex_on:
+  assumes "convex s"
+  shows "convex_on s f \<longleftrightarrow> (\<forall>k u x. (\<forall>i\<in>{1..k::nat}. 0 \<le> u i \<and> x i \<in> s) \<and> setsum u {1..k} = 1 \<longrightarrow>
+   f (setsum (\<lambda>i. u i *s x i) {1..k} ) \<le> setsum (\<lambda>i. u i * f(x i)) {1..k} ) "
+  unfolding convex_epigraph_convex[OF assms] convex epigraph_def Ball_def mem_Collect_eq
+  unfolding sndcart_setsum[OF finite_atLeastAtMost] fstcart_setsum[OF finite_atLeastAtMost] dest_vec1_setsum[OF finite_atLeastAtMost]
+  unfolding fstcart_pastecart sndcart_pastecart sndcart_add sndcart_cmul fstcart_add fstcart_cmul
+  unfolding dest_vec1_add dest_vec1_cmul apply(subst forall_of_pastecart)+ apply(subst forall_of_dest_vec1)+ apply rule
+  using assms[unfolded convex] apply simp apply(rule,rule,rule)
+  apply(erule_tac x=k in allE, erule_tac x=u in allE, erule_tac x=x in allE) apply rule apply rule apply rule defer
+  apply(rule_tac j="\<Sum>i = 1..k. u i * f (x i)" in real_le_trans)
+  defer apply(rule setsum_mono) apply(erule conjE)+ apply(erule_tac x=i in allE)apply(rule mult_left_mono)
+  using assms[unfolded convex] by auto
+
+subsection {* Convexity of general and special intervals. *}
+
+lemma is_interval_convex: assumes "is_interval s" shows "convex s"
+  unfolding convex_def apply(rule,rule,rule,rule,rule,rule,rule) proof-
+  fix x y u v assume as:"x \<in> s" "y \<in> s" "0 \<le> u" "0 \<le> v" "u + v = (1::real)"
+  hence *:"u = 1 - v" "1 - v \<ge> 0" and **:"v = 1 - u" "1 - u \<ge> 0" by auto
+  { fix a b assume "\<not> b \<le> u * a + v * b"
+    hence "u * a < (1 - v) * b" unfolding not_le using as(4) by(auto simp add: field_simps)
+    hence "a < b" unfolding * using as(4) *(2) apply(rule_tac mult_left_less_imp_less[of "1 - v"]) by(auto simp add: field_simps)
+    hence "a \<le> u * a + v * b" unfolding * using as(4) by (auto simp add: field_simps intro!:mult_right_mono)
+  } moreover
+  { fix a b assume "\<not> u * a + v * b \<le> a"
+    hence "v * b > (1 - u) * a" unfolding not_le using as(4) by(auto simp add: field_simps)
+    hence "a < b" unfolding * using as(4) apply(rule_tac mult_left_less_imp_less) by(auto simp add: ring_simps)
+    hence "u * a + v * b \<le> b" unfolding ** using **(2) as(3) by(auto simp add: field_simps intro!:mult_right_mono) }
+  ultimately show "u *s x + v *s y \<in> s" apply- apply(rule assms[unfolded is_interval_def, rule_format, OF as(1,2)])
+    using as(3-) dimindex_ge_1 apply- by(auto simp add: vector_component) qed
+
+lemma is_interval_connected:
+  fixes s :: "(real ^ _) set"
+  shows "is_interval s \<Longrightarrow> connected s"
+  using is_interval_convex convex_connected by auto
+
+lemma convex_interval: "convex {a .. b}" "convex {a<..<b::real^'n::finite}"
+  apply(rule_tac[!] is_interval_convex) using is_interval_interval by auto
+
+subsection {* On real^1, is_interval, convex and connected are all equivalent. *}
+
+lemma is_interval_1:
+  "is_interval s \<longleftrightarrow> (\<forall>a\<in>s. \<forall>b\<in>s. \<forall> x. dest_vec1 a \<le> dest_vec1 x \<and> dest_vec1 x \<le> dest_vec1 b \<longrightarrow> x \<in> s)"
+  unfolding is_interval_def dest_vec1_def forall_1 by auto
+
+lemma is_interval_connected_1: "is_interval s \<longleftrightarrow> connected (s::(real^1) set)"
+  apply(rule, rule is_interval_connected, assumption) unfolding is_interval_1
+  apply(rule,rule,rule,rule,erule conjE,rule ccontr) proof-
+  fix a b x assume as:"connected s" "a \<in> s" "b \<in> s" "dest_vec1 a \<le> dest_vec1 x" "dest_vec1 x \<le> dest_vec1 b" "x\<notin>s"
+  hence *:"dest_vec1 a < dest_vec1 x" "dest_vec1 x < dest_vec1 b" apply(rule_tac [!] ccontr) unfolding not_less by auto
+  let ?halfl = "{z. basis 1 \<bullet> z < dest_vec1 x} " and ?halfr = "{z. basis 1 \<bullet> z > dest_vec1 x} "
+  { fix y assume "y \<in> s" have "y \<in> ?halfr \<union> ?halfl" apply(rule ccontr)
+    using as(6) `y\<in>s` by (auto simp add: basis_component field_simps dest_vec1_eq[unfolded dest_vec1_def One_nat_def] dest_vec1_def) }
+  moreover have "a\<in>?halfl" "b\<in>?halfr" using * by (auto simp add: basis_component field_simps dest_vec1_def) 
+  hence "?halfl \<inter> s \<noteq> {}" "?halfr \<inter> s \<noteq> {}"  using as(2-3) by auto
+  ultimately show False apply(rule_tac notE[OF as(1)[unfolded connected_def]])
+    apply(rule_tac x="?halfl" in exI, rule_tac x="?halfr" in exI) 
+    apply(rule, rule open_halfspace_lt, rule, rule open_halfspace_gt) apply(rule, rule, rule ccontr)
+    by(auto simp add: basis_component field_simps) qed 
+
+lemma is_interval_convex_1:
+  "is_interval s \<longleftrightarrow> convex (s::(real^1) set)" 
+  using is_interval_convex convex_connected is_interval_connected_1 by auto
+
+lemma convex_connected_1:
+  "connected s \<longleftrightarrow> convex (s::(real^1) set)" 
+  using is_interval_convex convex_connected is_interval_connected_1 by auto
+
+subsection {* Another intermediate value theorem formulation. *}
+
+lemma ivt_increasing_component_on_1: fixes f::"real^1 \<Rightarrow> real^'n::finite"
+  assumes "dest_vec1 a \<le> dest_vec1 b" "continuous_on {a .. b} f" "(f a)$k \<le> y" "y \<le> (f b)$k"
+  shows "\<exists>x\<in>{a..b}. (f x)$k = y"
+proof- have "f a \<in> f ` {a..b}" "f b \<in> f ` {a..b}" apply(rule_tac[!] imageI) 
+    using assms(1) by(auto simp add: vector_less_eq_def dest_vec1_def)
+  thus ?thesis using connected_ivt_component[of "f ` {a..b}" "f a" "f b" k y]
+    using connected_continuous_image[OF assms(2) convex_connected[OF convex_interval(1)]]
+    using assms by(auto intro!: imageI) qed
+
+lemma ivt_increasing_component_1: fixes f::"real^1 \<Rightarrow> real^'n::finite"
+  assumes "dest_vec1 a \<le> dest_vec1 b"
+  "\<forall>x\<in>{a .. b}. continuous (at x) f" "f a$k \<le> y" "y \<le> f b$k"
+  shows "\<exists>x\<in>{a..b}. (f x)$k = y"
+  apply(rule ivt_increasing_component_on_1) using assms using continuous_at_imp_continuous_on by auto
+
+lemma ivt_decreasing_component_on_1: fixes f::"real^1 \<Rightarrow> real^'n::finite"
+  assumes "dest_vec1 a \<le> dest_vec1 b" "continuous_on {a .. b} f" "(f b)$k \<le> y" "y \<le> (f a)$k"
+  shows "\<exists>x\<in>{a..b}. (f x)$k = y"
+  apply(subst neg_equal_iff_equal[THEN sym]) unfolding vector_uminus_component[THEN sym]
+  apply(rule ivt_increasing_component_on_1) using assms using continuous_on_neg
+  by(auto simp add:vector_uminus_component)
+
+lemma ivt_decreasing_component_1: fixes f::"real^1 \<Rightarrow> real^'n::finite"
+  assumes "dest_vec1 a \<le> dest_vec1 b" "\<forall>x\<in>{a .. b}. continuous (at x) f" "f b$k \<le> y" "y \<le> f a$k"
+  shows "\<exists>x\<in>{a..b}. (f x)$k = y"
+  apply(rule ivt_decreasing_component_on_1) using assms using continuous_at_imp_continuous_on by auto
+
+subsection {* A bound within a convex hull, and so an interval. *}
+
+lemma convex_on_convex_hull_bound:
+  assumes "convex_on (convex hull s) f" "\<forall>x\<in>s. f x \<le> b"
+  shows "\<forall>x\<in> convex hull s. f x \<le> b" proof
+  fix x assume "x\<in>convex hull s"
+  then obtain k u v where obt:"\<forall>i\<in>{1..k::nat}. 0 \<le> u i \<and> v i \<in> s" "setsum u {1..k} = 1" "(\<Sum>i = 1..k. u i *s v i) = x"
+    unfolding convex_hull_indexed mem_Collect_eq by auto
+  have "(\<Sum>i = 1..k. u i * f (v i)) \<le> b" using setsum_mono[of "{1..k}" "\<lambda>i. u i * f (v i)" "\<lambda>i. u i * b"]
+    unfolding setsum_left_distrib[THEN sym] obt(2) mult_1 apply(drule_tac meta_mp) apply(rule mult_left_mono)
+    using assms(2) obt(1) by auto
+  thus "f x \<le> b" using assms(1)[unfolded convex_on[OF convex_convex_hull], rule_format, of k u v]
+    unfolding obt(2-3) using obt(1) and hull_subset[unfolded subset_eq, rule_format, of _ s] by auto qed
+
+lemma unit_interval_convex_hull:
+  "{0::real^'n::finite .. 1} = convex hull {x. \<forall>i. (x$i = 0) \<or> (x$i = 1)}" (is "?int = convex hull ?points")
+proof- have 01:"{0,1} \<subseteq> convex hull ?points" apply rule apply(rule_tac hull_subset[unfolded subset_eq, rule_format]) by auto
+  { fix n x assume "x\<in>{0::real^'n .. 1}" "n \<le> CARD('n)" "card {i. x$i \<noteq> 0} \<le> n" 
+  hence "x\<in>convex hull ?points" proof(induct n arbitrary: x)
+    case 0 hence "x = 0" apply(subst Cart_eq) apply rule by auto
+    thus "x\<in>convex hull ?points" using 01 by auto
+  next
+    case (Suc n) show "x\<in>convex hull ?points" proof(cases "{i. x$i \<noteq> 0} = {}")
+      case True hence "x = 0" unfolding Cart_eq by auto
+      thus "x\<in>convex hull ?points" using 01 by auto
+    next
+      case False def xi \<equiv> "Min ((\<lambda>i. x$i) ` {i. x$i \<noteq> 0})"
+      have "xi \<in> (\<lambda>i. x$i) ` {i. x$i \<noteq> 0}" unfolding xi_def apply(rule Min_in) using False by auto
+      then obtain i where i':"x$i = xi" "x$i \<noteq> 0" by auto
+      have i:"\<And>j. x$j > 0 \<Longrightarrow> x$i \<le> x$j"
+	unfolding i'(1) xi_def apply(rule_tac Min_le) unfolding image_iff
+	defer apply(rule_tac x=j in bexI) using i' by auto
+      have i01:"x$i \<le> 1" "x$i > 0" using Suc(2)[unfolded mem_interval,rule_format,of i] using i'(2) `x$i \<noteq> 0`
+	by(auto simp add: Cart_lambda_beta) 
+      show ?thesis proof(cases "x$i=1")
+	case True have "\<forall>j\<in>{i. x$i \<noteq> 0}. x$j = 1" apply(rule, rule ccontr) unfolding mem_Collect_eq proof-
+	  fix j assume "x $ j \<noteq> 0" "x $ j \<noteq> 1"
+	  hence j:"x$j \<in> {0<..<1}" using Suc(2) by(auto simp add: vector_less_eq_def elim!:allE[where x=j])
+	  hence "x$j \<in> op $ x ` {i. x $ i \<noteq> 0}" by auto 
+	  hence "x$j \<ge> x$i" unfolding i'(1) xi_def apply(rule_tac Min_le) by auto
+	  thus False using True Suc(2) j by(auto simp add: vector_less_eq_def elim!:ballE[where x=j]) qed
+        thus "x\<in>convex hull ?points" apply(rule_tac hull_subset[unfolded subset_eq, rule_format])
+	  by(auto simp add: Cart_lambda_beta)
+      next let ?y = "\<lambda>j. if x$j = 0 then 0 else (x$j - x$i) / (1 - x$i)"
+	case False hence *:"x = x$i *s (\<chi> j. if x$j = 0 then 0 else 1) + (1 - x$i) *s (\<chi> j. ?y j)" unfolding Cart_eq
+	  by(auto simp add: Cart_lambda_beta vector_add_component vector_smult_component vector_minus_component field_simps)
+	{ fix j have "x$j \<noteq> 0 \<Longrightarrow> 0 \<le> (x $ j - x $ i) / (1 - x $ i)" "(x $ j - x $ i) / (1 - x $ i) \<le> 1"
+	    apply(rule_tac divide_nonneg_pos) using i(1)[of j] using False i01
+	    using Suc(2)[unfolded mem_interval, rule_format, of j] by(auto simp add:field_simps Cart_lambda_beta) 
+	  hence "0 \<le> ?y j \<and> ?y j \<le> 1" by auto }
+	moreover have "i\<in>{j. x$j \<noteq> 0} - {j. ((\<chi> j. ?y j)::real^'n) $ j \<noteq> 0}" using i01 by(auto simp add: Cart_lambda_beta)
+	hence "{j. x$j \<noteq> 0} \<noteq> {j. ((\<chi> j. ?y j)::real^'n::finite) $ j \<noteq> 0}" by auto
+	hence **:"{j. ((\<chi> j. ?y j)::real^'n::finite) $ j \<noteq> 0} \<subset> {j. x$j \<noteq> 0}" apply - apply rule by(auto simp add: Cart_lambda_beta)  
+	have "card {j. ((\<chi> j. ?y j)::real^'n) $ j \<noteq> 0} \<le> n" using less_le_trans[OF psubset_card_mono[OF _ **] Suc(4)] by auto
+	ultimately show ?thesis apply(subst *) apply(rule convex_convex_hull[unfolded convex_def, rule_format])
+	  apply(rule_tac hull_subset[unfolded subset_eq, rule_format]) defer apply(rule Suc(1))
+	  unfolding mem_interval using i01 Suc(3) by (auto simp add: Cart_lambda_beta)
+      qed qed qed } note * = this
+  show ?thesis apply rule defer apply(rule hull_minimal) unfolding subset_eq prefer 3 apply rule 
+    apply(rule_tac n2="CARD('n)" in *) prefer 3 apply(rule card_mono) using 01 and convex_interval(1) prefer 5 apply - apply rule
+    unfolding mem_interval apply rule unfolding mem_Collect_eq apply(erule_tac x=i in allE)
+    by(auto simp add: vector_less_eq_def mem_def[of _ convex]) qed
+
+subsection {* And this is a finite set of vertices. *}
+
+lemma unit_cube_convex_hull: obtains s where "finite s" "{0 .. 1::real^'n::finite} = convex hull s"
+  apply(rule that[of "{x::real^'n::finite. \<forall>i. x$i=0 \<or> x$i=1}"])
+  apply(rule finite_subset[of _ "(\<lambda>s. (\<chi> i. if i\<in>s then 1::real else 0)::real^'n::finite) ` UNIV"])
+  prefer 3 apply(rule unit_interval_convex_hull) apply rule unfolding mem_Collect_eq proof-
+  fix x::"real^'n" assume as:"\<forall>i. x $ i = 0 \<or> x $ i = 1"
+  show "x \<in> (\<lambda>s. \<chi> i. if i \<in> s then 1 else 0) ` UNIV" apply(rule image_eqI[where x="{i. x$i = 1}"])
+    unfolding Cart_eq using as by(auto simp add:Cart_lambda_beta) qed auto
+
+subsection {* Hence any cube (could do any nonempty interval). *}
+
+lemma cube_convex_hull:
+  assumes "0 < d" obtains s::"(real^'n::finite) set" where "finite s" "{x - (\<chi> i. d) .. x + (\<chi> i. d)} = convex hull s" proof-
+  let ?d = "(\<chi> i. d)::real^'n"
+  have *:"{x - ?d .. x + ?d} = (\<lambda>y. x - ?d + (2 * d) *s y) ` {0 .. 1}" apply(rule set_ext, rule)
+    unfolding image_iff defer apply(erule bexE) proof-
+    fix y assume as:"y\<in>{x - ?d .. x + ?d}"
+    { fix i::'n have "x $ i \<le> d + y $ i" "y $ i \<le> d + x $ i" using as[unfolded mem_interval, THEN spec[where x=i]]
+	by(auto simp add: vector_component)
+      hence "1 \<ge> inverse d * (x $ i - y $ i)" "1 \<ge> inverse d * (y $ i - x $ i)"
+	apply(rule_tac[!] mult_left_le_imp_le[OF _ assms]) unfolding mult_assoc[THEN sym]
+	using assms by(auto simp add: field_simps right_inverse) 
+      hence "inverse d * (x $ i * 2) \<le> 2 + inverse d * (y $ i * 2)"
+            "inverse d * (y $ i * 2) \<le> 2 + inverse d * (x $ i * 2)" by(auto simp add:field_simps) }
+    hence "inverse (2 * d) *s (y - (x - ?d)) \<in> {0..1}" unfolding mem_interval using assms
+      by(auto simp add: Cart_eq vector_component_simps field_simps)
+    thus "\<exists>z\<in>{0..1}. y = x - ?d + (2 * d) *s z" apply- apply(rule_tac x="inverse (2 * d) *s (y - (x - ?d))" in bexI) 
+      using assms by(auto simp add: Cart_eq vector_less_eq_def Cart_lambda_beta)
+  next
+    fix y z assume as:"z\<in>{0..1}" "y = x - ?d + (2*d) *s z" 
+    have "\<And>i. 0 \<le> d * z $ i \<and> d * z $ i \<le> d" using assms as(1)[unfolded mem_interval] apply(erule_tac x=i in allE)
+      apply rule apply(rule mult_nonneg_nonneg) prefer 3 apply(rule mult_right_le_one_le)
+      using assms by(auto simp add: vector_component_simps Cart_eq)
+    thus "y \<in> {x - ?d..x + ?d}" unfolding as(2) mem_interval apply- apply rule using as(1)[unfolded mem_interval]
+      apply(erule_tac x=i in allE) using assms by(auto simp add:  vector_component_simps Cart_eq) qed
+  obtain s where "finite s" "{0..1::real^'n} = convex hull s" using unit_cube_convex_hull by auto
+  thus ?thesis apply(rule_tac that[of "(\<lambda>y. x - ?d + (2 * d) *s y)` s"]) unfolding * and convex_hull_affinity by auto qed
+
+subsection {* Bounded convex function on open set is continuous. *}
+
+lemma convex_on_bounded_continuous:
+  assumes "open s" "convex_on s f" "\<forall>x\<in>s. abs(f x) \<le> b"
+  shows "continuous_on s (vec1 o f)"
+  apply(rule continuous_at_imp_continuous_on) unfolding continuous_at_vec1_range proof(rule,rule,rule)
+  fix x e assume "x\<in>s" "(0::real) < e"
+  def B \<equiv> "abs b + 1"
+  have B:"0 < B" "\<And>x. x\<in>s \<Longrightarrow> abs (f x) \<le> B"
+    unfolding B_def defer apply(drule assms(3)[rule_format]) by auto
+  obtain k where "k>0"and k:"cball x k \<subseteq> s" using assms(1)[unfolded open_contains_cball, THEN bspec[where x=x]] using `x\<in>s` by auto
+  show "\<exists>d>0. \<forall>x'. norm (x' - x) < d \<longrightarrow> \<bar>f x' - f x\<bar> < e"
+    apply(rule_tac x="min (k / 2) (e / (2 * B) * k)" in exI) apply rule defer proof(rule,rule)
+    fix y assume as:"norm (y - x) < min (k / 2) (e / (2 * B) * k)" 
+    show "\<bar>f y - f x\<bar> < e" proof(cases "y=x")
+      case False def t \<equiv> "k / norm (y - x)"
+      have "2 < t" "0<t" unfolding t_def using as False and `k>0` by(auto simp add:field_simps)
+      have "y\<in>s" apply(rule k[unfolded subset_eq,rule_format]) unfolding mem_cball dist_norm
+	apply(rule order_trans[of _ "2 * norm (x - y)"]) using as by(auto simp add: field_simps norm_minus_commute) 
+      { def w \<equiv> "x + t *s (y - x)"
+	have "w\<in>s" unfolding w_def apply(rule k[unfolded subset_eq,rule_format]) unfolding mem_cball dist_norm 
+	  unfolding t_def using `k>0` by(auto simp add: norm_mul simp del: vector_ssub_ldistrib) 
+	have "(1 / t) *s x + - x + ((t - 1) / t) *s x = (1 / t - 1 + (t - 1) / t) *s x" by auto 
+	also have "\<dots> = 0"  using `t>0` by(auto simp add:field_simps simp del:vector_sadd_rdistrib)
+	finally have w:"(1 / t) *s w + ((t - 1) / t) *s x = y" unfolding w_def using False and `t>0` by auto
+	have  "2 * B < e * t" unfolding t_def using `0<e` `0<k` `B>0` and as and False by (auto simp add:field_simps) 
+	hence "(f w - f x) / t < e"
+	  using B(2)[OF `w\<in>s`] and B(2)[OF `x\<in>s`] using `t>0` by(auto simp add:field_simps) 
+	hence th1:"f y - f x < e" apply- apply(rule le_less_trans) defer apply assumption
+	  using assms(2)[unfolded convex_on_def,rule_format,of w x "1/t" "(t - 1)/t", unfolded w]
+	  using `0<t` `2<t` and `x\<in>s` `w\<in>s` by(auto simp add:field_simps) }
+      moreover 
+      { def w \<equiv> "x - t *s (y - x)"
+	have "w\<in>s" unfolding w_def apply(rule k[unfolded subset_eq,rule_format]) unfolding mem_cball dist_norm 
+	  unfolding t_def using `k>0` by(auto simp add: norm_mul simp del: vector_ssub_ldistrib) 
+	have "(1 / (1 + t)) *s x + (t / (1 + t)) *s x = (1 / (1 + t) + t / (1 + t)) *s x" by auto
+	also have "\<dots>=x" using `t>0` by (auto simp add:field_simps simp del:vector_sadd_rdistrib)
+	finally have w:"(1 / (1+t)) *s w + (t / (1 + t)) *s y = x" unfolding w_def using False and `t>0` by auto 
+	have  "2 * B < e * t" unfolding t_def using `0<e` `0<k` `B>0` and as and False by (auto simp add:field_simps) 
+	hence *:"(f w - f y) / t < e" using B(2)[OF `w\<in>s`] and B(2)[OF `y\<in>s`] using `t>0` by(auto simp add:field_simps) 
+	have "f x \<le> 1 / (1 + t) * f w + (t / (1 + t)) * f y" 
+	  using assms(2)[unfolded convex_on_def,rule_format,of w y "1/(1+t)" "t / (1+t)",unfolded w]
+	  using `0<t` `2<t` and `y\<in>s` `w\<in>s` by (auto simp add:field_simps)
+	also have "\<dots> = (f w + t * f y) / (1 + t)" using `t>0` unfolding real_divide_def by (auto simp add:field_simps)
+	also have "\<dots> < e + f y" using `t>0` * `e>0` by(auto simp add:field_simps)
+	finally have "f x - f y < e" by auto }
+      ultimately show ?thesis by auto 
+    qed(insert `0<e`, auto) 
+  qed(insert `0<e` `0<k` `0<B`, auto simp add:field_simps intro!:mult_pos_pos) qed
+
+subsection {* Upper bound on a ball implies upper and lower bounds. *}
+
+lemma convex_bounds_lemma:
+  assumes "convex_on (cball x e) f"  "\<forall>y \<in> cball x e. f y \<le> b"
+  shows "\<forall>y \<in> cball x e. abs(f y) \<le> b + 2 * abs(f x)"
+  apply(rule) proof(cases "0 \<le> e") case True
+  fix y assume y:"y\<in>cball x e" def z \<equiv> "2 *s x - y"
+  have *:"x - (2 *s x - y) = y - x" by vector
+  have z:"z\<in>cball x e" using y unfolding z_def mem_cball dist_norm * by(auto simp add: norm_minus_commute)
+  have "(1 / 2) *s y + (1 / 2) *s z = x" unfolding z_def by auto
+  thus "\<bar>f y\<bar> \<le> b + 2 * \<bar>f x\<bar>" using assms(1)[unfolded convex_on_def,rule_format, OF y z, of "1/2" "1/2"]
+    using assms(2)[rule_format,OF y] assms(2)[rule_format,OF z] by(auto simp add:field_simps)
+next case False fix y assume "y\<in>cball x e" 
+  hence "dist x y < 0" using False unfolding mem_cball not_le by (auto simp del: dist_not_less_zero)
+  thus "\<bar>f y\<bar> \<le> b + 2 * \<bar>f x\<bar>" using zero_le_dist[of x y] by auto qed
+
+subsection {* Hence a convex function on an open set is continuous. *}
+
+lemma convex_on_continuous:
+  assumes "open (s::(real^'n::finite) set)" "convex_on s f" 
+  shows "continuous_on s (vec1 \<circ> f)"
+  unfolding continuous_on_eq_continuous_at[OF assms(1)] proof
+  note dimge1 = dimindex_ge_1[where 'a='n]
+  fix x assume "x\<in>s"
+  then obtain e where e:"cball x e \<subseteq> s" "e>0" using assms(1) unfolding open_contains_cball by auto
+  def d \<equiv> "e / real CARD('n)"
+  have "0 < d" unfolding d_def using `e>0` dimge1 by(rule_tac divide_pos_pos, auto) 
+  let ?d = "(\<chi> i. d)::real^'n"
+  obtain c where c:"finite c" "{x - ?d..x + ?d} = convex hull c" using cube_convex_hull[OF `d>0`, of x] by auto
+  have "x\<in>{x - ?d..x + ?d}" using `d>0` unfolding mem_interval by(auto simp add:vector_component_simps)
+  hence "c\<noteq>{}" apply(rule_tac ccontr) using c by(auto simp add:convex_hull_empty)
+  def k \<equiv> "Max (f ` c)"
+  have "convex_on {x - ?d..x + ?d} f" apply(rule convex_on_subset[OF assms(2)])
+    apply(rule subset_trans[OF _ e(1)]) unfolding subset_eq mem_cball proof 
+    fix z assume z:"z\<in>{x - ?d..x + ?d}"
+    have e:"e = setsum (\<lambda>i. d) (UNIV::'n set)" unfolding setsum_constant d_def using dimge1
+      by (metis card_enum field_simps d_def not_one_le_zero of_nat_le_iff real_eq_of_nat real_of_nat_1)
+    show "dist x z \<le> e" unfolding dist_norm e apply(rule_tac order_trans[OF norm_le_l1], rule setsum_mono)
+      using z[unfolded mem_interval] apply(erule_tac x=i in allE) by(auto simp add:field_simps vector_component_simps) qed
+  hence k:"\<forall>y\<in>{x - ?d..x + ?d}. f y \<le> k" unfolding c(2) apply(rule_tac convex_on_convex_hull_bound) apply assumption
+    unfolding k_def apply(rule, rule Max_ge) using c(1) by auto
+  have "d \<le> e" unfolding d_def apply(rule mult_imp_div_pos_le) using `e>0` dimge1 unfolding mult_le_cancel_left1 using real_dimindex_ge_1 by auto
+  hence dsube:"cball x d \<subseteq> cball x e" unfolding subset_eq Ball_def mem_cball by auto
+  have conv:"convex_on (cball x d) f" apply(rule convex_on_subset, rule convex_on_subset[OF assms(2)]) apply(rule e(1)) using dsube by auto
+  hence "\<forall>y\<in>cball x d. abs (f y) \<le> k + 2 * abs (f x)" apply(rule_tac convex_bounds_lemma) apply assumption proof
+    fix y assume y:"y\<in>cball x d"
+    { fix i::'n have "x $ i - d \<le> y $ i"  "y $ i \<le> x $ i + d" 
+	using order_trans[OF component_le_norm y[unfolded mem_cball dist_norm], of i] by(auto simp add: vector_component)  }
+    thus "f y \<le> k" apply(rule_tac k[rule_format]) unfolding mem_cball mem_interval dist_norm 
+      by(auto simp add: vector_component_simps) qed
+  hence "continuous_on (ball x d) (vec1 \<circ> f)" apply(rule_tac convex_on_bounded_continuous)
+    apply(rule open_ball, rule convex_on_subset[OF conv], rule ball_subset_cball) by auto
+  thus "continuous (at x) (vec1 \<circ> f)" unfolding continuous_on_eq_continuous_at[OF open_ball] using `d>0` by auto qed
+
+subsection {* Line segments, starlike sets etc.                                         *)
+(* Use the same overloading tricks as for intervals, so that                 *)
+(* segment[a,b] is closed and segment(a,b) is open relative to affine hull. *}
+
+definition "midpoint a b = (inverse (2::real)) *s (a + b)"
+
+definition "open_segment a b = {(1 - u) *s a + u *s b | u::real.  0 < u \<and> u < 1}"
+
+definition "closed_segment a b = {(1 - u) *s a + u *s b | u::real. 0 \<le> u \<and> u \<le> 1}"
+
+definition "between = (\<lambda> (a,b). closed_segment a b)"
+
+lemmas segment = open_segment_def closed_segment_def
+
+definition "starlike s \<longleftrightarrow> (\<exists>a\<in>s. \<forall>x\<in>s. closed_segment a x \<subseteq> s)"
+
+lemma midpoint_refl: "midpoint x x = x"
+  unfolding midpoint_def unfolding vector_add_ldistrib unfolding vector_sadd_rdistrib[THEN sym] by auto
+
+lemma midpoint_sym: "midpoint a b = midpoint b a" unfolding midpoint_def by auto
+
+lemma dist_midpoint:
+  "dist a (midpoint a b) = (dist a b) / 2" (is ?t1)
+  "dist b (midpoint a b) = (dist a b) / 2" (is ?t2)
+  "dist (midpoint a b) a = (dist a b) / 2" (is ?t3)
+  "dist (midpoint a b) b = (dist a b) / 2" (is ?t4)
+proof-
+  have *: "\<And>x y::real^'n::finite. 2 *s x = - y \<Longrightarrow> norm x = (norm y) / 2" unfolding equation_minus_iff by auto
+  have **:"\<And>x y::real^'n::finite. 2 *s x =   y \<Longrightarrow> norm x = (norm y) / 2" by auto
+  show ?t1 unfolding midpoint_def dist_norm apply (rule **) by(auto,vector)
+  show ?t2 unfolding midpoint_def dist_norm apply (rule *)  by(auto,vector)
+  show ?t3 unfolding midpoint_def dist_norm apply (rule *)  by(auto,vector)
+  show ?t4 unfolding midpoint_def dist_norm apply (rule **) by(auto,vector) qed
+
+lemma midpoint_eq_endpoint:
+  "midpoint a b = a \<longleftrightarrow> a = (b::real^'n::finite)"
+  "midpoint a b = b \<longleftrightarrow> a = b"
+  unfolding dist_eq_0_iff[where 'a="real^'n", THEN sym] dist_midpoint by auto
+
+lemma convex_contains_segment:
+  "convex s \<longleftrightarrow> (\<forall>a\<in>s. \<forall>b\<in>s. closed_segment a b \<subseteq> s)"
+  unfolding convex_alt closed_segment_def by auto
+
+lemma convex_imp_starlike:
+  "convex s \<Longrightarrow> s \<noteq> {} \<Longrightarrow> starlike s"
+  unfolding convex_contains_segment starlike_def by auto
+
+lemma segment_convex_hull:
+ "closed_segment a b = convex hull {a,b}" proof-
+  have *:"\<And>x. {x} \<noteq> {}" by auto
+  have **:"\<And>u v. u + v = 1 \<longleftrightarrow> u = 1 - (v::real)" by auto
+  show ?thesis unfolding segment convex_hull_insert[OF *] convex_hull_singleton apply(rule set_ext)
+    unfolding mem_Collect_eq apply(rule,erule exE) 
+    apply(rule_tac x="1 - u" in exI) apply rule defer apply(rule_tac x=u in exI) defer
+    apply(erule exE, (erule conjE)?)+ apply(rule_tac x="1 - u" in exI) unfolding ** by auto qed
+
+lemma convex_segment: "convex (closed_segment a b)"
+  unfolding segment_convex_hull by(rule convex_convex_hull)
+
+lemma ends_in_segment: "a \<in> closed_segment a b" "b \<in> closed_segment a b"
+  unfolding segment_convex_hull apply(rule_tac[!] hull_subset[unfolded subset_eq, rule_format]) by auto
+
+lemma segment_furthest_le:
+  assumes "x \<in> closed_segment a b" shows "norm(y - x) \<le> norm(y - a) \<or>  norm(y - x) \<le> norm(y - b)" proof-
+  obtain z where "z\<in>{a, b}" "norm (x - y) \<le> norm (z - y)" using simplex_furthest_le[of "{a, b}" y]
+    using assms[unfolded segment_convex_hull] by auto
+  thus ?thesis by(auto simp add:norm_minus_commute) qed
+
+lemma segment_bound:
+  assumes "x \<in> closed_segment a b"
+  shows "norm(x - a) \<le> norm(b - a)" "norm(x - b) \<le> norm(b - a)"
+  using segment_furthest_le[OF assms, of a]
+  using segment_furthest_le[OF assms, of b]
+  by (auto simp add:norm_minus_commute) 
+
+lemma segment_refl:"closed_segment a a = {a}" unfolding segment by auto
+
+lemma between_mem_segment: "between (a,b) x \<longleftrightarrow> x \<in> closed_segment a b"
+  unfolding between_def mem_def by auto
+
+lemma between:"between (a,b) (x::real^'n::finite) \<longleftrightarrow> dist a b = (dist a x) + (dist x b)"
+proof(cases "a = b")
+  case True thus ?thesis unfolding between_def split_conv mem_def[of x, symmetric]
+    by(auto simp add:segment_refl dist_commute) next
+  case False hence Fal:"norm (a - b) \<noteq> 0" and Fal2: "norm (a - b) > 0" by auto 
+  have *:"\<And>u. a - ((1 - u) *s a + u *s b) = u *s (a - b)" by auto
+  show ?thesis unfolding between_def split_conv mem_def[of x, symmetric] closed_segment_def mem_Collect_eq
+    apply rule apply(erule exE, (erule conjE)+) apply(subst dist_triangle_eq) proof-
+      fix u assume as:"x = (1 - u) *s a + u *s b" "0 \<le> u" "u \<le> 1" 
+      hence *:"a - x = u *s (a - b)" "x - b = (1 - u) *s (a - b)"
+	unfolding as(1) by(auto simp add:field_simps)
+      show "norm (a - x) *s (x - b) = norm (x - b) *s (a - x)"
+	unfolding norm_minus_commute[of x a] * norm_mul Cart_eq using as(2,3)
+	by(auto simp add: vector_component_simps field_simps)
+    next assume as:"dist a b = dist a x + dist x b"
+      have "norm (a - x) / norm (a - b) \<le> 1" unfolding divide_le_eq_1_pos[OF Fal2] unfolding as[unfolded dist_norm] norm_ge_zero by auto 
+      thus "\<exists>u. x = (1 - u) *s a + u *s b \<and> 0 \<le> u \<and> u \<le> 1" apply(rule_tac x="dist a x / dist a b" in exI)
+	unfolding dist_norm Cart_eq apply- apply rule defer apply(rule, rule divide_nonneg_pos) prefer 4 proof rule
+	  fix i::'n have "((1 - norm (a - x) / norm (a - b)) *s a + (norm (a - x) / norm (a - b)) *s b) $ i =
+	    ((norm (a - b) - norm (a - x)) * (a $ i) + norm (a - x) * (b $ i)) / norm (a - b)"
+	    using Fal by(auto simp add:vector_component_simps field_simps)
+	  also have "\<dots> = x$i" apply(rule divide_eq_imp[OF Fal])
+	    unfolding as[unfolded dist_norm] using as[unfolded dist_triangle_eq Cart_eq,rule_format, of i]
+	    by(auto simp add:field_simps vector_component_simps)
+	  finally show "x $ i = ((1 - norm (a - x) / norm (a - b)) *s a + (norm (a - x) / norm (a - b)) *s b) $ i" by auto
+	qed(insert Fal2, auto) qed qed
+
+lemma between_midpoint: fixes a::"real^'n::finite" shows
+  "between (a,b) (midpoint a b)" (is ?t1) 
+  "between (b,a) (midpoint a b)" (is ?t2)
+proof- have *:"\<And>x y z. x = (1/2::real) *s z \<Longrightarrow> y = (1/2) *s z \<Longrightarrow> norm z = norm x + norm y" by auto
+  show ?t1 ?t2 unfolding between midpoint_def dist_norm apply(rule_tac[!] *)
+    by(auto simp add:field_simps Cart_eq vector_component_simps) qed
+
+lemma between_mem_convex_hull:
+  "between (a,b) x \<longleftrightarrow> x \<in> convex hull {a,b}"
+  unfolding between_mem_segment segment_convex_hull ..
+
+subsection {* Shrinking towards the interior of a convex set. *}
+
+lemma mem_interior_convex_shrink:
+  assumes "convex s" "c \<in> interior s" "x \<in> s" "0 < e" "e \<le> 1"
+  shows "x - e *s (x - c) \<in> interior s"
+proof- obtain d where "d>0" and d:"ball c d \<subseteq> s" using assms(2) unfolding mem_interior by auto
+  show ?thesis unfolding mem_interior apply(rule_tac x="e*d" in exI)
+    apply(rule) defer unfolding subset_eq Ball_def mem_ball proof(rule,rule)
+    fix y assume as:"dist (x - e *s (x - c)) y < e * d"
+    have *:"y = (1 - (1 - e)) *s ((1 / e) *s y - ((1 - e) / e) *s x) + (1 - e) *s x" using `e>0` by auto
+    have "dist c ((1 / e) *s y - ((1 - e) / e) *s x) = abs(1/e) * norm (e *s c - y + (1 - e) *s x)"
+      unfolding dist_norm unfolding norm_mul[THEN sym] apply(rule norm_eqI) using `e>0`
+      by(auto simp add:vector_component_simps Cart_eq field_simps) 
+    also have "\<dots> = abs(1/e) * norm (x - e *s (x - c) - y)" by(auto intro!:norm_eqI)
+    also have "\<dots> < d" using as[unfolded dist_norm] and `e>0`
+      by(auto simp add:pos_divide_less_eq[OF `e>0`] real_mult_commute)
+    finally show "y \<in> s" apply(subst *) apply(rule assms(1)[unfolded convex_alt,rule_format])
+      apply(rule d[unfolded subset_eq,rule_format]) unfolding mem_ball using assms(3-5) by auto
+  qed(rule mult_pos_pos, insert `e>0` `d>0`, auto) qed
+
+lemma mem_interior_closure_convex_shrink:
+  assumes "convex s" "c \<in> interior s" "x \<in> closure s" "0 < e" "e \<le> 1"
+  shows "x - e *s (x - c) \<in> interior s"
+proof- obtain d where "d>0" and d:"ball c d \<subseteq> s" using assms(2) unfolding mem_interior by auto
+  have "\<exists>y\<in>s. norm (y - x) * (1 - e) < e * d" proof(cases "x\<in>s")
+    case True thus ?thesis using `e>0` `d>0` by(rule_tac bexI[where x=x], auto intro!: mult_pos_pos) next
+    case False hence x:"x islimpt s" using assms(3)[unfolded closure_def] by auto
+    show ?thesis proof(cases "e=1")
+      case True obtain y where "y\<in>s" "y \<noteq> x" "dist y x < 1"
+	using x[unfolded islimpt_approachable,THEN spec[where x=1]] by auto
+      thus ?thesis apply(rule_tac x=y in bexI) unfolding True using `d>0` by auto next
+      case False hence "0 < e * d / (1 - e)" and *:"1 - e > 0"
+	using `e\<le>1` `e>0` `d>0` by(auto intro!:mult_pos_pos divide_pos_pos)
+      then obtain y where "y\<in>s" "y \<noteq> x" "dist y x < e * d / (1 - e)"
+	using x[unfolded islimpt_approachable,THEN spec[where x="e*d / (1 - e)"]] by auto
+      thus ?thesis apply(rule_tac x=y in bexI) unfolding dist_norm using pos_less_divide_eq[OF *] by auto qed qed
+  then obtain y where "y\<in>s" and y:"norm (y - x) * (1 - e) < e * d" by auto
+  def z \<equiv> "c + ((1 - e) / e) *s (x - y)"
+  have *:"x - e *s (x - c) = y - e *s (y - z)" unfolding z_def using `e>0` by auto
+  have "z\<in>interior s" apply(rule subset_interior[OF d,unfolded subset_eq,rule_format])
+    unfolding interior_open[OF open_ball] mem_ball z_def dist_norm using y and assms(4,5)
+    by(auto simp del:vector_ssub_ldistrib simp add:field_simps norm_minus_commute) 
+  thus ?thesis unfolding * apply - apply(rule mem_interior_convex_shrink) 
+    using assms(1,4-5) `y\<in>s` by auto qed
+
+subsection {* Some obvious but surprisingly hard simplex lemmas. *}
+
+lemma simplex:
+  assumes "finite s" "0 \<notin> s"
+  shows "convex hull (insert 0 s) =  { y. (\<exists>u. (\<forall>x\<in>s. 0 \<le> u x) \<and> setsum u s \<le> 1 \<and> setsum (\<lambda>x. u x *s x) s = y)}"
+  unfolding convex_hull_finite[OF finite.insertI[OF assms(1)]] apply(rule set_ext, rule) unfolding mem_Collect_eq
+  apply(erule_tac[!] exE) apply(erule_tac[!] conjE)+ unfolding setsum_clauses(2)[OF assms(1)]
+  apply(rule_tac x=u in exI) defer apply(rule_tac x="\<lambda>x. if x = 0 then 1 - setsum u s else u x" in exI) using assms(2)
+  unfolding if_smult and setsum_delta_notmem[OF assms(2)] by auto
+
+lemma std_simplex:
+  "convex hull (insert 0 { basis i | i. i\<in>UNIV}) =
+        {x::real^'n::finite . (\<forall>i. 0 \<le> x$i) \<and> setsum (\<lambda>i. x$i) UNIV \<le> 1 }" (is "convex hull (insert 0 ?p) = ?s")
+proof- let ?D = "UNIV::'n set"
+  have "0\<notin>?p" by(auto simp add: basis_nonzero)
+  have "{(basis i)::real^'n |i. i \<in> ?D} = basis ` ?D" by auto
+  note sumbas = this  setsum_reindex[OF basis_inj, unfolded o_def]
+  show ?thesis unfolding simplex[OF finite_stdbasis `0\<notin>?p`] apply(rule set_ext) unfolding mem_Collect_eq apply rule
+    apply(erule exE, (erule conjE)+) apply(erule_tac[2] conjE)+ proof-
+    fix x::"real^'n" and u assume as: "\<forall>x\<in>{basis i |i. i \<in>?D}. 0 \<le> u x" "setsum u {basis i |i. i \<in> ?D} \<le> 1" "(\<Sum>x\<in>{basis i |i. i \<in>?D}. u x *s x) = x"
+    have *:"\<forall>i. u (basis i) = x$i" using as(3) unfolding sumbas and basis_expansion_unique by auto
+    hence **:"setsum u {basis i |i. i \<in> ?D} = setsum (op $ x) ?D" unfolding sumbas by(rule_tac setsum_cong, auto)
+    show " (\<forall>i. 0 \<le> x $ i) \<and> setsum (op $ x) ?D \<le> 1" apply - proof(rule,rule)
+      fix i::'n show "0 \<le> x$i" unfolding *[rule_format,of i,THEN sym] apply(rule_tac as(1)[rule_format]) by auto
+    qed(insert as(2)[unfolded **], auto)
+  next fix x::"real^'n" assume as:"\<forall>i. 0 \<le> x $ i" "setsum (op $ x) ?D \<le> 1"
+    show "\<exists>u. (\<forall>x\<in>{basis i |i. i \<in> ?D}. 0 \<le> u x) \<and> setsum u {basis i |i. i \<in> ?D} \<le> 1 \<and> (\<Sum>x\<in>{basis i |i. i \<in> ?D}. u x *s x) = x"
+      apply(rule_tac x="\<lambda>y. y \<bullet> x" in exI) apply(rule,rule) unfolding mem_Collect_eq apply(erule exE) using as(1) apply(erule_tac x=i in allE) 
+      unfolding sumbas using as(2) and basis_expansion_unique by(auto simp add:dot_basis) qed qed 
+
+lemma interior_std_simplex:
+  "interior (convex hull (insert 0 { basis i| i. i\<in>UNIV})) =
+  {x::real^'n::finite. (\<forall>i. 0 < x$i) \<and> setsum (\<lambda>i. x$i) UNIV < 1 }"
+  apply(rule set_ext) unfolding mem_interior std_simplex unfolding subset_eq mem_Collect_eq Ball_def mem_ball
+  unfolding Ball_def[symmetric] apply rule apply(erule exE, (erule conjE)+) defer apply(erule conjE) proof-
+  fix x::"real^'n" and e assume "0<e" and as:"\<forall>xa. dist x xa < e \<longrightarrow> (\<forall>x. 0 \<le> xa $ x) \<and> setsum (op $ xa) UNIV \<le> 1"
+  show "(\<forall>xa. 0 < x $ xa) \<and> setsum (op $ x) UNIV < 1" apply(rule,rule) proof-
+    fix i::'n show "0 < x $ i" using as[THEN spec[where x="x - (e / 2) *s basis i"]] and `e>0`
+      unfolding dist_norm by(auto simp add: norm_basis vector_component_simps basis_component elim:allE[where x=i])
+  next guess a using UNIV_witness[where 'a='n] ..
+    have **:"dist x (x + (e / 2) *s basis a) < e" using  `e>0` and norm_basis[of a]
+      unfolding dist_norm by(auto simp add: vector_component_simps basis_component intro!: mult_strict_left_mono_comm)
+    have "\<And>i. (x + (e / 2) *s basis a) $ i = x$i + (if i = a then e/2 else 0)" by(auto simp add:vector_component_simps)
+    hence *:"setsum (op $ (x + (e / 2) *s basis a)) UNIV = setsum (\<lambda>i. x$i + (if a = i then e/2 else 0)) UNIV" by(rule_tac setsum_cong, auto) 
+    have "setsum (op $ x) UNIV < setsum (op $ (x + (e / 2) *s basis a)) UNIV" unfolding * setsum_addf
+      using `0<e` dimindex_ge_1 by(auto simp add: setsum_delta')
+    also have "\<dots> \<le> 1" using ** apply(drule_tac as[rule_format]) by auto
+    finally show "setsum (op $ x) UNIV < 1" by auto qed
+next
+  fix x::"real^'n::finite" assume as:"\<forall>i. 0 < x $ i" "setsum (op $ x) UNIV < 1"
+  guess a using UNIV_witness[where 'a='b] ..
+  let ?d = "(1 - setsum (op $ x) UNIV) / real (CARD('n))"
+  have "Min ((op $ x) ` UNIV) > 0" apply(rule Min_grI) using as(1) dimindex_ge_1 by auto
+  moreover have"?d > 0" apply(rule divide_pos_pos) using as(2) using dimindex_ge_1 by(auto simp add: Suc_le_eq)
+  ultimately show "\<exists>e>0. \<forall>y. dist x y < e \<longrightarrow> (\<forall>i. 0 \<le> y $ i) \<and> setsum (op $ y) UNIV \<le> 1"
+    apply(rule_tac x="min (Min ((op $ x) ` UNIV)) ?D" in exI) apply rule defer apply(rule,rule) proof-
+    fix y assume y:"dist x y < min (Min (op $ x ` UNIV)) ?d"
+    have "setsum (op $ y) UNIV \<le> setsum (\<lambda>i. x$i + ?d) UNIV" proof(rule setsum_mono)
+      fix i::'n have "abs (y$i - x$i) < ?d" apply(rule le_less_trans) using component_le_norm[of "y - x" i]
+	using y[unfolded min_less_iff_conj dist_norm, THEN conjunct2] by(auto simp add:vector_component_simps norm_minus_commute)
+      thus "y $ i \<le> x $ i + ?d" by auto qed
+    also have "\<dots> \<le> 1" unfolding setsum_addf setsum_constant card_enum real_eq_of_nat using dimindex_ge_1 by(auto simp add: Suc_le_eq)
+    finally show "(\<forall>i. 0 \<le> y $ i) \<and> setsum (op $ y) UNIV \<le> 1" apply- proof(rule,rule)
+      fix i::'n have "norm (x - y) < x$i" using y[unfolded min_less_iff_conj dist_norm, THEN conjunct1]
+	using Min_gr_iff[of "op $ x ` dimset x"] dimindex_ge_1 by auto
+      thus "0 \<le> y$i" using component_le_norm[of "x - y" i] and as(1)[rule_format, of i] by(auto simp add: vector_component_simps)
+    qed auto qed auto qed
+
+lemma interior_std_simplex_nonempty: obtains a::"real^'n::finite" where
+  "a \<in> interior(convex hull (insert 0 {basis i | i . i \<in> UNIV}))" proof-
+  let ?D = "UNIV::'n set" let ?a = "setsum (\<lambda>b. inverse (2 * real CARD('n)) *s b) {(basis i) | i. i \<in> ?D}"
+  have *:"{basis i | i. i \<in> ?D} = basis ` ?D" by auto
+  { fix i have "?a $ i = inverse (2 * real CARD('n))"
+    unfolding setsum_component vector_smult_component and * and setsum_reindex[OF basis_inj] and o_def
+    apply(rule trans[of _ "setsum (\<lambda>j. if i = j then inverse (2 * real CARD('n)) else 0) ?D"]) apply(rule setsum_cong2)
+      unfolding setsum_delta'[OF finite_UNIV[where 'a='n]] and real_dimindex_ge_1[where 'n='n] by(auto simp add: basis_component[of i]) }
+  note ** = this
+  show ?thesis apply(rule that[of ?a]) unfolding interior_std_simplex mem_Collect_eq proof(rule,rule)
+    fix i::'n show "0 < ?a $ i" unfolding ** using dimindex_ge_1 by(auto simp add: Suc_le_eq) next
+    have "setsum (op $ ?a) ?D = setsum (\<lambda>i. inverse (2 * real CARD('n))) ?D" by(rule setsum_cong2, rule **) 
+    also have "\<dots> < 1" unfolding setsum_constant card_enum real_eq_of_nat real_divide_def[THEN sym] by (auto simp add:field_simps)
+    finally show "setsum (op $ ?a) ?D < 1" by auto qed qed
+
+subsection {* Paths. *}
+
+definition "path (g::real^1 \<Rightarrow> real^'n::finite) \<longleftrightarrow> continuous_on {0 .. 1} g"
+
+definition "pathstart (g::real^1 \<Rightarrow> real^'n) = g 0"
+
+definition "pathfinish (g::real^1 \<Rightarrow> real^'n) = g 1"
+
+definition "path_image (g::real^1 \<Rightarrow> real^'n) = g ` {0 .. 1}"
+
+definition "reversepath (g::real^1 \<Rightarrow> real^'n) = (\<lambda>x. g(1 - x))"
+
+definition joinpaths:: "(real^1 \<Rightarrow> real^'n) \<Rightarrow> (real^1 \<Rightarrow> real^'n) \<Rightarrow> (real^1 \<Rightarrow> real^'n)" (infixr "+++" 75)
+  where "joinpaths g1 g2 = (\<lambda>x. if dest_vec1 x \<le> ((1 / 2)::real) then g1 (2 *s x) else g2(2 *s x - 1))"
+definition "simple_path (g::real^1 \<Rightarrow> real^'n) \<longleftrightarrow>
+  (\<forall>x\<in>{0..1}. \<forall>y\<in>{0..1}. g x = g y \<longrightarrow> x = y \<or> x = 0 \<and> y = 1 \<or> x = 1 \<and> y = 0)"
+
+definition "injective_path (g::real^1 \<Rightarrow> real^'n) \<longleftrightarrow>
+  (\<forall>x\<in>{0..1}. \<forall>y\<in>{0..1}. g x = g y \<longrightarrow> x = y)"
+
+subsection {* Some lemmas about these concepts. *}
+
+lemma injective_imp_simple_path:
+  "injective_path g \<Longrightarrow> simple_path g"
+  unfolding injective_path_def simple_path_def by auto
+
+lemma path_image_nonempty: "path_image g \<noteq> {}"
+  unfolding path_image_def image_is_empty interval_eq_empty by auto 
+
+lemma pathstart_in_path_image[intro]: "(pathstart g) \<in> path_image g"
+  unfolding pathstart_def path_image_def apply(rule imageI)
+  unfolding mem_interval_1 vec_1[THEN sym] dest_vec1_vec by auto
+
+lemma pathfinish_in_path_image[intro]: "(pathfinish g) \<in> path_image g"
+  unfolding pathfinish_def path_image_def apply(rule imageI)
+  unfolding mem_interval_1 vec_1[THEN sym] dest_vec1_vec by auto
+
+lemma connected_path_image[intro]: "path g \<Longrightarrow> connected(path_image g)"
+  unfolding path_def path_image_def apply(rule connected_continuous_image, assumption)
+  by(rule convex_connected, rule convex_interval)
+
+lemma compact_path_image[intro]: "path g \<Longrightarrow> compact(path_image g)"
+  unfolding path_def path_image_def apply(rule compact_continuous_image, assumption)
+  by(rule compact_interval)
+
+lemma reversepath_reversepath[simp]: "reversepath(reversepath g) = g"
+  unfolding reversepath_def by auto
+
+lemma pathstart_reversepath[simp]: "pathstart(reversepath g) = pathfinish g"
+  unfolding pathstart_def reversepath_def pathfinish_def by auto
+
+lemma pathfinish_reversepath[simp]: "pathfinish(reversepath g) = pathstart g"
+  unfolding pathstart_def reversepath_def pathfinish_def by auto
+
+lemma pathstart_join[simp]: "pathstart(g1 +++ g2) = pathstart g1"
+  unfolding pathstart_def joinpaths_def pathfinish_def by auto
+
+lemma pathfinish_join[simp]:"pathfinish(g1 +++ g2) = pathfinish g2" proof-
+  have "2 *s 1 - 1 = (1::real^1)" unfolding Cart_eq by(auto simp add:vector_component_simps)
+  thus ?thesis unfolding pathstart_def joinpaths_def pathfinish_def
+    unfolding vec_1[THEN sym] dest_vec1_vec by auto qed
+
+lemma path_image_reversepath[simp]: "path_image(reversepath g) = path_image g" proof-
+  have *:"\<And>g. path_image(reversepath g) \<subseteq> path_image g"
+    unfolding path_image_def subset_eq reversepath_def Ball_def image_iff apply(rule,rule,erule bexE)  
+    apply(rule_tac x="1 - xa" in bexI) by(auto simp add:vector_less_eq_def vector_component_simps elim!:ballE)
+  show ?thesis using *[of g] *[of "reversepath g"] unfolding reversepath_reversepath by auto qed
+
+lemma path_reversepath[simp]: "path(reversepath g) \<longleftrightarrow> path g" proof-
+  have *:"\<And>g. path g \<Longrightarrow> path(reversepath g)" unfolding path_def reversepath_def
+    apply(rule continuous_on_compose[unfolded o_def, of _ "\<lambda>x. 1 - x"])
+    apply(rule continuous_on_sub, rule continuous_on_const, rule continuous_on_id)
+    apply(rule continuous_on_subset[of "{0..1}"], assumption)
+    by (auto, auto simp add:vector_less_eq_def vector_component_simps elim!:ballE)
+  show ?thesis using *[of g] *[of "reversepath g"] unfolding reversepath_reversepath by auto qed
+
+lemmas reversepath_simps = path_reversepath path_image_reversepath pathstart_reversepath pathfinish_reversepath
+
+lemma path_join[simp]: assumes "pathfinish g1 = pathstart g2" shows "path (g1 +++ g2) \<longleftrightarrow>  path g1 \<and> path g2"
+  unfolding path_def pathfinish_def pathstart_def apply rule defer apply(erule conjE) proof-
+  assume as:"continuous_on {0..1} (g1 +++ g2)"
+  have *:"g1 = (\<lambda>x. g1 (2 *s x)) \<circ> (\<lambda>x. (1/2) *s x)" 
+         "g2 = (\<lambda>x. g2 (2 *s x - 1)) \<circ> (\<lambda>x. (1/2) *s (x + 1))" unfolding o_def by auto
+  have "op *s (1 / 2) ` {0::real^1..1} \<subseteq> {0..1}"  "(\<lambda>x. (1 / 2) *s (x + 1)) ` {(0::real^1)..1} \<subseteq> {0..1}"
+    unfolding image_smult_interval by (auto, auto simp add:vector_less_eq_def vector_component_simps elim!:ballE)
+  thus "continuous_on {0..1} g1 \<and> continuous_on {0..1} g2" apply -apply rule
+    apply(subst *) defer apply(subst *) apply (rule_tac[!] continuous_on_compose)
+    apply (rule continuous_on_cmul, rule continuous_on_add, rule continuous_on_id, rule continuous_on_const) defer
+    apply (rule continuous_on_cmul, rule continuous_on_id) apply(rule_tac[!] continuous_on_eq[of _ "g1 +++ g2"]) defer prefer 3
+    apply(rule_tac[1-2] continuous_on_subset[of "{0 .. 1}"]) apply(rule as, assumption, rule as, assumption)
+    apply(rule) defer apply rule proof-
+    fix x assume "x \<in> op *s (1 / 2) ` {0::real^1..1}"
+    hence "dest_vec1 x \<le> 1 / 2" unfolding image_iff by(auto simp add: vector_component_simps)
+    thus "(g1 +++ g2) x = g1 (2 *s x)" unfolding joinpaths_def by auto next
+    fix x assume "x \<in> (\<lambda>x. (1 / 2) *s (x + 1)) ` {0::real^1..1}"
+    hence "dest_vec1 x \<ge> 1 / 2" unfolding image_iff by(auto simp add: vector_component_simps)
+    thus "(g1 +++ g2) x = g2 (2 *s x - 1)" proof(cases "dest_vec1 x = 1 / 2")
+      case True hence "x = (1/2) *s 1" unfolding Cart_eq by(auto simp add: forall_1 vector_component_simps)
+      thus ?thesis unfolding joinpaths_def using assms[unfolded pathstart_def pathfinish_def] by auto
+    qed (auto simp add:le_less joinpaths_def) qed
+next assume as:"continuous_on {0..1} g1" "continuous_on {0..1} g2"
+  have *:"{0 .. 1::real^1} = {0.. (1/2)*s 1} \<union> {(1/2) *s 1 .. 1}" by(auto simp add: vector_component_simps) 
+  have **:"op *s 2 ` {0..(1 / 2) *s 1} = {0..1::real^1}" apply(rule set_ext, rule) unfolding image_iff 
+    defer apply(rule_tac x="(1/2)*s x" in bexI) by(auto simp add: vector_component_simps)
+  have ***:"(\<lambda>x. 2 *s x - 1) ` {(1 / 2) *s 1..1} = {0..1::real^1}"
+    unfolding image_affinity_interval[of _ "- 1", unfolded diff_def[symmetric]] and interval_eq_empty_1
+    by(auto simp add: vector_component_simps)
+  have ****:"\<And>x::real^1. x $ 1 * 2 = 1 \<longleftrightarrow> x = (1/2) *s 1" unfolding Cart_eq by(auto simp add: forall_1 vector_component_simps)
+  show "continuous_on {0..1} (g1 +++ g2)" unfolding * apply(rule continuous_on_union) apply(rule closed_interval)+ proof-
+    show "continuous_on {0..(1 / 2) *s 1} (g1 +++ g2)" apply(rule continuous_on_eq[of _ "\<lambda>x. g1 (2 *s x)"]) defer
+      unfolding o_def[THEN sym] apply(rule continuous_on_compose) apply(rule continuous_on_cmul, rule continuous_on_id)
+      unfolding ** apply(rule as(1)) unfolding joinpaths_def by(auto simp add: vector_component_simps) next
+    show "continuous_on {(1/2)*s1..1} (g1 +++ g2)" apply(rule continuous_on_eq[of _ "g2 \<circ> (\<lambda>x. 2 *s x - 1)"]) defer
+      apply(rule continuous_on_compose) apply(rule continuous_on_sub, rule continuous_on_cmul, rule continuous_on_id, rule continuous_on_const)
+      unfolding *** o_def joinpaths_def apply(rule as(2)) using assms[unfolded pathstart_def pathfinish_def]
+      by(auto simp add: vector_component_simps ****) qed qed
+
+lemma path_image_join_subset: "path_image(g1 +++ g2) \<subseteq> (path_image g1 \<union> path_image g2)" proof
+  fix x assume "x \<in> path_image (g1 +++ g2)"
+  then obtain y where y:"y\<in>{0..1}" "x = (if dest_vec1 y \<le> 1 / 2 then g1 (2 *s y) else g2 (2 *s y - 1))"
+    unfolding path_image_def image_iff joinpaths_def by auto
+  thus "x \<in> path_image g1 \<union> path_image g2" apply(cases "dest_vec1 y \<le> 1/2")
+    apply(rule_tac UnI1) defer apply(rule_tac UnI2) unfolding y(2) path_image_def using y(1)
+    by(auto intro!: imageI simp add: vector_component_simps) qed
+
+lemma subset_path_image_join:
+  assumes "path_image g1 \<subseteq> s" "path_image g2 \<subseteq> s" shows "path_image(g1 +++ g2) \<subseteq> s"
+  using path_image_join_subset[of g1 g2] and assms by auto
+
+lemma path_image_join:
+  assumes "path g1" "path g2" "pathfinish g1 = pathstart g2"
+  shows "path_image(g1 +++ g2) = (path_image g1) \<union> (path_image g2)"
+apply(rule, rule path_image_join_subset, rule) unfolding Un_iff proof(erule disjE)
+  fix x assume "x \<in> path_image g1"
+  then obtain y where y:"y\<in>{0..1}" "x = g1 y" unfolding path_image_def image_iff by auto
+  thus "x \<in> path_image (g1 +++ g2)" unfolding joinpaths_def path_image_def image_iff
+    apply(rule_tac x="(1/2) *s y" in bexI) by(auto simp add: vector_component_simps) next
+  fix x assume "x \<in> path_image g2"
+  then obtain y where y:"y\<in>{0..1}" "x = g2 y" unfolding path_image_def image_iff by auto
+  moreover have *:"y $ 1 = 0 \<Longrightarrow> y = 0" unfolding Cart_eq by auto
+  ultimately show "x \<in> path_image (g1 +++ g2)" unfolding joinpaths_def path_image_def image_iff
+    apply(rule_tac x="(1/2) *s (y + 1)" in bexI) using assms(3)[unfolded pathfinish_def pathstart_def]
+    by(auto simp add: vector_component_simps) qed 
+
+lemma not_in_path_image_join:
+  assumes "x \<notin> path_image g1" "x \<notin> path_image g2" shows "x \<notin> path_image(g1 +++ g2)"
+  using assms and path_image_join_subset[of g1 g2] by auto
+
+lemma simple_path_reversepath: assumes "simple_path g" shows "simple_path (reversepath g)"
+  using assms unfolding simple_path_def reversepath_def apply- apply(rule ballI)+
+  apply(erule_tac x="1-x" in ballE, erule_tac x="1-y" in ballE)
+  unfolding mem_interval_1 by(auto simp add:vector_component_simps)
+
+lemma simple_path_join_loop:
+  assumes "injective_path g1" "injective_path g2" "pathfinish g2 = pathstart g1"
+  "(path_image g1 \<inter> path_image g2) \<subseteq> {pathstart g1,pathstart g2}"
+  shows "simple_path(g1 +++ g2)"
+unfolding simple_path_def proof((rule ballI)+, rule impI) let ?g = "g1 +++ g2"
+  note inj = assms(1,2)[unfolded injective_path_def, rule_format]
+  fix x y::"real^1" assume xy:"x \<in> {0..1}" "y \<in> {0..1}" "?g x = ?g y"
+  show "x = y \<or> x = 0 \<and> y = 1 \<or> x = 1 \<and> y = 0" proof(case_tac "x$1 \<le> 1/2",case_tac[!] "y$1 \<le> 1/2", unfold not_le)
+    assume as:"x $ 1 \<le> 1 / 2" "y $ 1 \<le> 1 / 2"
+    hence "g1 (2 *s x) = g1 (2 *s y)" using xy(3) unfolding joinpaths_def dest_vec1_def by auto
+    moreover have "2 *s x \<in> {0..1}" "2 *s y \<in> {0..1}" using xy(1,2) as
+      unfolding mem_interval_1 dest_vec1_def by(auto simp add:vector_component_simps)
+    ultimately show ?thesis using inj(1)[of "2*s x" "2*s y"] by auto
+  next assume as:"x $ 1 > 1 / 2" "y $ 1 > 1 / 2"
+    hence "g2 (2 *s x - 1) = g2 (2 *s y - 1)" using xy(3) unfolding joinpaths_def dest_vec1_def by auto
+    moreover have "2 *s x - 1 \<in> {0..1}" "2 *s y - 1 \<in> {0..1}" using xy(1,2) as
+      unfolding mem_interval_1 dest_vec1_def by(auto simp add:vector_component_simps)
+    ultimately show ?thesis using inj(2)[of "2*s x - 1" "2*s y - 1"] by auto
+  next assume as:"x $ 1 \<le> 1 / 2" "y $ 1 > 1 / 2"
+    hence "?g x \<in> path_image g1" "?g y \<in> path_image g2" unfolding path_image_def joinpaths_def
+      using xy(1,2)[unfolded mem_interval_1] by(auto simp add:vector_component_simps intro!: imageI)
+    moreover have "?g y \<noteq> pathstart g2" using as(2) unfolding pathstart_def joinpaths_def
+      using inj(2)[of "2 *s y - 1" 0] and xy(2)[unfolded mem_interval_1]
+      apply(rule_tac ccontr) by(auto simp add:vector_component_simps field_simps Cart_eq)
+    ultimately have *:"?g x = pathstart g1" using assms(4) unfolding xy(3) by auto
+    hence "x = 0" unfolding pathstart_def joinpaths_def using as(1) and xy(1)[unfolded mem_interval_1]
+      using inj(1)[of "2 *s x" 0] by(auto simp add:vector_component_simps)
+    moreover have "y = 1" using * unfolding xy(3) assms(3)[THEN sym]
+      unfolding joinpaths_def pathfinish_def using as(2) and xy(2)[unfolded mem_interval_1]
+      using inj(2)[of "2 *s y - 1" 1] by (auto simp add:vector_component_simps Cart_eq)
+    ultimately show ?thesis by auto 
+  next assume as:"x $ 1 > 1 / 2" "y $ 1 \<le> 1 / 2"
+    hence "?g x \<in> path_image g2" "?g y \<in> path_image g1" unfolding path_image_def joinpaths_def
+      using xy(1,2)[unfolded mem_interval_1] by(auto simp add:vector_component_simps intro!: imageI)
+    moreover have "?g x \<noteq> pathstart g2" using as(1) unfolding pathstart_def joinpaths_def
+      using inj(2)[of "2 *s x - 1" 0] and xy(1)[unfolded mem_interval_1]
+      apply(rule_tac ccontr) by(auto simp add:vector_component_simps field_simps Cart_eq)
+    ultimately have *:"?g y = pathstart g1" using assms(4) unfolding xy(3) by auto
+    hence "y = 0" unfolding pathstart_def joinpaths_def using as(2) and xy(2)[unfolded mem_interval_1]
+      using inj(1)[of "2 *s y" 0] by(auto simp add:vector_component_simps)
+    moreover have "x = 1" using * unfolding xy(3)[THEN sym] assms(3)[THEN sym]
+      unfolding joinpaths_def pathfinish_def using as(1) and xy(1)[unfolded mem_interval_1]
+      using inj(2)[of "2 *s x - 1" 1] by(auto simp add:vector_component_simps Cart_eq)
+    ultimately show ?thesis by auto qed qed
+
+lemma injective_path_join:
+  assumes "injective_path g1" "injective_path g2" "pathfinish g1 = pathstart g2"
+  "(path_image g1 \<inter> path_image g2) \<subseteq> {pathstart g2}"
+  shows "injective_path(g1 +++ g2)"
+  unfolding injective_path_def proof(rule,rule,rule) let ?g = "g1 +++ g2"
+  note inj = assms(1,2)[unfolded injective_path_def, rule_format]
+  fix x y assume xy:"x \<in> {0..1}" "y \<in> {0..1}" "(g1 +++ g2) x = (g1 +++ g2) y"
+  show "x = y" proof(cases "x$1 \<le> 1/2", case_tac[!] "y$1 \<le> 1/2", unfold not_le)
+    assume "x $ 1 \<le> 1 / 2" "y $ 1 \<le> 1 / 2" thus ?thesis using inj(1)[of "2*s x" "2*s y"] and xy
+      unfolding mem_interval_1 joinpaths_def by(auto simp add:vector_component_simps)
+  next assume "x $ 1 > 1 / 2" "y $ 1 > 1 / 2" thus ?thesis using inj(2)[of "2*s x - 1" "2*s y - 1"] and xy
+      unfolding mem_interval_1 joinpaths_def by(auto simp add:vector_component_simps)
+  next assume as:"x $ 1 \<le> 1 / 2" "y $ 1 > 1 / 2" 
+    hence "?g x \<in> path_image g1" "?g y \<in> path_image g2" unfolding path_image_def joinpaths_def
+      using xy(1,2)[unfolded mem_interval_1] by(auto simp add:vector_component_simps intro!: imageI)
+    hence "?g x = pathfinish g1" "?g y = pathstart g2" using assms(4) unfolding assms(3) xy(3) by auto
+    thus ?thesis using as and inj(1)[of "2 *s x" 1] inj(2)[of "2 *s y - 1" 0] and xy(1,2)
+      unfolding pathstart_def pathfinish_def joinpaths_def mem_interval_1
+      by(auto simp add:vector_component_simps Cart_eq forall_1)
+  next assume as:"x $ 1 > 1 / 2" "y $ 1 \<le> 1 / 2" 
+    hence "?g x \<in> path_image g2" "?g y \<in> path_image g1" unfolding path_image_def joinpaths_def
+      using xy(1,2)[unfolded mem_interval_1] by(auto simp add:vector_component_simps intro!: imageI)
+    hence "?g x = pathstart g2" "?g y = pathfinish g1" using assms(4) unfolding assms(3) xy(3) by auto
+    thus ?thesis using as and inj(2)[of "2 *s x - 1" 0] inj(1)[of "2 *s y" 1] and xy(1,2)
+      unfolding pathstart_def pathfinish_def joinpaths_def mem_interval_1
+      by(auto simp add:vector_component_simps forall_1 Cart_eq) qed qed
+
+lemmas join_paths_simps = path_join path_image_join pathstart_join pathfinish_join
+ 
+subsection {* Reparametrizing a closed curve to start at some chosen point. *}
+
+definition "shiftpath a (f::real^1 \<Rightarrow> real^'n) =
+  (\<lambda>x. if dest_vec1 (a + x) \<le> 1 then f(a + x) else f(a + x - 1))"
+
+lemma pathstart_shiftpath: "a \<le> 1 \<Longrightarrow> pathstart(shiftpath a g) = g a"
+  unfolding pathstart_def shiftpath_def by auto
+
+(** move this **)
+declare forall_1[simp] ex_1[simp]
+
+lemma pathfinish_shiftpath: assumes "0 \<le> a" "pathfinish g = pathstart g"
+  shows "pathfinish(shiftpath a g) = g a"
+  using assms unfolding pathstart_def pathfinish_def shiftpath_def
+  by(auto simp add: vector_component_simps)
+
+lemma endpoints_shiftpath:
+  assumes "pathfinish g = pathstart g" "a \<in> {0 .. 1}" 
+  shows "pathfinish(shiftpath a g) = g a" "pathstart(shiftpath a g) = g a"
+  using assms by(auto intro!:pathfinish_shiftpath pathstart_shiftpath)
+
+lemma closed_shiftpath:
+  assumes "pathfinish g = pathstart g" "a \<in> {0..1}"
+  shows "pathfinish(shiftpath a g) = pathstart(shiftpath a g)"
+  using endpoints_shiftpath[OF assms] by auto
+
+lemma path_shiftpath:
+  assumes "path g" "pathfinish g = pathstart g" "a \<in> {0..1}"
+  shows "path(shiftpath a g)" proof-
+  have *:"{0 .. 1} = {0 .. 1-a} \<union> {1-a .. 1}" using assms(3) by(auto simp add: vector_component_simps)
+  have **:"\<And>x. x + a = 1 \<Longrightarrow> g (x + a - 1) = g (x + a)"
+    using assms(2)[unfolded pathfinish_def pathstart_def] by auto
+  show ?thesis unfolding path_def shiftpath_def * apply(rule continuous_on_union)
+    apply(rule closed_interval)+ apply(rule continuous_on_eq[of _ "g \<circ> (\<lambda>x. a + x)"]) prefer 3
+    apply(rule continuous_on_eq[of _ "g \<circ> (\<lambda>x. a - 1 + x)"]) defer prefer 3
+    apply(rule continuous_on_intros)+ prefer 2 apply(rule continuous_on_intros)+
+    apply(rule_tac[1-2] continuous_on_subset[OF assms(1)[unfolded path_def]])
+    using assms(3) and ** by(auto simp add:vector_component_simps field_simps Cart_eq) qed
+
+lemma shiftpath_shiftpath: assumes "pathfinish g = pathstart g" "a \<in> {0..1}" "x \<in> {0..1}" 
+  shows "shiftpath (1 - a) (shiftpath a g) x = g x"
+  using assms unfolding pathfinish_def pathstart_def shiftpath_def 
+  by(auto simp add: vector_component_simps)
+
+lemma path_image_shiftpath:
+  assumes "a \<in> {0..1}" "pathfinish g = pathstart g"
+  shows "path_image(shiftpath a g) = path_image g" proof-
+  { fix x assume as:"g 1 = g 0" "x \<in> {0..1::real^1}" " \<forall>y\<in>{0..1} \<inter> {x. \<not> a $ 1 + x $ 1 \<le> 1}. g x \<noteq> g (a + y - 1)" 
+    hence "\<exists>y\<in>{0..1} \<inter> {x. a $ 1 + x $ 1 \<le> 1}. g x = g (a + y)" proof(cases "a \<le> x")
+      case False thus ?thesis apply(rule_tac x="1 + x - a" in bexI)
+	using as(1,2) and as(3)[THEN bspec[where x="1 + x - a"]] and assms(1)
+	by(auto simp add:vector_component_simps field_simps atomize_not) next
+      case True thus ?thesis using as(1-2) and assms(1) apply(rule_tac x="x - a" in bexI)
+	by(auto simp add:vector_component_simps field_simps) qed }
+  thus ?thesis using assms unfolding shiftpath_def path_image_def pathfinish_def pathstart_def 
+    by(auto simp add:vector_component_simps image_iff) qed
+
+subsection {* Special case of straight-line paths. *}
+
+definition
+  linepath :: "real ^ 'n::finite \<Rightarrow> real ^ 'n \<Rightarrow> real ^ 1 \<Rightarrow> real ^ 'n" where
+  "linepath a b = (\<lambda>x. (1 - dest_vec1 x) *s a + dest_vec1 x *s b)"
+
+lemma pathstart_linepath[simp]: "pathstart(linepath a b) = a"
+  unfolding pathstart_def linepath_def by auto
+
+lemma pathfinish_linepath[simp]: "pathfinish(linepath a b) = b"
+  unfolding pathfinish_def linepath_def by auto
+
+lemma continuous_linepath_at[intro]: "continuous (at x) (linepath a b)"
+  unfolding linepath_def by(auto simp add: vec1_dest_vec1 o_def intro!: continuous_intros)
+
+lemma continuous_on_linepath[intro]: "continuous_on s (linepath a b)"
+  using continuous_linepath_at by(auto intro!: continuous_at_imp_continuous_on)
+
+lemma path_linepath[intro]: "path(linepath a b)"
+  unfolding path_def by(rule continuous_on_linepath)
+
+lemma path_image_linepath[simp]: "path_image(linepath a b) = (closed_segment a b)"
+  unfolding path_image_def segment linepath_def apply (rule set_ext, rule) defer
+  unfolding mem_Collect_eq image_iff apply(erule exE) apply(rule_tac x="u *s 1" in bexI)
+  by(auto simp add:vector_component_simps)
+
+lemma reversepath_linepath[simp]:  "reversepath(linepath a b) = linepath b a"
+  unfolding reversepath_def linepath_def by(rule ext, auto simp add:vector_component_simps)
+
+lemma injective_path_linepath: assumes "a \<noteq> b" shows "injective_path(linepath a b)" proof- 
+  { obtain i where i:"a$i \<noteq> b$i" using assms[unfolded Cart_eq] by auto
+    fix x y::"real^1" assume "x $ 1 *s b + y $ 1 *s a = x $ 1 *s a + y $ 1 *s b"
+    hence "x$1 * (b$i - a$i) = y$1 * (b$i - a$i)" unfolding Cart_eq by(auto simp add:field_simps vector_component_simps)
+    hence "x = y" unfolding mult_cancel_right Cart_eq using i(1) by(auto simp add:field_simps) }
+  thus ?thesis unfolding injective_path_def linepath_def by(auto simp add:vector_component_simps field_simps) qed
+
+lemma simple_path_linepath[intro]: "a \<noteq> b \<Longrightarrow> simple_path(linepath a b)" by(auto intro!: injective_imp_simple_path injective_path_linepath)
+
+subsection {* Bounding a point away from a path. *}
+
+lemma not_on_path_ball: assumes "path g" "z \<notin> path_image g"
+  shows "\<exists>e>0. ball z e \<inter> (path_image g) = {}" proof-
+  obtain a where "a\<in>path_image g" "\<forall>y\<in>path_image g. dist z a \<le> dist z y"
+    using distance_attains_inf[OF _ path_image_nonempty, of g z]
+    using compact_path_image[THEN compact_imp_closed, OF assms(1)] by auto
+  thus ?thesis apply(rule_tac x="dist z a" in exI) using assms(2) by(auto intro!: dist_pos_lt) qed
+
+lemma not_on_path_cball: assumes "path g" "z \<notin> path_image g"
+  shows "\<exists>e>0. cball z e \<inter> (path_image g) = {}" proof-
+  obtain e where "ball z e \<inter> path_image g = {}" "e>0" using not_on_path_ball[OF assms] by auto
+  moreover have "cball z (e/2) \<subseteq> ball z e" using `e>0` by auto
+  ultimately show ?thesis apply(rule_tac x="e/2" in exI) by auto qed
+
+subsection {* Path component, considered as a "joinability" relation (from Tom Hales). *}
+
+definition "path_component s x y \<longleftrightarrow> (\<exists>g. path g \<and> path_image g \<subseteq> s \<and> pathstart g = x \<and> pathfinish g = y)"
+
+lemmas path_defs = path_def pathstart_def pathfinish_def path_image_def path_component_def 
+
+lemma path_component_mem: assumes "path_component s x y" shows "x \<in> s" "y \<in> s"
+  using assms unfolding path_defs by auto
+
+lemma path_component_refl: assumes "x \<in> s" shows "path_component s x x"
+  unfolding path_defs apply(rule_tac x="\<lambda>u. x" in exI) using assms 
+  by(auto intro!:continuous_on_intros)    
+
+lemma path_component_refl_eq: "path_component s x x \<longleftrightarrow> x \<in> s"
+  by(auto intro!: path_component_mem path_component_refl) 
+
+lemma path_component_sym: "path_component s x y \<Longrightarrow> path_component s y x"
+  using assms unfolding path_component_def apply(erule exE) apply(rule_tac x="reversepath g" in exI) 
+  by(auto simp add: reversepath_simps)
+
+lemma path_component_trans: assumes "path_component s x y" "path_component s y z" shows "path_component s x z"
+  using assms unfolding path_component_def apply- apply(erule exE)+ apply(rule_tac x="g +++ ga" in exI) by(auto simp add: path_image_join)
+
+lemma path_component_of_subset: "s \<subseteq> t \<Longrightarrow>  path_component s x y \<Longrightarrow> path_component t x y"
+  unfolding path_component_def by auto
+
+subsection {* Can also consider it as a set, as the name suggests. *}
+
+lemma path_component_set: "path_component s x = { y. (\<exists>g. path g \<and> path_image g \<subseteq> s \<and> pathstart g = x \<and> pathfinish g = y )}"
+  apply(rule set_ext) unfolding mem_Collect_eq unfolding mem_def path_component_def by auto
+
+lemma mem_path_component_set:"x \<in> path_component s y \<longleftrightarrow> path_component s y x" unfolding mem_def by auto
+
+lemma path_component_subset: "(path_component s x) \<subseteq> s"
+  apply(rule, rule path_component_mem(2)) by(auto simp add:mem_def)
+
+lemma path_component_eq_empty: "path_component s x = {} \<longleftrightarrow> x \<notin> s"
+  apply rule apply(drule equals0D[of _ x]) defer apply(rule equals0I) unfolding mem_path_component_set
+  apply(drule path_component_mem(1)) using path_component_refl by auto
+
+subsection {* Path connectedness of a space. *}
+
+definition "path_connected s \<longleftrightarrow> (\<forall>x\<in>s. \<forall>y\<in>s. \<exists>g. path g \<and> (path_image g) \<subseteq> s \<and> pathstart g = x \<and> pathfinish g = y)"
+
+lemma path_connected_component: "path_connected s \<longleftrightarrow> (\<forall>x\<in>s. \<forall>y\<in>s. path_component s x y)"
+  unfolding path_connected_def path_component_def by auto
+
+lemma path_connected_component_set: "path_connected s \<longleftrightarrow> (\<forall>x\<in>s. path_component s x = s)" 
+  unfolding path_connected_component apply(rule, rule, rule, rule path_component_subset) 
+  unfolding subset_eq mem_path_component_set Ball_def mem_def by auto
+
+subsection {* Some useful lemmas about path-connectedness. *}
+
+lemma convex_imp_path_connected: assumes "convex s" shows "path_connected s"
+  unfolding path_connected_def apply(rule,rule,rule_tac x="linepath x y" in exI)
+  unfolding path_image_linepath using assms[unfolded convex_contains_segment] by auto
+
+lemma path_connected_imp_connected: assumes "path_connected s" shows "connected s"
+  unfolding connected_def not_ex apply(rule,rule,rule ccontr) unfolding not_not apply(erule conjE)+ proof-
+  fix e1 e2 assume as:"open e1" "open e2" "s \<subseteq> e1 \<union> e2" "e1 \<inter> e2 \<inter> s = {}" "e1 \<inter> s \<noteq> {}" "e2 \<inter> s \<noteq> {}"
+  then obtain x1 x2 where obt:"x1\<in>e1\<inter>s" "x2\<in>e2\<inter>s" by auto
+  then obtain g where g:"path g" "path_image g \<subseteq> s" "pathstart g = x1" "pathfinish g = x2"
+    using assms[unfolded path_connected_def,rule_format,of x1 x2] by auto
+  have *:"connected {0..1::real^1}" by(auto intro!: convex_connected convex_interval)
+  have "{0..1} \<subseteq> {x \<in> {0..1}. g x \<in> e1} \<union> {x \<in> {0..1}. g x \<in> e2}" using as(3) g(2)[unfolded path_defs] by blast
+  moreover have "{x \<in> {0..1}. g x \<in> e1} \<inter> {x \<in> {0..1}. g x \<in> e2} = {}" using as(4) g(2)[unfolded path_defs] unfolding subset_eq by auto 
+  moreover have "{x \<in> {0..1}. g x \<in> e1} \<noteq> {} \<and> {x \<in> {0..1}. g x \<in> e2} \<noteq> {}" using g(3,4)[unfolded path_defs] using obt by(auto intro!: exI)
+  ultimately show False using *[unfolded connected_local not_ex,rule_format, of "{x\<in>{0..1}. g x \<in> e1}" "{x\<in>{0..1}. g x \<in> e2}"]
+    using continuous_open_in_preimage[OF g(1)[unfolded path_def] as(1)]
+    using continuous_open_in_preimage[OF g(1)[unfolded path_def] as(2)] by auto qed
+
+lemma open_path_component: assumes "open s" shows "open(path_component s x)"
+  unfolding open_contains_ball proof
+  fix y assume as:"y \<in> path_component s x"
+  hence "y\<in>s" apply- apply(rule path_component_mem(2)) unfolding mem_def by auto
+  then obtain e where e:"e>0" "ball y e \<subseteq> s" using assms[unfolded open_contains_ball] by auto
+  show "\<exists>e>0. ball y e \<subseteq> path_component s x" apply(rule_tac x=e in exI) apply(rule,rule `e>0`,rule) unfolding mem_ball mem_path_component_set proof-
+    fix z assume "dist y z < e" thus "path_component s x z" apply(rule_tac path_component_trans[of _ _ y]) defer 
+      apply(rule path_component_of_subset[OF e(2)]) apply(rule convex_imp_path_connected[OF convex_ball, unfolded path_connected_component, rule_format]) using `e>0`
+      using as[unfolded mem_def] by auto qed qed
+
+lemma open_non_path_component: assumes "open s" shows "open(s - path_component s x)" unfolding open_contains_ball proof
+  fix y assume as:"y\<in>s - path_component s x" 
+  then obtain e where e:"e>0" "ball y e \<subseteq> s" using assms[unfolded open_contains_ball] by auto
+  show "\<exists>e>0. ball y e \<subseteq> s - path_component s x" apply(rule_tac x=e in exI) apply(rule,rule `e>0`,rule,rule) defer proof(rule ccontr)
+    fix z assume "z\<in>ball y e" "\<not> z \<notin> path_component s x" 
+    hence "y \<in> path_component s x" unfolding not_not mem_path_component_set using `e>0` 
+      apply- apply(rule path_component_trans,assumption) apply(rule path_component_of_subset[OF e(2)])
+      apply(rule convex_imp_path_connected[OF convex_ball, unfolded path_connected_component, rule_format]) by auto
+    thus False using as by auto qed(insert e(2), auto) qed
+
+lemma connected_open_path_connected: assumes "open s" "connected s" shows "path_connected s"
+  unfolding path_connected_component_set proof(rule,rule,rule path_component_subset, rule)
+  fix x y assume "x \<in> s" "y \<in> s" show "y \<in> path_component s x" proof(rule ccontr)
+    assume "y \<notin> path_component s x" moreover
+    have "path_component s x \<inter> s \<noteq> {}" using `x\<in>s` path_component_eq_empty path_component_subset[of s x] by auto
+    ultimately show False using `y\<in>s` open_non_path_component[OF assms(1)] open_path_component[OF assms(1)]
+    using assms(2)[unfolded connected_def not_ex, rule_format, of"path_component s x" "s - path_component s x"] by auto
+qed qed
+
+lemma path_connected_continuous_image:
+  assumes "continuous_on s f" "path_connected s" shows "path_connected (f ` s)"
+  unfolding path_connected_def proof(rule,rule)
+  fix x' y' assume "x' \<in> f ` s" "y' \<in> f ` s"
+  then obtain x y where xy:"x\<in>s" "y\<in>s" "x' = f x" "y' = f y" by auto
+  guess g using assms(2)[unfolded path_connected_def,rule_format,OF xy(1,2)] ..
+  thus "\<exists>g. path g \<and> path_image g \<subseteq> f ` s \<and> pathstart g = x' \<and> pathfinish g = y'"
+    unfolding xy apply(rule_tac x="f \<circ> g" in exI) unfolding path_defs
+    using assms(1) by(auto intro!: continuous_on_compose continuous_on_subset[of _ _ "g ` {0..1}"]) qed
+
+lemma homeomorphic_path_connectedness:
+  "s homeomorphic t \<Longrightarrow> (path_connected s \<longleftrightarrow> path_connected t)"
+  unfolding homeomorphic_def homeomorphism_def apply(erule exE|erule conjE)+ apply rule
+  apply(drule_tac f=f in path_connected_continuous_image) prefer 3
+  apply(drule_tac f=g in path_connected_continuous_image) by auto
+
+lemma path_connected_empty: "path_connected {}"
+  unfolding path_connected_def by auto
+
+lemma path_connected_singleton: "path_connected {a}"
+  unfolding path_connected_def apply(rule,rule)
+  apply(rule_tac x="linepath a a" in exI) by(auto simp add:segment)
+
+lemma path_connected_Un: assumes "path_connected s" "path_connected t" "s \<inter> t \<noteq> {}"
+  shows "path_connected (s \<union> t)" unfolding path_connected_component proof(rule,rule)
+  fix x y assume as:"x \<in> s \<union> t" "y \<in> s \<union> t" 
+  from assms(3) obtain z where "z \<in> s \<inter> t" by auto
+  thus "path_component (s \<union> t) x y" using as using assms(1-2)[unfolded path_connected_component] apply- 
+    apply(erule_tac[!] UnE)+ apply(rule_tac[2-3] path_component_trans[of _ _ z])
+    by(auto simp add:path_component_of_subset [OF Un_upper1] path_component_of_subset[OF Un_upper2]) qed
+
+subsection {* sphere is path-connected. *}
+
+lemma path_connected_punctured_universe:
+ assumes "2 \<le> CARD('n::finite)" shows "path_connected((UNIV::(real^'n::finite) set) - {a})" proof-
+  obtain \<psi> where \<psi>:"bij_betw \<psi> {1..CARD('n)} (UNIV::'n set)" using ex_bij_betw_nat_finite_1[OF finite_UNIV] by auto
+  let ?U = "UNIV::(real^'n) set" let ?u = "?U - {0}"
+  let ?basis = "\<lambda>k. basis (\<psi> k)"
+  let ?A = "\<lambda>k. {x::real^'n. \<exists>i\<in>{1..k}. (basis (\<psi> i)) \<bullet> x \<noteq> 0}"
+  have "\<forall>k\<in>{2..CARD('n)}. path_connected (?A k)" proof
+    have *:"\<And>k. ?A (Suc k) = {x. ?basis (Suc k) \<bullet> x < 0} \<union> {x. ?basis (Suc k) \<bullet> x > 0} \<union> ?A k" apply(rule set_ext,rule) defer
+      apply(erule UnE)+  unfolding mem_Collect_eq apply(rule_tac[1-2] x="Suc k" in bexI)
+      by(auto elim!: ballE simp add: not_less le_Suc_eq)
+    fix k assume "k \<in> {2..CARD('n)}" thus "path_connected (?A k)" proof(induct k)
+      case (Suc k) show ?case proof(cases "k = 1")
+	case False from Suc have d:"k \<in> {1..CARD('n)}" "Suc k \<in> {1..CARD('n)}" by auto
+	hence "\<psi> k \<noteq> \<psi> (Suc k)" using \<psi>[unfolded bij_betw_def inj_on_def, THEN conjunct1, THEN bspec[where x=k]] by auto
+	hence **:"?basis k + ?basis (Suc k) \<in> {x. 0 < ?basis (Suc k) \<bullet> x} \<inter> (?A k)" 
+          "?basis k - ?basis (Suc k) \<in> {x. 0 > ?basis (Suc k) \<bullet> x} \<inter> ({x. 0 < ?basis (Suc k) \<bullet> x} \<union> (?A k))" using d
+	  by(auto simp add: dot_basis vector_component_simps intro!:bexI[where x=k])
+	show ?thesis unfolding * Un_assoc apply(rule path_connected_Un) defer apply(rule path_connected_Un) 
+	  prefer 5 apply(rule_tac[1-2] convex_imp_path_connected, rule convex_halfspace_lt, rule convex_halfspace_gt)
+	  apply(rule Suc(1)) apply(rule_tac[2-3] ccontr) using d ** False by auto
+      next case True hence d:"1\<in>{1..CARD('n)}" "2\<in>{1..CARD('n)}" using Suc(2) by auto
+	have ***:"Suc 1 = 2" by auto
+	have **:"\<And>s t P Q. s \<union> t \<union> {x. P x \<or> Q x} = (s \<union> {x. P x}) \<union> (t \<union> {x. Q x})" by auto
+	have "\<psi> 2 \<noteq> \<psi> (Suc 0)" apply(rule ccontr) using \<psi>[unfolded bij_betw_def inj_on_def, THEN conjunct1, THEN bspec[where x=2]] using assms by auto
+	thus ?thesis unfolding * True unfolding ** neq_iff bex_disj_distrib apply -
+	  apply(rule path_connected_Un, rule_tac[1-2] path_connected_Un) defer 3 apply(rule_tac[1-4] convex_imp_path_connected) 
+	  apply(rule_tac[5] x=" ?basis 1 + ?basis 2" in nequals0I)
+	  apply(rule_tac[6] x="-?basis 1 + ?basis 2" in nequals0I)
+	  apply(rule_tac[7] x="-?basis 1 - ?basis 2" in nequals0I)
+	  using d unfolding *** by(auto intro!: convex_halfspace_gt convex_halfspace_lt, auto simp add:vector_component_simps dot_basis)
+  qed qed auto qed note lem = this
+
+  have ***:"\<And>x::real^'n. (\<exists>i\<in>{1..CARD('n)}. basis (\<psi> i) \<bullet> x \<noteq> 0) \<longleftrightarrow> (\<exists>i. basis i \<bullet> x \<noteq> 0)"
+    apply rule apply(erule bexE) apply(rule_tac x="\<psi> i" in exI) defer apply(erule exE) proof- 
+    fix x::"real^'n" and i assume as:"basis i \<bullet> x \<noteq> 0"
+    have "i\<in>\<psi> ` {1..CARD('n)}" using \<psi>[unfolded bij_betw_def, THEN conjunct2] by auto
+    then obtain j where "j\<in>{1..CARD('n)}" "\<psi> j = i" by auto
+    thus "\<exists>i\<in>{1..CARD('n)}. basis (\<psi> i) \<bullet> x \<noteq> 0" apply(rule_tac x=j in bexI) using as by auto qed auto
+  have *:"?U - {a} = (\<lambda>x. x + a) ` {x. x \<noteq> 0}" apply(rule set_ext) unfolding image_iff 
+    apply rule apply(rule_tac x="x - a" in bexI) by auto
+  have **:"\<And>x::real^'n. x\<noteq>0 \<longleftrightarrow> (\<exists>i. basis i \<bullet> x \<noteq> 0)" unfolding Cart_eq by(auto simp add: dot_basis)
+  show ?thesis unfolding * apply(rule path_connected_continuous_image) apply(rule continuous_on_intros)+ 
+    unfolding ** apply(rule lem[THEN bspec[where x="CARD('n)"], unfolded ***]) using assms by auto qed
+
+lemma path_connected_sphere: assumes "2 \<le> CARD('n::finite)" shows "path_connected {x::real^'n::finite. norm(x - a) = r}" proof(cases "r\<le>0")
+  case True thus ?thesis proof(cases "r=0") 
+    case False hence "{x::real^'n. norm(x - a) = r} = {}" using True by auto
+    thus ?thesis using path_connected_empty by auto
+  qed(auto intro!:path_connected_singleton) next
+  case False hence *:"{x::real^'n. norm(x - a) = r} = (\<lambda>x. a + r *s x) ` {x. norm x = 1}" unfolding not_le apply -apply(rule set_ext,rule)
+    unfolding image_iff apply(rule_tac x="(1/r) *s (x - a)" in bexI) unfolding mem_Collect_eq norm_mul by auto
+  have ***:"\<And>xa. (if xa = 0 then 0 else 1) \<noteq> 1 \<Longrightarrow> xa = 0" apply(rule ccontr) by auto
+  have **:"{x::real^'n. norm x = 1} = (\<lambda>x. (1/norm x) *s x) ` (UNIV - {0})" apply(rule set_ext,rule)
+    unfolding image_iff apply(rule_tac x=x in bexI) unfolding mem_Collect_eq norm_mul by(auto intro!: ***) 
+  have "continuous_on (UNIV - {0}) (vec1 \<circ> (\<lambda>x::real^'n. 1 / norm x))" unfolding o_def continuous_on_eq_continuous_within
+    apply(rule, rule continuous_at_within_inv[unfolded o_def inverse_eq_divide]) apply(rule continuous_at_within)
+    apply(rule continuous_at_vec1_norm[unfolded o_def]) by auto
+  thus ?thesis unfolding * ** using path_connected_punctured_universe[OF assms]
+    by(auto intro!: path_connected_continuous_image continuous_on_intros continuous_on_mul) qed
+
+lemma connected_sphere: "2 \<le> CARD('n) \<Longrightarrow> connected {x::real^'n::finite. norm(x - a) = r}"
+  using path_connected_sphere path_connected_imp_connected by auto
+ 
+(** In continuous_at_vec1_norm : Use \<And> instead of \<forall>. **)
+
+end
--- a/src/HOL/Library/Determinants.thy	Mon Jun 01 09:26:28 2009 +0200
+++ b/src/HOL/Library/Determinants.thy	Tue Jun 02 12:18:08 2009 +0200
@@ -733,7 +733,7 @@
       apply simp
       done
     from c ci
-    have thr0: "- row i A = setsum (\<lambda>j. (1/ c i) *s c j *s row j A) (?U - {i})"
+    have thr0: "- row i A = setsum (\<lambda>j. (1/ c i) *s (c j *s row j A)) (?U - {i})"
       unfolding setsum_diff1'[OF fU iU] setsum_cmul
       apply -
       apply (rule vector_mul_lcancel_imp[OF ci])
@@ -923,10 +923,10 @@
   shows "linear f"
 proof-
   {fix v w
-    {fix x note fd[rule_format, of x 0, unfolded dist_def f0 diff_0_right] }
+    {fix x note fd[rule_format, of x 0, unfolded dist_norm f0 diff_0_right] }
     note th0 = this
     have "f v \<bullet> f w = c^2 * (v \<bullet> w)"
-      unfolding dot_norm_neg dist_def[symmetric]
+      unfolding dot_norm_neg dist_norm[symmetric]
       unfolding th0 fd[rule_format] by (simp add: power2_eq_square field_simps)}
   note fc = this
   show ?thesis unfolding linear_def vector_eq
@@ -947,7 +947,7 @@
   unfolding orthogonal_transformation
   apply (rule iffI)
   apply clarify
-  apply (clarsimp simp add: linear_0 linear_sub[symmetric] dist_def)
+  apply (clarsimp simp add: linear_0 linear_sub[symmetric] dist_norm)
   apply (rule conjI)
   apply (rule isometry_linear)
   apply simp
@@ -955,7 +955,7 @@
   apply clarify
   apply (erule_tac x=v in allE)
   apply (erule_tac x=0 in allE)
-  by (simp add: dist_def)
+  by (simp add: dist_norm)
 
 (* ------------------------------------------------------------------------- *)
 (* Can extend an isometry from unit sphere.                                  *)
@@ -995,18 +995,18 @@
     moreover
     {assume "x = 0" "y \<noteq> 0"
       then have "dist (?g x) (?g y) = dist x y"
-	apply (simp add: dist_def norm_mul)
+	apply (simp add: dist_norm norm_mul)
 	apply (rule f1[rule_format])
 	by(simp add: norm_mul field_simps)}
     moreover
     {assume "x \<noteq> 0" "y = 0"
       then have "dist (?g x) (?g y) = dist x y"
-	apply (simp add: dist_def norm_mul)
+	apply (simp add: dist_norm norm_mul)
 	apply (rule f1[rule_format])
 	by(simp add: norm_mul field_simps)}
     moreover
     {assume z: "x \<noteq> 0" "y \<noteq> 0"
-      have th00: "x = norm x *s inverse (norm x) *s x" "y = norm y *s inverse (norm y) *s y" "norm x *s f (inverse (norm x) *s x) = norm x *s f (inverse (norm x) *s x)"
+      have th00: "x = norm x *s (inverse (norm x) *s x)" "y = norm y *s (inverse (norm y) *s y)" "norm x *s f ((inverse (norm x) *s x)) = norm x *s f (inverse (norm x) *s x)"
 	"norm y *s f (inverse (norm y) *s y) = norm y *s f (inverse (norm y) *s y)"
 	"norm (inverse (norm x) *s x) = 1"
 	"norm (f (inverse (norm x) *s x)) = 1"
@@ -1015,9 +1015,9 @@
 	"norm (f (inverse (norm x) *s x) - f (inverse (norm y) *s y)) =
 	norm (inverse (norm x) *s x - inverse (norm y) *s y)"
 	using z
-	by (auto simp add: vector_smult_assoc field_simps norm_mul intro: f1[rule_format] fd1[rule_format, unfolded dist_def])
+	by (auto simp add: vector_smult_assoc field_simps norm_mul intro: f1[rule_format] fd1[rule_format, unfolded dist_norm])
       from z th0[OF th00] have "dist (?g x) (?g y) = dist x y"
-	by (simp add: dist_def)}
+	by (simp add: dist_norm)}
     ultimately have "dist (?g x) (?g y) = dist x y" by blast}
   note thd = this
     show ?thesis
--- a/src/HOL/Library/Efficient_Nat.thy	Mon Jun 01 09:26:28 2009 +0200
+++ b/src/HOL/Library/Efficient_Nat.thy	Tue Jun 02 12:18:08 2009 +0200
@@ -317,7 +317,7 @@
 
 setup {*
   fold (Numeral.add_code @{const_name number_nat_inst.number_of_nat}
-    true false) ["SML", "OCaml", "Haskell"]
+    false true) ["SML", "OCaml", "Haskell"]
 *}
 
 text {*
--- a/src/HOL/Library/Euclidean_Space.thy	Mon Jun 01 09:26:28 2009 +0200
+++ b/src/HOL/Library/Euclidean_Space.thy	Tue Jun 02 12:18:08 2009 +0200
@@ -109,10 +109,10 @@
 
 text{* Also the scalar-vector multiplication. *}
 
-definition vector_scalar_mult:: "'a::times \<Rightarrow> 'a ^'n \<Rightarrow> 'a ^ 'n" (infixr "*s" 75)
+definition vector_scalar_mult:: "'a::times \<Rightarrow> 'a ^'n \<Rightarrow> 'a ^ 'n" (infixl "*s" 70)
   where "c *s x = (\<chi> i. c * (x$i))"
 
-text{* Constant Vectors *}
+text{* Constant Vectors *} 
 
 definition "vec x = (\<chi> i. x)"
 
@@ -498,6 +498,30 @@
   apply simp
   done
 
+subsection {* Metric *}
+
+instantiation "^" :: (metric_space, finite) metric_space
+begin
+
+definition dist_vector_def:
+  "dist (x::'a^'b) (y::'a^'b) = setL2 (\<lambda>i. dist (x$i) (y$i)) UNIV"
+
+instance proof
+  fix x y :: "'a ^ 'b"
+  show "dist x y = 0 \<longleftrightarrow> x = y"
+    unfolding dist_vector_def
+    by (simp add: setL2_eq_0_iff Cart_eq)
+next
+  fix x y z :: "'a ^ 'b"
+  show "dist x y \<le> dist x z + dist y z"
+    unfolding dist_vector_def
+    apply (rule order_trans [OF _ setL2_triangle_ineq])
+    apply (simp add: setL2_mono dist_triangle2)
+    done
+qed
+
+end
+
 subsection {* Norms *}
 
 instantiation "^" :: (real_normed_vector, finite) real_normed_vector
@@ -527,6 +551,9 @@
     by (simp add: norm_scaleR setL2_right_distrib)
   show "sgn x = scaleR (inverse (norm x)) x"
     by (rule vector_sgn_def)
+  show "dist x y = norm (x - y)"
+    unfolding dist_vector_def vector_norm_def
+    by (simp add: dist_norm)
 qed
 
 end
@@ -620,14 +647,8 @@
 lemma norm_real: "norm(x::real ^ 1) = abs(x$1)"
   by (simp add: norm_vector_1)
 
-text{* Metric *}
-
-text {* FIXME: generalize to arbitrary @{text real_normed_vector} types *}
-definition dist:: "real ^ 'n::finite \<Rightarrow> real ^ 'n \<Rightarrow> real" where
-  "dist x y = norm (x - y)"
-
 lemma dist_real: "dist(x::real ^ 1) y = abs((x$1) - (y$1))"
-  by (auto simp add: norm_real dist_def)
+  by (auto simp add: norm_real dist_norm)
 
 subsection {* A connectedness or intermediate value lemma with several applications. *}
 
@@ -698,7 +719,7 @@
 qed
 
 lemma square_continuous: "0 < (e::real) ==> \<exists>d. 0 < d \<and> (\<forall>y. abs(y - x) < d \<longrightarrow> abs(y * y - x * x) < e)"
-  using isCont_power[OF isCont_ident, of 2, unfolded isCont_def LIM_def, rule_format, of e x] apply (auto simp add: power2_eq_square)
+  using isCont_power[OF isCont_ident, of 2, unfolded isCont_def LIM_eq, rule_format, of e x] apply (auto simp add: power2_eq_square)
   apply (rule_tac x="s" in exI)
   apply auto
   apply (erule_tac x=y in allE)
@@ -950,6 +971,11 @@
   "x \<noteq> y \<longleftrightarrow> \<not> (norm (x - y) \<le> 0)"
   using norm_ge_zero[of "x - y"] by auto
 
+lemma vector_dist_norm:
+  fixes x y :: "real ^ _"
+  shows "dist x y = norm (x - y)"
+  by (rule dist_norm)
+
 use "normarith.ML"
 
 method_setup norm = {* Scan.succeed (SIMPLE_METHOD' o NormArith.norm_arith_tac)
@@ -959,38 +985,53 @@
 
 text{* Hence more metric properties. *}
 
-lemma dist_refl[simp]: "dist x x = 0" by norm
-
-lemma dist_sym: "dist x y = dist y x"by norm
-
-lemma dist_pos_le[simp]: "0 <= dist x y" by norm
-
-lemma dist_triangle: "dist x z <= dist x y + dist y z" by norm
-
-lemma dist_triangle_alt: "dist y z <= dist x y + dist x z" by norm
-
-lemma dist_eq_0[simp]: "dist x y = 0 \<longleftrightarrow> x = y" by norm
-
-lemma dist_pos_lt: "x \<noteq> y ==> 0 < dist x y" by norm
-lemma dist_nz:  "x \<noteq> y \<longleftrightarrow> 0 < dist x y" by norm
-
-lemma dist_triangle_le: "dist x z + dist y z <= e \<Longrightarrow> dist x y <= e" by norm
-
-lemma dist_triangle_lt: "dist x z + dist y z < e ==> dist x y < e" by norm
-
-lemma dist_triangle_half_l: "dist x1 y < e / 2 \<Longrightarrow> dist x2 y < e / 2 ==> dist x1 x2 < e" by norm
-
-lemma dist_triangle_half_r: "dist y x1 < e / 2 \<Longrightarrow> dist y x2 < e / 2 ==> dist x1 x2 < e" by norm
-
-lemma dist_triangle_add: "dist (x + y) (x' + y') <= dist x x' + dist y y'"
-  by norm
+lemma dist_triangle_alt:
+  fixes x y z :: "'a::metric_space"
+  shows "dist y z <= dist x y + dist x z"
+using dist_triangle [of y z x] by (simp add: dist_commute)
+
+lemma dist_pos_lt:
+  fixes x y :: "'a::metric_space"
+  shows "x \<noteq> y ==> 0 < dist x y"
+by (simp add: zero_less_dist_iff)
+
+lemma dist_nz:
+  fixes x y :: "'a::metric_space"
+  shows "x \<noteq> y \<longleftrightarrow> 0 < dist x y"
+by (simp add: zero_less_dist_iff)
+
+lemma dist_triangle_le:
+  fixes x y z :: "'a::metric_space"
+  shows "dist x z + dist y z <= e \<Longrightarrow> dist x y <= e"
+by (rule order_trans [OF dist_triangle2])
+
+lemma dist_triangle_lt:
+  fixes x y z :: "'a::metric_space"
+  shows "dist x z + dist y z < e ==> dist x y < e"
+by (rule le_less_trans [OF dist_triangle2])
+
+lemma dist_triangle_half_l:
+  fixes x1 x2 y :: "'a::metric_space"
+  shows "dist x1 y < e / 2 \<Longrightarrow> dist x2 y < e / 2 \<Longrightarrow> dist x1 x2 < e"
+by (rule dist_triangle_lt [where z=y], simp)
+
+lemma dist_triangle_half_r:
+  fixes x1 x2 y :: "'a::metric_space"
+  shows "dist y x1 < e / 2 \<Longrightarrow> dist y x2 < e / 2 \<Longrightarrow> dist x1 x2 < e"
+by (rule dist_triangle_half_l, simp_all add: dist_commute)
+
+lemma dist_triangle_add:
+  fixes x y x' y' :: "'a::real_normed_vector"
+  shows "dist (x + y) (x' + y') <= dist x x' + dist y y'"
+unfolding dist_norm by (rule norm_diff_triangle_ineq)
 
 lemma dist_mul[simp]: "dist (c *s x) (c *s y) = \<bar>c\<bar> * dist x y"
-  unfolding dist_def vector_ssub_ldistrib[symmetric] norm_mul ..
-
-lemma dist_triangle_add_half: " dist x x' < e / 2 \<Longrightarrow> dist y y' < e / 2 ==> dist(x + y) (x' + y') < e" by norm
-
-lemma dist_le_0[simp]: "dist x y <= 0 \<longleftrightarrow> x = y" by norm
+  unfolding dist_norm vector_ssub_ldistrib[symmetric] norm_mul ..
+
+lemma dist_triangle_add_half:
+  fixes x x' y y' :: "'a::real_normed_vector"
+  shows "dist x x' < e / 2 \<Longrightarrow> dist y y' < e / 2 \<Longrightarrow> dist(x + y) (x' + y') < e"
+by (rule le_less_trans [OF dist_triangle_add], simp)
 
 lemma setsum_component [simp]:
   fixes f:: " 'a \<Rightarrow> ('b::comm_monoid_add) ^'n"
@@ -1228,7 +1269,7 @@
 proof-
   from vector_choose_size[OF e] obtain c:: "real ^'n"  where "norm c = e"
     by blast
-  then have "dist x (x - c) = e" by (simp add: dist_def)
+  then have "dist x (x - c) = e" by (simp add: dist_norm)
   then show ?thesis by blast
 qed
 
@@ -2552,7 +2593,7 @@
 qed
 
 lemma dist_fstcart: "dist(fstcart (x::real^_)) (fstcart y) <= dist x y"
-  by (metis dist_def fstcart_sub[symmetric] norm_fstcart)
+  unfolding dist_norm by (metis fstcart_sub[symmetric] norm_fstcart)
 
 lemma norm_sndcart: "norm(sndcart x) <= norm (x::real ^('n::finite + 'm::finite))"
 proof-
@@ -2567,7 +2608,7 @@
 qed
 
 lemma dist_sndcart: "dist(sndcart (x::real^_)) (sndcart y) <= dist x y"
-  by (metis dist_def sndcart_sub[symmetric] norm_sndcart)
+  unfolding dist_norm by (metis sndcart_sub[symmetric] norm_sndcart)
 
 lemma dot_pastecart: "(pastecart (x1::'a::{times,comm_monoid_add}^'n::finite) (x2::'a::{times,comm_monoid_add}^'m::finite)) \<bullet> (pastecart y1 y2) =  x1 \<bullet> y1 + x2 \<bullet> y2"
   by (simp add: dot_def setsum_UNIV_sum pastecart_def)
@@ -3907,7 +3948,7 @@
 qed
 
 lemma span_eq: "span S = span T \<longleftrightarrow> S \<subseteq> span T \<and> T \<subseteq> span S"
-  by (metis set_eq_subset span_mono span_span span_inc)
+  by (metis set_eq_subset span_mono span_span span_inc) (* FIXME: slow *)
 
 (* ------------------------------------------------------------------------- *)
 (* Low-dimensional subset is in a hyperplane (weak orthogonal complement).   *)
--- a/src/HOL/Library/Formal_Power_Series.thy	Mon Jun 01 09:26:28 2009 +0200
+++ b/src/HOL/Library/Formal_Power_Series.thy	Tue Jun 02 12:18:08 2009 +0200
@@ -5,7 +5,7 @@
 header{* A formalization of formal power series *}
 
 theory Formal_Power_Series
-imports Main Fact Parity
+imports Main Fact Parity Rational
 begin
 
 subsection {* The type of formal power series*}
@@ -393,8 +393,8 @@
 begin
 definition number_of_fps_def: "(number_of k::'a fps) = of_int k"
 
-instance 
-by (intro_classes, rule number_of_fps_def)
+instance proof
+qed (rule number_of_fps_def)
 end
 
 lemma number_of_fps_const: "(number_of k::('a::comm_ring_1) fps) = fps_const (of_int k)"
@@ -936,12 +936,19 @@
 
 
 subsection{* Integration *}
-definition "fps_integral a a0 = Abs_fps (\<lambda>n. if n = 0 then a0 else (a$(n - 1) / of_nat n))"
+
+definition
+  fps_integral :: "'a::field_char_0 fps \<Rightarrow> 'a \<Rightarrow> 'a fps" where
+  "fps_integral a a0 = Abs_fps (\<lambda>n. if n = 0 then a0 else (a$(n - 1) / of_nat n))"
 
-lemma fps_deriv_fps_integral: "fps_deriv (fps_integral a (a0 :: 'a :: {field, ring_char_0})) = a"
-  by (simp add: fps_integral_def fps_deriv_def fps_eq_iff field_simps del: of_nat_Suc)
+lemma fps_deriv_fps_integral: "fps_deriv (fps_integral a a0) = a"
+  unfolding fps_integral_def fps_deriv_def
+  by (simp add: fps_eq_iff del: of_nat_Suc)
 
-lemma fps_integral_linear: "fps_integral (fps_const (a::'a::{field, ring_char_0}) * f + fps_const b * g) (a*a0 + b*b0) = fps_const a * fps_integral f a0 + fps_const b * fps_integral g b0" (is "?l = ?r")
+lemma fps_integral_linear:
+  "fps_integral (fps_const a * f + fps_const b * g) (a*a0 + b*b0) =
+    fps_const a * fps_integral f a0 + fps_const b * fps_integral g b0"
+  (is "?l = ?r")
 proof-
   have "fps_deriv ?l = fps_deriv ?r" by (simp add: fps_deriv_fps_integral)
   moreover have "?l$0 = ?r$0" by (simp add: fps_integral_def)
@@ -1454,7 +1461,7 @@
 qed
 
 lemma power_radical:
-  fixes a:: "'a ::{field, ring_char_0} fps"
+  fixes a:: "'a::field_char_0 fps"
   assumes a0: "a$0 \<noteq> 0"
   shows "(r (Suc k) (a$0)) ^ Suc k = a$0 \<longleftrightarrow> (fps_radical r (Suc k) a) ^ (Suc k) = a"
 proof-
@@ -1515,7 +1522,7 @@
 
 (*
 lemma power_radical:
-  fixes a:: "'a ::{field, ring_char_0} fps"
+  fixes a:: "'a::field_char_0 fps"
   assumes r0: "(r (Suc k) (a$0)) ^ Suc k = a$0" and a0: "a$0 \<noteq> 0"
   shows "(fps_radical r (Suc k) a) ^ (Suc k) = a"
 proof-
@@ -1577,7 +1584,7 @@
 
 lemma radical_unique:
   assumes r0: "(r (Suc k) (b$0)) ^ Suc k = b$0"
-  and a0: "r (Suc k) (b$0 ::'a::{field, ring_char_0}) = a$0" and b0: "b$0 \<noteq> 0"
+  and a0: "r (Suc k) (b$0 ::'a::field_char_0) = a$0" and b0: "b$0 \<noteq> 0"
   shows "a^(Suc k) = b \<longleftrightarrow> a = fps_radical r (Suc k) b"
 proof-
   let ?r = "fps_radical r (Suc k) b"
@@ -1671,7 +1678,7 @@
 
 lemma radical_power:
   assumes r0: "r (Suc k) ((a$0) ^ Suc k) = a$0"
-  and a0: "(a$0 ::'a::{field, ring_char_0}) \<noteq> 0"
+  and a0: "(a$0 ::'a::field_char_0) \<noteq> 0"
   shows "(fps_radical r (Suc k) (a ^ Suc k)) = a"
 proof-
   let ?ak = "a^ Suc k"
@@ -1683,7 +1690,7 @@
 qed
 
 lemma fps_deriv_radical:
-  fixes a:: "'a ::{field, ring_char_0} fps"
+  fixes a:: "'a::field_char_0 fps"
   assumes r0: "(r (Suc k) (a$0)) ^ Suc k = a$0" and a0: "a$0 \<noteq> 0"
   shows "fps_deriv (fps_radical r (Suc k) a) = fps_deriv a / (fps_const (of_nat (Suc k)) * (fps_radical r (Suc k) a) ^ k)"
 proof-
@@ -1704,7 +1711,7 @@
 qed
 
 lemma radical_mult_distrib:
-  fixes a:: "'a ::{field, ring_char_0} fps"
+  fixes a:: "'a::field_char_0 fps"
   assumes
   k: "k > 0"
   and ra0: "r k (a $ 0) ^ k = a $ 0"
@@ -1738,7 +1745,7 @@
 
 (*
 lemma radical_mult_distrib:
-  fixes a:: "'a ::{field, ring_char_0} fps"
+  fixes a:: "'a::field_char_0 fps"
   assumes
   ra0: "r k (a $ 0) ^ k = a $ 0"
   and rb0: "r k (b $ 0) ^ k = b $ 0"
@@ -1768,7 +1775,7 @@
   by (simp add: fps_divide_def)
 
 lemma radical_divide:
-  fixes a:: "'a ::{field, ring_char_0} fps"
+  fixes a :: "'a::field_char_0 fps"
   assumes
   kp: "k>0"
   and ra0: "(r k (a $ 0)) ^ k = a $ 0"
@@ -1806,7 +1813,7 @@
 qed
 
 lemma radical_inverse:
-  fixes a:: "'a ::{field, ring_char_0} fps"
+  fixes a :: "'a::field_char_0 fps"
   assumes
   k: "k>0"
   and ra0: "r k (a $ 0) ^ k = a $ 0"
@@ -2175,7 +2182,7 @@
 by (induct n, auto)
 
 lemma fps_compose_radical:
-  assumes b0: "b$0 = (0::'a::{field, ring_char_0})"
+  assumes b0: "b$0 = (0::'a::field_char_0)"
   and ra0: "r (Suc k) (a$0) ^ Suc k = a$0"
   and a0: "a$0 \<noteq> 0"
   shows "fps_radical r (Suc k)  a oo b = fps_radical r (Suc k) (a oo b)"
@@ -2315,7 +2322,7 @@
 subsubsection{* Exponential series *}
 definition "E x = Abs_fps (\<lambda>n. x^n / of_nat (fact n))"
 
-lemma E_deriv[simp]: "fps_deriv (E a) = fps_const (a::'a::{field, ring_char_0}) * E a" (is "?l = ?r")
+lemma E_deriv[simp]: "fps_deriv (E a) = fps_const (a::'a::field_char_0) * E a" (is "?l = ?r")
 proof-
   {fix n
     have "?l$n = ?r $ n"
@@ -2325,7 +2332,7 @@
 qed
 
 lemma E_unique_ODE:
-  "fps_deriv a = fps_const c * a \<longleftrightarrow> a = fps_const (a$0) * E (c :: 'a::{field, ring_char_0})"
+  "fps_deriv a = fps_const c * a \<longleftrightarrow> a = fps_const (a$0) * E (c :: 'a::field_char_0)"
   (is "?lhs \<longleftrightarrow> ?rhs")
 proof-
   {assume d: ?lhs
@@ -2352,7 +2359,7 @@
 ultimately show ?thesis by blast
 qed
 
-lemma E_add_mult: "E (a + b) = E (a::'a::{ring_char_0, field}) * E b" (is "?l = ?r")
+lemma E_add_mult: "E (a + b) = E (a::'a::field_char_0) * E b" (is "?l = ?r")
 proof-
   have "fps_deriv (?r) = fps_const (a+b) * ?r"
     by (simp add: fps_const_add[symmetric] ring_simps del: fps_const_add)
@@ -2367,7 +2374,7 @@
 lemma E0[simp]: "E (0::'a::{field}) = 1"
   by (simp add: fps_eq_iff power_0_left)
 
-lemma E_neg: "E (- a) = inverse (E (a::'a::{ring_char_0, field}))"
+lemma E_neg: "E (- a) = inverse (E (a::'a::field_char_0))"
 proof-
   from E_add_mult[of a "- a"] have th0: "E a * E (- a) = 1"
     by (simp )
@@ -2375,7 +2382,7 @@
   from fps_inverse_unique[OF th1 th0] show ?thesis by simp
 qed
 
-lemma E_nth_deriv[simp]: "fps_nth_deriv n (E (a::'a::{field, ring_char_0})) = (fps_const a)^n * (E a)"
+lemma E_nth_deriv[simp]: "fps_nth_deriv n (E (a::'a::field_char_0)) = (fps_const a)^n * (E a)"
   by (induct n, auto simp add: power_Suc)
 
 lemma X_compose_E[simp]: "X oo E (a::'a::{field}) = E a - 1"
@@ -2408,11 +2415,11 @@
   from fps_inverse_unique[OF th' th] show ?thesis .
 qed
 
-lemma E_power_mult: "(E (c::'a::{field,ring_char_0}))^n = E (of_nat n * c)"
+lemma E_power_mult: "(E (c::'a::field_char_0))^n = E (of_nat n * c)"
   by (induct n, auto simp add: ring_simps E_add_mult power_Suc)
 
 lemma assumes r: "r (Suc k) 1 = 1" 
-  shows "fps_radical r (Suc k) (E (c::'a::{field, ring_char_0})) = E (c / of_nat (Suc k))"
+  shows "fps_radical r (Suc k) (E (c::'a::{field_char_0})) = E (c / of_nat (Suc k))"
 proof-
   let ?ck = "(c / of_nat (Suc k))"
   let ?r = "fps_radical r (Suc k)"
@@ -2426,18 +2433,17 @@
 qed
 
 lemma Ec_E1_eq: 
-  "E (1::'a::{field, ring_char_0}) oo (fps_const c * X) = E c"
+  "E (1::'a::{field_char_0}) oo (fps_const c * X) = E c"
   apply (auto simp add: fps_eq_iff E_def fps_compose_def power_mult_distrib)
   by (simp add: cond_value_iff cond_application_beta setsum_delta' cong del: if_weak_cong)
 
 subsubsection{* Logarithmic series *}
 
-
 lemma Abs_fps_if_0: 
   "Abs_fps(%n. if n=0 then (v::'a::ring_1) else f n) = fps_const v + X * Abs_fps (%n. f (Suc n))"
   by (auto simp add: fps_eq_iff)
 
-definition L:: "'a::{field, ring_char_0} \<Rightarrow> 'a fps" where 
+definition L:: "'a::{field_char_0} \<Rightarrow> 'a fps" where 
   "L c \<equiv> fps_const (1/c) * Abs_fps (\<lambda>n. if n = 0 then 0 else (- 1) ^ (n - 1) / of_nat n)"
 
 lemma fps_deriv_L: "fps_deriv (L c) = fps_const (1/c) * inverse (1 + X)"
@@ -2449,7 +2455,7 @@
 
 lemma L_0[simp]: "L c $ 0 = 0" by (simp add: L_def)
 lemma L_E_inv:
-  assumes a: "a\<noteq> (0::'a::{field,ring_char_0})"
+  assumes a: "a\<noteq> (0::'a::{field_char_0})"
   shows "L a = fps_inv (E a - 1)" (is "?l = ?r")
 proof-
   let ?b = "E a - 1"
@@ -2487,16 +2493,17 @@
 
 subsubsection{* Formal trigonometric functions  *}
 
-definition "fps_sin (c::'a::{field, ring_char_0}) =
+definition "fps_sin (c::'a::field_char_0) =
   Abs_fps (\<lambda>n. if even n then 0 else (- 1) ^((n - 1) div 2) * c^n /(of_nat (fact n)))"
 
-definition "fps_cos (c::'a::{field, ring_char_0}) = Abs_fps (\<lambda>n. if even n then (- 1) ^ (n div 2) * c^n / (of_nat (fact n)) else 0)"
+definition "fps_cos (c::'a::field_char_0) =
+  Abs_fps (\<lambda>n. if even n then (- 1) ^ (n div 2) * c^n / (of_nat (fact n)) else 0)"
 
 lemma fps_sin_deriv:
   "fps_deriv (fps_sin c) = fps_const c * fps_cos c"
   (is "?lhs = ?rhs")
-proof-
-  {fix n::nat
+proof (rule fps_ext)
+  fix n::nat
     {assume en: "even n"
       have "?lhs$n = of_nat (n+1) * (fps_sin c $ (n+1))" by simp
       also have "\<dots> = of_nat (n+1) * ((- 1)^(n div 2) * c^Suc n / of_nat (fact (Suc n)))"
@@ -2508,18 +2515,18 @@
 	by (simp add: field_simps del: of_nat_add of_nat_Suc)
       finally have "?lhs $n = ?rhs$n" using en
 	by (simp add: fps_cos_def ring_simps power_Suc )}
-    then have "?lhs $ n = ?rhs $ n"
-      by (cases "even n", simp_all add: fps_deriv_def fps_sin_def fps_cos_def) }
-  then show ?thesis by (auto simp add: fps_eq_iff)
+    then show "?lhs $ n = ?rhs $ n"
+      by (cases "even n", simp_all add: fps_deriv_def fps_sin_def fps_cos_def)
 qed
 
 lemma fps_cos_deriv:
   "fps_deriv (fps_cos c) = fps_const (- c)* (fps_sin c)"
   (is "?lhs = ?rhs")
-proof-
+proof (rule fps_ext)
   have th0: "\<And>n. - ((- 1::'a) ^ n) = (- 1)^Suc n" by (simp add: power_Suc)
-  have th1: "\<And>n. odd n\<Longrightarrow> Suc ((n - 1) div 2) = Suc n div 2" by presburger (* FIXME: VERY slow! *)
-  {fix n::nat
+  have th1: "\<And>n. odd n \<Longrightarrow> Suc ((n - 1) div 2) = Suc n div 2"
+    by (case_tac n, simp_all)
+  fix n::nat
     {assume en: "odd n"
       from en have n0: "n \<noteq>0 " by presburger
       have "?lhs$n = of_nat (n+1) * (fps_cos c $ (n+1))" by simp
@@ -2534,10 +2541,9 @@
 	unfolding th0 unfolding th1[OF en] by simp
       finally have "?lhs $n = ?rhs$n" using en
 	by (simp add: fps_sin_def ring_simps power_Suc)}
-    then have "?lhs $ n = ?rhs $ n"
+    then show "?lhs $ n = ?rhs $ n"
       by (cases "even n", simp_all add: fps_deriv_def fps_sin_def
-	fps_cos_def) }
-  then show ?thesis by (auto simp add: fps_eq_iff)
+	fps_cos_def)
 qed
 
 lemma fps_sin_cos_sum_of_squares:
@@ -2553,6 +2559,110 @@
   finally show ?thesis .
 qed
 
+lemma fact_1 [simp]: "fact 1 = 1"
+unfolding One_nat_def fact_Suc by simp
+
+lemma divide_eq_iff: "a \<noteq> (0::'a::field) \<Longrightarrow> x / a = y \<longleftrightarrow> x = y * a"
+by auto
+
+lemma eq_divide_iff: "a \<noteq> (0::'a::field) \<Longrightarrow> x = y / a \<longleftrightarrow> x * a = y"
+by auto
+
+lemma fps_sin_nth_0 [simp]: "fps_sin c $ 0 = 0"
+unfolding fps_sin_def by simp
+
+lemma fps_sin_nth_1 [simp]: "fps_sin c $ 1 = c"
+unfolding fps_sin_def by simp
+
+lemma fps_sin_nth_add_2:
+  "fps_sin c $ (n + 2) = - (c * c * fps_sin c $ n / (of_nat(n+1) * of_nat(n+2)))"
+unfolding fps_sin_def
+apply (cases n, simp)
+apply (simp add: divide_eq_iff eq_divide_iff del: of_nat_Suc fact_Suc)
+apply (simp add: of_nat_mult del: of_nat_Suc mult_Suc)
+done
+
+lemma fps_cos_nth_0 [simp]: "fps_cos c $ 0 = 1"
+unfolding fps_cos_def by simp
+
+lemma fps_cos_nth_1 [simp]: "fps_cos c $ 1 = 0"
+unfolding fps_cos_def by simp
+
+lemma fps_cos_nth_add_2:
+  "fps_cos c $ (n + 2) = - (c * c * fps_cos c $ n / (of_nat(n+1) * of_nat(n+2)))"
+unfolding fps_cos_def
+apply (simp add: divide_eq_iff eq_divide_iff del: of_nat_Suc fact_Suc)
+apply (simp add: of_nat_mult del: of_nat_Suc mult_Suc)
+done
+
+lemma nat_induct2:
+  "\<lbrakk>P 0; P 1; \<And>n. P n \<Longrightarrow> P (n + 2)\<rbrakk> \<Longrightarrow> P (n::nat)"
+unfolding One_nat_def numeral_2_eq_2
+apply (induct n rule: nat_less_induct)
+apply (case_tac n, simp)
+apply (rename_tac m, case_tac m, simp)
+apply (rename_tac k, case_tac k, simp_all)
+done
+
+lemma nat_add_1_add_1: "(n::nat) + 1 + 1 = n + 2"
+by simp
+
+lemma eq_fps_sin:
+  assumes 0: "a $ 0 = 0" and 1: "a $ 1 = c"
+  and 2: "fps_deriv (fps_deriv a) = - (fps_const c * fps_const c * a)"
+  shows "a = fps_sin c"
+apply (rule fps_ext)
+apply (induct_tac n rule: nat_induct2)
+apply (simp add: fps_sin_nth_0 0)
+apply (simp add: fps_sin_nth_1 1 del: One_nat_def)
+apply (rename_tac m, cut_tac f="\<lambda>a. a $ m" in arg_cong [OF 2])
+apply (simp add: nat_add_1_add_1 fps_sin_nth_add_2
+            del: One_nat_def of_nat_Suc of_nat_add add_2_eq_Suc')
+apply (subst minus_divide_left)
+apply (subst eq_divide_iff)
+apply (simp del: of_nat_add of_nat_Suc)
+apply (simp only: mult_ac)
+done
+
+lemma eq_fps_cos:
+  assumes 0: "a $ 0 = 1" and 1: "a $ 1 = 0"
+  and 2: "fps_deriv (fps_deriv a) = - (fps_const c * fps_const c * a)"
+  shows "a = fps_cos c"
+apply (rule fps_ext)
+apply (induct_tac n rule: nat_induct2)
+apply (simp add: fps_cos_nth_0 0)
+apply (simp add: fps_cos_nth_1 1 del: One_nat_def)
+apply (rename_tac m, cut_tac f="\<lambda>a. a $ m" in arg_cong [OF 2])
+apply (simp add: nat_add_1_add_1 fps_cos_nth_add_2
+            del: One_nat_def of_nat_Suc of_nat_add add_2_eq_Suc')
+apply (subst minus_divide_left)
+apply (subst eq_divide_iff)
+apply (simp del: of_nat_add of_nat_Suc)
+apply (simp only: mult_ac)
+done
+
+lemma mult_nth_0 [simp]: "(a * b) $ 0 = a $ 0 * b $ 0"
+by (simp add: fps_mult_nth)
+
+lemma mult_nth_1 [simp]: "(a * b) $ 1 = a $ 0 * b $ 1 + a $ 1 * b $ 0"
+by (simp add: fps_mult_nth)
+
+lemma fps_sin_add:
+  "fps_sin (a + b) = fps_sin a * fps_cos b + fps_cos a * fps_sin b"
+apply (rule eq_fps_sin [symmetric], simp, simp del: One_nat_def)
+apply (simp del: fps_const_neg fps_const_add fps_const_mult
+            add: fps_const_add [symmetric] fps_const_neg [symmetric]
+                 fps_sin_deriv fps_cos_deriv algebra_simps)
+done
+
+lemma fps_cos_add:
+  "fps_cos (a + b) = fps_cos a * fps_cos b - fps_sin a * fps_sin b"
+apply (rule eq_fps_cos [symmetric], simp, simp del: One_nat_def)
+apply (simp del: fps_const_neg fps_const_add fps_const_mult
+            add: fps_const_add [symmetric] fps_const_neg [symmetric]
+                 fps_sin_deriv fps_cos_deriv algebra_simps)
+done
+
 definition "fps_tan c = fps_sin c / fps_cos c"
 
 lemma fps_tan_deriv: "fps_deriv(fps_tan c) = fps_const c/ (fps_cos c ^ 2)"
--- a/src/HOL/Library/Fundamental_Theorem_Algebra.thy	Mon Jun 01 09:26:28 2009 +0200
+++ b/src/HOL/Library/Fundamental_Theorem_Algebra.thy	Tue Jun 02 12:18:08 2009 +0200
@@ -306,12 +306,12 @@
   from conv1[unfolded convergent_def] obtain x where "LIMSEQ (\<lambda>n. Re (s (f n))) x"
     by blast
   hence  x: "\<forall>r>0. \<exists>n0. \<forall>n\<ge>n0. \<bar> Re (s (f n)) - x \<bar> < r"
-    unfolding LIMSEQ_def real_norm_def .
+    unfolding LIMSEQ_iff real_norm_def .
 
   from conv2[unfolded convergent_def] obtain y where "LIMSEQ (\<lambda>n. Im (s (f (g n)))) y"
     by blast
   hence  y: "\<forall>r>0. \<exists>n0. \<forall>n\<ge>n0. \<bar> Im (s (f (g n))) - y \<bar> < r"
-    unfolding LIMSEQ_def real_norm_def .
+    unfolding LIMSEQ_iff real_norm_def .
   let ?w = "Complex x y"
   from f(1) g(1) have hs: "subseq ?h" unfolding subseq_def by auto
   {fix e assume ep: "e > (0::real)"
--- a/src/HOL/Library/Inner_Product.thy	Mon Jun 01 09:26:28 2009 +0200
+++ b/src/HOL/Library/Inner_Product.thy	Tue Jun 02 12:18:08 2009 +0200
@@ -10,7 +10,7 @@
 
 subsection {* Real inner product spaces *}
 
-class real_inner = real_vector + sgn_div_norm +
+class real_inner = real_vector + sgn_div_norm + dist_norm +
   fixes inner :: "'a \<Rightarrow> 'a \<Rightarrow> real"
   assumes inner_commute: "inner x y = inner y x"
   and inner_left_distrib: "inner (x + y) z = inner x z + inner y z"
--- a/src/HOL/Library/Product_Vector.thy	Mon Jun 01 09:26:28 2009 +0200
+++ b/src/HOL/Library/Product_Vector.thy	Tue Jun 02 12:18:08 2009 +0200
@@ -39,6 +39,38 @@
 
 end
 
+subsection {* Product is a metric space *}
+
+instantiation
+  "*" :: (metric_space, metric_space) metric_space
+begin
+
+definition dist_prod_def:
+  "dist (x::'a \<times> 'b) y = sqrt ((dist (fst x) (fst y))\<twosuperior> + (dist (snd x) (snd y))\<twosuperior>)"
+
+lemma dist_Pair_Pair: "dist (a, b) (c, d) = sqrt ((dist a c)\<twosuperior> + (dist b d)\<twosuperior>)"
+  unfolding dist_prod_def by simp
+
+instance proof
+  fix x y :: "'a \<times> 'b"
+  show "dist x y = 0 \<longleftrightarrow> x = y"
+    unfolding dist_prod_def
+    by (simp add: expand_prod_eq)
+next
+  fix x y z :: "'a \<times> 'b"
+  show "dist x y \<le> dist x z + dist y z"
+    unfolding dist_prod_def
+    apply (rule order_trans [OF _ real_sqrt_sum_squares_triangle_ineq])
+    apply (rule real_sqrt_le_mono)
+    apply (rule order_trans [OF add_mono])
+    apply (rule power_mono [OF dist_triangle2 [of _ _ "fst z"] zero_le_dist])
+    apply (rule power_mono [OF dist_triangle2 [of _ _ "snd z"] zero_le_dist])
+    apply (simp only: real_sum_squared_expand)
+    done
+qed
+
+end
+
 subsection {* Product is a normed vector space *}
 
 instantiation
@@ -74,6 +106,9 @@
     done
   show "sgn x = scaleR (inverse (norm x)) x"
     by (rule sgn_prod_def)
+  show "dist x y = norm (x - y)"
+    unfolding dist_prod_def norm_prod_def
+    by (simp add: dist_norm)
 qed
 
 end
@@ -174,53 +209,53 @@
 lemma LIMSEQ_Pair:
   assumes "X ----> a" and "Y ----> b"
   shows "(\<lambda>n. (X n, Y n)) ----> (a, b)"
-proof (rule LIMSEQ_I)
+proof (rule metric_LIMSEQ_I)
   fix r :: real assume "0 < r"
   then have "0 < r / sqrt 2" (is "0 < ?s")
     by (simp add: divide_pos_pos)
-  obtain M where M: "\<forall>n\<ge>M. norm (X n - a) < ?s"
-    using LIMSEQ_D [OF `X ----> a` `0 < ?s`] ..
-  obtain N where N: "\<forall>n\<ge>N. norm (Y n - b) < ?s"
-    using LIMSEQ_D [OF `Y ----> b` `0 < ?s`] ..
-  have "\<forall>n\<ge>max M N. norm ((X n, Y n) - (a, b)) < r"
-    using M N by (simp add: real_sqrt_sum_squares_less norm_Pair)
-  then show "\<exists>n0. \<forall>n\<ge>n0. norm ((X n, Y n) - (a, b)) < r" ..
+  obtain M where M: "\<forall>n\<ge>M. dist (X n) a < ?s"
+    using metric_LIMSEQ_D [OF `X ----> a` `0 < ?s`] ..
+  obtain N where N: "\<forall>n\<ge>N. dist (Y n) b < ?s"
+    using metric_LIMSEQ_D [OF `Y ----> b` `0 < ?s`] ..
+  have "\<forall>n\<ge>max M N. dist (X n, Y n) (a, b) < r"
+    using M N by (simp add: real_sqrt_sum_squares_less dist_Pair_Pair)
+  then show "\<exists>n0. \<forall>n\<ge>n0. dist (X n, Y n) (a, b) < r" ..
 qed
 
 lemma Cauchy_Pair:
   assumes "Cauchy X" and "Cauchy Y"
   shows "Cauchy (\<lambda>n. (X n, Y n))"
-proof (rule CauchyI)
+proof (rule metric_CauchyI)
   fix r :: real assume "0 < r"
   then have "0 < r / sqrt 2" (is "0 < ?s")
     by (simp add: divide_pos_pos)
-  obtain M where M: "\<forall>m\<ge>M. \<forall>n\<ge>M. norm (X m - X n) < ?s"
-    using CauchyD [OF `Cauchy X` `0 < ?s`] ..
-  obtain N where N: "\<forall>m\<ge>N. \<forall>n\<ge>N. norm (Y m - Y n) < ?s"
-    using CauchyD [OF `Cauchy Y` `0 < ?s`] ..
-  have "\<forall>m\<ge>max M N. \<forall>n\<ge>max M N. norm ((X m, Y m) - (X n, Y n)) < r"
-    using M N by (simp add: real_sqrt_sum_squares_less norm_Pair)
-  then show "\<exists>n0. \<forall>m\<ge>n0. \<forall>n\<ge>n0. norm ((X m, Y m) - (X n, Y n)) < r" ..
+  obtain M where M: "\<forall>m\<ge>M. \<forall>n\<ge>M. dist (X m) (X n) < ?s"
+    using metric_CauchyD [OF `Cauchy X` `0 < ?s`] ..
+  obtain N where N: "\<forall>m\<ge>N. \<forall>n\<ge>N. dist (Y m) (Y n) < ?s"
+    using metric_CauchyD [OF `Cauchy Y` `0 < ?s`] ..
+  have "\<forall>m\<ge>max M N. \<forall>n\<ge>max M N. dist (X m, Y m) (X n, Y n) < r"
+    using M N by (simp add: real_sqrt_sum_squares_less dist_Pair_Pair)
+  then show "\<exists>n0. \<forall>m\<ge>n0. \<forall>n\<ge>n0. dist (X m, Y m) (X n, Y n) < r" ..
 qed
 
 lemma LIM_Pair:
   assumes "f -- x --> a" and "g -- x --> b"
   shows "(\<lambda>x. (f x, g x)) -- x --> (a, b)"
-proof (rule LIM_I)
+proof (rule metric_LIM_I)
   fix r :: real assume "0 < r"
   then have "0 < r / sqrt 2" (is "0 < ?e")
     by (simp add: divide_pos_pos)
   obtain s where s: "0 < s"
-    "\<forall>z. z \<noteq> x \<and> norm (z - x) < s \<longrightarrow> norm (f z - a) < ?e"
-    using LIM_D [OF `f -- x --> a` `0 < ?e`] by fast
+    "\<forall>z. z \<noteq> x \<and> dist z x < s \<longrightarrow> dist (f z) a < ?e"
+    using metric_LIM_D [OF `f -- x --> a` `0 < ?e`] by fast
   obtain t where t: "0 < t"
-    "\<forall>z. z \<noteq> x \<and> norm (z - x) < t \<longrightarrow> norm (g z - b) < ?e"
-    using LIM_D [OF `g -- x --> b` `0 < ?e`] by fast
+    "\<forall>z. z \<noteq> x \<and> dist z x < t \<longrightarrow> dist (g z) b < ?e"
+    using metric_LIM_D [OF `g -- x --> b` `0 < ?e`] by fast
   have "0 < min s t \<and>
-    (\<forall>z. z \<noteq> x \<and> norm (z - x) < min s t \<longrightarrow> norm ((f z, g z) - (a, b)) < r)"
-    using s t by (simp add: real_sqrt_sum_squares_less norm_Pair)
+    (\<forall>z. z \<noteq> x \<and> dist z x < min s t \<longrightarrow> dist (f z, g z) (a, b) < r)"
+    using s t by (simp add: real_sqrt_sum_squares_less dist_Pair_Pair)
   then show
-    "\<exists>s>0. \<forall>z. z \<noteq> x \<and> norm (z - x) < s \<longrightarrow> norm ((f z, g z) - (a, b)) < r" ..
+    "\<exists>s>0. \<forall>z. z \<noteq> x \<and> dist z x < s \<longrightarrow> dist (f z, g z) (a, b) < r" ..
 qed
 
 lemma isCont_Pair [simp]:
--- a/src/HOL/Library/Topology_Euclidean_Space.thy	Mon Jun 01 09:26:28 2009 +0200
+++ b/src/HOL/Library/Topology_Euclidean_Space.thy	Tue Jun 02 12:18:08 2009 +0200
@@ -194,7 +194,9 @@
   by (simp add: subtopology_superset)
 
 subsection{* The universal Euclidean versions are what we use most of the time *}
-definition "open S \<longleftrightarrow> (\<forall>x \<in> S. \<exists>e >0. \<forall>x'. dist x' x < e \<longrightarrow> x' \<in> S)"
+definition
+  "open" :: "'a::metric_space set \<Rightarrow> bool" where
+  "open S \<longleftrightarrow> (\<forall>x \<in> S. \<exists>e >0. \<forall>x'. dist x' x < e \<longrightarrow> x' \<in> S)"
 definition "closed S \<longleftrightarrow> open(UNIV - S)"
 definition "euclidean = topology open"
 
@@ -285,13 +287,27 @@
 
 subsection{* Open and closed balls. *}
 
-definition "ball x e = {y. dist x y < e}"
-definition "cball x e = {y. dist x y \<le> e}"
+definition
+  ball :: "'a::metric_space \<Rightarrow> real \<Rightarrow> 'a set" where
+  "ball x e = {y. dist x y < e}"
+
+definition
+  cball :: "'a::metric_space \<Rightarrow> real \<Rightarrow> 'a set" where
+  "cball x e = {y. dist x y \<le> e}"
 
 lemma mem_ball[simp]: "y \<in> ball x e \<longleftrightarrow> dist x y < e" by (simp add: ball_def)
 lemma mem_cball[simp]: "y \<in> cball x e \<longleftrightarrow> dist x y \<le> e" by (simp add: cball_def)
-lemma mem_ball_0[simp]: "x \<in> ball 0 e \<longleftrightarrow> norm x < e" by (simp add: dist_def)
-lemma mem_cball_0[simp]: "x \<in> cball 0 e \<longleftrightarrow> norm x \<le> e" by (simp add: dist_def)
+
+lemma mem_ball_0 [simp]:
+  fixes x :: "'a::real_normed_vector"
+  shows "x \<in> ball 0 e \<longleftrightarrow> norm x < e"
+  by (simp add: dist_norm)
+
+lemma mem_cball_0 [simp]:
+  fixes x :: "'a::real_normed_vector"
+  shows "x \<in> cball 0 e \<longleftrightarrow> norm x \<le> e"
+  by (simp add: dist_norm)
+
 lemma centre_in_cball[simp]: "x \<in> cball x e \<longleftrightarrow> 0\<le> e"  by simp
 lemma ball_subset_cball[simp,intro]: "ball x e \<subseteq> cball x e" by (simp add: subset_eq)
 lemma subset_ball[intro]: "d <= e ==> ball x d \<subseteq> ball x e" by (simp add: subset_eq)
@@ -312,7 +328,7 @@
 
 lemma open_ball[intro, simp]: "open (ball x e)"
   unfolding open_def ball_def Collect_def Ball_def mem_def
-  unfolding dist_sym
+  unfolding dist_commute
   apply clarify
   apply (rule_tac x="e - dist xa x" in exI)
   using dist_triangle_alt[where z=x]
@@ -322,9 +338,9 @@
   apply (erule_tac x="xa" in allE)
   by arith
 
-lemma centre_in_ball[simp]: "x \<in> ball x e \<longleftrightarrow> e > 0" by (metis mem_ball dist_refl)
+lemma centre_in_ball[simp]: "x \<in> ball x e \<longleftrightarrow> e > 0" by (metis mem_ball dist_self)
 lemma open_contains_ball: "open S \<longleftrightarrow> (\<forall>x\<in>S. \<exists>e>0. ball x e \<subseteq> S)"
-  unfolding open_def subset_eq mem_ball Ball_def dist_sym ..
+  unfolding open_def subset_eq mem_ball Ball_def dist_commute ..
 
 lemma open_contains_ball_eq: "open S \<Longrightarrow> \<forall>x. x\<in>S \<longleftrightarrow> (\<exists>e>0. ball x e \<subseteq> S)"
   by (metis open_contains_ball subset_eq centre_in_ball)
@@ -332,7 +348,7 @@
 lemma ball_eq_empty[simp]: "ball x e = {} \<longleftrightarrow> e \<le> 0"
   unfolding mem_ball expand_set_eq
   apply (simp add: not_less)
-  by (metis dist_pos_le order_trans dist_refl)
+  by (metis zero_le_dist order_trans dist_self)
 
 lemma ball_empty[intro]: "e \<le> 0 ==> ball x e = {}" by simp
 
@@ -380,14 +396,14 @@
     { fix x assume "x\<in>S"
       hence "x \<in> \<Union>{B. \<exists>x\<in>S. B = ball x (d x)}"
 	apply simp apply(rule_tac x="ball x(d x)" in exI) apply auto
-	unfolding dist_refl using d[of x] by auto
+        by (rule d [THEN conjunct1])
       hence "x\<in> ?T \<inter> U" using SU and `x\<in>S` by auto  }
     moreover
     { fix y assume "y\<in>?T"
       then obtain B where "y\<in>B" "B\<in>{B. \<exists>x\<in>S. B = ball x (d x)}" by auto
       then obtain x where "x\<in>S" and x:"y \<in> ball x (d x)" by auto
       assume "y\<in>U"
-      hence "y\<in>S" using d[OF `x\<in>S`] and x by(auto simp add: dist_sym) }
+      hence "y\<in>S" using d[OF `x\<in>S`] and x by(auto simp add: dist_commute) }
     ultimately have "S = ?T \<inter> U" by blast
     with oT have ?lhs unfolding openin_subtopology open_openin[symmetric] by blast}
   ultimately show ?thesis by blast
@@ -472,8 +488,8 @@
   let ?V = "ball y (dist x y / 2)"
   have th0: "\<And>d x y z. (d x z :: real) <= d x y + d y z \<Longrightarrow> d y z = d z y
                ==> ~(d x y * 2 < d x z \<and> d z y * 2 < d x z)" by arith
-  have "?P ?U ?V" using dist_pos_lt[OF xy] th0[of dist,OF dist_triangle dist_sym]
-    by (auto simp add: dist_refl expand_set_eq less_divide_eq_number_of1)
+  have "?P ?U ?V" using dist_pos_lt[OF xy] th0[of dist,OF dist_triangle dist_commute]
+    by (auto simp add: expand_set_eq less_divide_eq_number_of1)
   then show ?thesis by blast
 qed
 
@@ -487,8 +503,9 @@
 
 subsection{* Limit points *}
 
-definition islimpt:: "real ^'n::finite \<Rightarrow> (real^'n) set \<Rightarrow> bool" (infixr "islimpt" 60) where
-  islimpt_def: "x islimpt S \<longleftrightarrow> (\<forall>T. x\<in>T \<longrightarrow> open T \<longrightarrow> (\<exists>y\<in>S. y\<in>T \<and> y\<noteq>x))"
+definition
+  islimpt:: "'a::metric_space \<Rightarrow> 'a set \<Rightarrow> bool" (infixr "islimpt" 60) where
+  "x islimpt S \<longleftrightarrow> (\<forall>T. x\<in>T \<longrightarrow> open T \<longrightarrow> (\<exists>y\<in>S. y\<in>T \<and> y\<noteq>x))"
 
   (* FIXME: Sure this form is OK????*)
 lemma islimptE: assumes "x islimpt S" and "x \<in> T" and "open T"
@@ -500,26 +517,56 @@
   unfolding islimpt_def
   apply auto
   apply(erule_tac x="ball x e" in allE)
-  apply (auto simp add: dist_refl)
-  apply(rule_tac x=y in bexI) apply (auto simp add: dist_sym)
-  by (metis open_def dist_sym open_ball centre_in_ball mem_ball)
+  apply auto
+  apply(rule_tac x=y in bexI)
+  apply (auto simp add: dist_commute)
+  apply (simp add: open_def, drule (1) bspec)
+  apply (clarify, drule spec, drule (1) mp, auto)
+  done
 
 lemma islimpt_approachable_le: "x islimpt S \<longleftrightarrow> (\<forall>e>0. \<exists>x'\<in> S. x' \<noteq> x \<and> dist x' x <= e)"
   unfolding islimpt_approachable
   using approachable_lt_le[where f="\<lambda>x'. dist x' x" and P="\<lambda>x'. \<not> (x'\<in>S \<and> x'\<noteq>x)"]
-  by metis
-
-lemma islimpt_UNIV[simp, intro]: "(x:: real ^'n::finite) islimpt UNIV"
-proof-
+  by metis (* FIXME: VERY slow! *)
+
+axclass perfect_space \<subseteq> metric_space
+  islimpt_UNIV [simp, intro]: "x islimpt UNIV"
+
+lemma perfect_choose_dist:
+  fixes x :: "'a::perfect_space"
+  shows "0 < r \<Longrightarrow> \<exists>a. a \<noteq> x \<and> dist a x < r"
+using islimpt_UNIV [of x]
+by (simp add: islimpt_approachable)
+
+instance real :: perfect_space
+apply default
+apply (rule islimpt_approachable [THEN iffD2])
+apply (clarify, rule_tac x="x + e/2" in bexI)
+apply (auto simp add: dist_norm)
+done
+  
+instance "^" :: (perfect_space, finite) perfect_space
+proof
+  fix x :: "'a ^ 'b"
   {
-    fix e::real assume ep: "e>0"
-    from vector_choose_size[of "e/2"] ep have "\<exists>(c:: real ^'n). norm c = e/2" by auto
-    then obtain c ::"real^'n" where c: "norm c = e/2" by blast
-    let ?x = "x + c"
-    have "?x \<noteq> x" using c ep by (auto simp add: norm_eq_0_imp)
-    moreover have "dist ?x x < e" using c ep apply simp by norm
-    ultimately have "\<exists>x'. x' \<noteq> x\<and> dist x' x < e" by blast}
-  then show ?thesis unfolding islimpt_approachable by blast
+    fix e :: real assume "0 < e"
+    def a \<equiv> "x $ arbitrary"
+    have "a islimpt UNIV" by (rule islimpt_UNIV)
+    with `0 < e` obtain b where "b \<noteq> a" and "dist b a < e"
+      unfolding islimpt_approachable by auto
+    def y \<equiv> "Cart_lambda ((Cart_nth x)(arbitrary := b))"
+    from `b \<noteq> a` have "y \<noteq> x"
+      unfolding a_def y_def by (simp add: Cart_eq)
+    from `dist b a < e` have "dist y x < e"
+      unfolding dist_vector_def a_def y_def
+      apply simp
+      apply (rule le_less_trans [OF setL2_le_setsum [OF zero_le_dist]])
+      apply (subst setsum_diff1' [where a=arbitrary], simp, simp, simp)
+      done
+    from `y \<noteq> x` and `dist y x < e`
+    have "\<exists>y\<in>UNIV. y \<noteq> x \<and> dist y x < e" by auto
+  }
+  then show "x islimpt UNIV" unfolding islimpt_approachable by blast
 qed
 
 lemma closed_limpt: "closed S \<longleftrightarrow> (\<forall>x. x islimpt S \<longrightarrow> x \<in> S)"
@@ -545,13 +592,15 @@
 	apply (simp only: vector_component)
 	by (rule th') auto
       have th2: "\<bar>dist x x'\<bar> \<ge> \<bar>(x' - x)$i\<bar>" using  component_le_norm[of "x'-x" i]
-	apply (simp add: dist_def) by norm
-      from th[OF th1 th2] x'(3) have False by (simp add: dist_sym dist_pos_le) }
+	apply (simp add: dist_norm) by norm
+      from th[OF th1 th2] x'(3) have False by (simp add: dist_commute) }
   then show ?thesis unfolding closed_limpt islimpt_approachable
     unfolding not_le[symmetric] by blast
 qed
 
-lemma finite_set_avoid: assumes fS: "finite S" shows  "\<exists>d>0. \<forall>x\<in>S. x \<noteq> a \<longrightarrow> d <= dist a x"
+lemma finite_set_avoid:
+  fixes a :: "'a::metric_space"
+  assumes fS: "finite S" shows  "\<exists>d>0. \<forall>x\<in>S. x \<noteq> a \<longrightarrow> d <= dist a x"
 proof(induct rule: finite_induct[OF fS])
   case 1 thus ?case apply auto by ferrack
 next
@@ -569,7 +618,7 @@
 
 lemma islimpt_finite: assumes fS: "finite S" shows "\<not> a islimpt S"
   unfolding islimpt_approachable
-  using finite_set_avoid[OF fS, of a] by (metis dist_sym  not_le)
+  using finite_set_avoid[OF fS, of a] by (metis dist_commute  not_le)
 
 lemma islimpt_Un: "x islimpt (S \<union> T) \<longleftrightarrow> x islimpt S \<or> x islimpt T"
   apply (rule iffI)
@@ -582,7 +631,7 @@
   done
 
 lemma discrete_imp_closed:
-  assumes e: "0 < e" and d: "\<forall>x \<in> S. \<forall>y \<in> S. norm(y - x) < e \<longrightarrow> y = x"
+  assumes e: "0 < e" and d: "\<forall>x \<in> S. \<forall>y \<in> S. dist y x < e \<longrightarrow> y = x"
   shows "closed S"
 proof-
   {fix x assume C: "\<forall>e>0. \<exists>x'\<in>S. x' \<noteq> x \<and> dist x' x < e"
@@ -591,9 +640,10 @@
     let ?m = "min (e/2) (dist x y) "
     from e2 y(2) have mp: "?m > 0" by (simp add: dist_nz[THEN sym])
     from C[rule_format, OF mp] obtain z where z: "z \<in> S" "z\<noteq>x" "dist z x < ?m" by blast
-    have th: "norm (z - y) < e" using z y by norm
+    have th: "dist z y < e" using z y
+      by (intro dist_triangle_lt [where z=x], simp)
     from d[rule_format, OF y(1) z(1) th] y z
-    have False by (auto simp add: dist_sym)}
+    have False by (auto simp add: dist_commute)}
   then show ?thesis by (metis islimpt_approachable closed_limpt)
 qed
 
@@ -630,23 +680,28 @@
   apply (metis Int_lower1 Int_lower2 subset_interior)
   by (metis Int_mono interior_subset open_inter open_interior open_subset_interior)
 
-lemma interior_limit_point[intro]: assumes x: "x \<in> interior S" shows "x islimpt S"
+lemma interior_limit_point [intro]:
+  fixes x :: "'a::perfect_space"
+  assumes x: "x \<in> interior S" shows "x islimpt S"
 proof-
   from x obtain e where e: "e>0" "\<forall>x'. dist x x' < e \<longrightarrow> x' \<in> S"
     unfolding mem_interior subset_eq Ball_def mem_ball by blast
-  {fix d::real assume d: "d>0"
-    let ?m = "min d e / 2"
-    have mde2: "?m \<ge> 0" using e(1) d(1) by arith
-    from vector_choose_dist[OF mde2, of x]
-    obtain y where y: "dist x y = ?m" by blast
-    have th: "dist x y < e" "dist x y < d" unfolding y using e(1) d(1) by arith+
+  {
+    fix d::real assume d: "d>0"
+    let ?m = "min d e"
+    have mde2: "0 < ?m" using e(1) d(1) by simp
+    from perfect_choose_dist [OF mde2, of x]
+    obtain y where "y \<noteq> x" and "dist y x < ?m" by blast
+    then have "dist y x < e" "dist y x < d" by simp_all
+    from `dist y x < e` e(2) have "y \<in> S" by (simp add: dist_commute)
     have "\<exists>x'\<in>S. x'\<noteq> x \<and> dist x' x < d"
-      apply (rule bexI[where x=y])
-      using e th y by (auto simp add: dist_sym)}
+      using `y \<in> S` `y \<noteq> x` `dist y x < d` by fast
+  }
   then show ?thesis unfolding islimpt_approachable by blast
 qed
 
 lemma interior_closed_Un_empty_interior:
+  fixes S T :: "(real ^ 'n::finite) set" (* FIXME: generalize to perfect_space *)
   assumes cS: "closed S" and iT: "interior T = {}"
   shows "interior(S \<union> T) = interior S"
 proof-
@@ -657,17 +712,16 @@
     {fix y assume y: "y \<in> ball x e"
       {fix d::real assume d: "d > 0"
 	let ?k = "min d (e - dist x y)"
-	have kp: "?k > 0" using d e(1) y[unfolded mem_ball] by norm
+	have kp: "?k > 0" using d e(1) y[unfolded mem_ball] by simp
 	have "?k/2 \<ge> 0" using kp by simp
 	then obtain w where w: "dist y w = ?k/ 2" by (metis vector_choose_dist)
 	from iT[unfolded expand_set_eq mem_interior]
 	have "\<not> ball w (?k/4) \<subseteq> T" using kp by (auto simp add: less_divide_eq_number_of1)
 	then obtain z where z: "dist w z < ?k/4" "z \<notin> T" by (auto simp add: subset_eq)
 	have "z \<notin> T \<and> z\<noteq> y \<and> dist z y < d \<and> dist x z < e" using z apply simp
-	  using w e(1) d apply (auto simp only: dist_sym)
+	  using w e(1) d apply (auto simp only: dist_commute)
 	  apply (auto simp add: min_def cong del: if_weak_cong)
 	  apply (cases "d \<le> e - dist x y", auto simp add: ring_simps cong del: if_weak_cong)
-	  apply norm
 	  apply (cases "d \<le> e - dist x y", auto simp add: ring_simps not_le not_less cong del: if_weak_cong)
 	  apply norm
 	  apply norm
@@ -677,7 +731,7 @@
 	  done
 	then have "\<exists>z. z \<notin> T \<and> z\<noteq> y \<and> dist z y < d \<and> dist x z < e" by blast
 	then have "\<exists>x' \<in>S. x'\<noteq>y \<and> dist x' y < d" using e by auto}
-      then have "y\<in>S" by (metis islimpt_approachable cS closed_limpt) }
+      then have "y\<in>S" by (metis islimpt_approachable [where 'a="real^'n"] cS closed_limpt[where 'a="real^'n"]) }
     then have "x \<in> interior S" unfolding mem_interior using e(1) by blast}
   hence "interior (S\<union>T) \<subseteq> interior S" unfolding mem_interior Ball_def subset_eq by blast
   ultimately show ?thesis by blast
@@ -753,7 +807,7 @@
     with * have "closure S \<subseteq> t"
       unfolding closure_def
       using closed_limpt[of t]
-      by blast
+      by auto
   }
   ultimately show ?thesis
     using hull_unique[of S, of "closure S", of closed]
@@ -877,9 +931,9 @@
     assume "e > 0"
     let ?rhse = "(\<exists>x\<in>S. dist a x < e) \<and> (\<exists>x. x \<notin> S \<and> dist a x < e)"
     { assume "a\<in>S"
-      have "\<exists>x\<in>S. dist a x < e" using dist_refl[of a] `e>0` `a\<in>S` by(rule_tac x=a in bexI) auto
+      have "\<exists>x\<in>S. dist a x < e" using `e>0` `a\<in>S` by(rule_tac x=a in bexI) auto
       moreover have "\<exists>x. x \<notin> S \<and> dist a x < e" using `?lhs` `a\<in>S`
-	unfolding frontier_closures closure_def islimpt_def using dist_refl[of a] `e>0`
+	unfolding frontier_closures closure_def islimpt_def using `e>0`
 	by (auto, erule_tac x="ball a e" in allE, auto)
       ultimately have ?rhse by auto
     }
@@ -887,8 +941,8 @@
     { assume "a\<notin>S"
       hence ?rhse using `?lhs`
 	unfolding frontier_closures closure_def islimpt_def
-	using open_ball[of a e] dist_refl[of a] `e > 0`
-	by (auto, erule_tac x = "ball a e" in allE, auto)
+	using open_ball[of a e] `e > 0`
+	by (auto, erule_tac x = "ball a e" in allE, auto) (* FIXME: VERY slow! *)
     }
     ultimately have ?rhse by auto
   }
@@ -957,15 +1011,25 @@
 
 subsection{* Common nets and The "within" modifier for nets. *}
 
-definition "at a = mknet(\<lambda>x y. 0 < dist x a \<and> dist x a <= dist y a)"
-definition "at_infinity = mknet(\<lambda>x y. norm x \<ge> norm y)"
-definition "sequentially = mknet(\<lambda>(m::nat) n. m >= n)"
-
-definition within :: "'a net \<Rightarrow> 'a set \<Rightarrow> 'a net" (infixr "within" 70) where
-  within_def: "net within S = mknet (\<lambda>x y. netord net x y \<and> x \<in> S)"
-
-definition indirection :: "real ^'n::finite \<Rightarrow> real ^'n \<Rightarrow> (real ^'n) net" (infixr "indirection" 70) where
-  indirection_def: "a indirection v = (at a) within {b. \<exists>c\<ge>0. b - a = c*s v}"
+definition
+  at :: "'a::perfect_space \<Rightarrow> 'a net" where
+  "at a = mknet(\<lambda>x y. 0 < dist x a \<and> dist x a <= dist y a)"
+
+definition
+  at_infinity :: "'a::real_normed_vector net" where
+  "at_infinity = mknet (\<lambda>x y. norm x \<ge> norm y)"
+
+definition
+  sequentially :: "nat net" where
+  "sequentially = mknet (\<lambda>m n. n \<le> m)"
+
+definition
+  within :: "'a net \<Rightarrow> 'a set \<Rightarrow> 'a net" (infixr "within" 70) where
+  "net within S = mknet (\<lambda>x y. netord net x y \<and> x \<in> S)"
+
+definition
+  indirection :: "real ^'n::finite \<Rightarrow> real ^'n \<Rightarrow> (real ^'n) net" (infixr "indirection" 70) where
+  "a indirection v = (at a) within {b. \<exists>c\<ge>0. b - a = c*s v}"
 
 text{* Prove That They are all nets. *}
 
@@ -982,7 +1046,7 @@
 
 lemma at: "\<And>x y. netord (at a) x y \<longleftrightarrow> 0 < dist x a \<and> dist x a <= dist y a"
   apply (net at_def)
-  by (metis dist_sym real_le_linear real_le_trans)
+  by (metis dist_commute real_le_linear real_le_trans)
 
 lemma at_infinity:
  "\<And>x y. netord at_infinity x y \<longleftrightarrow> norm x >= norm y"
@@ -1008,19 +1072,22 @@
 lemma in_direction: "netord (a indirection v) x y \<longleftrightarrow> 0 < dist x a \<and> dist x a \<le> dist y a \<and> (\<exists>c \<ge> 0. x - a = c *s v)"
   by (simp add: within at indirection_def)
 
-lemma within_UNIV: "at x within UNIV = at x"
-  by (simp add: within_def at_def netord_inverse)
+lemma within_UNIV: "net within UNIV = net"
+  by (simp add: within_def netord_inverse)
 
 subsection{* Identify Trivial limits, where we can't approach arbitrarily closely. *}
 
-
-definition "trivial_limit (net:: 'a net) \<longleftrightarrow>
-  (\<forall>(a::'a) b. a = b) \<or> (\<exists>(a::'a) b. a \<noteq> b \<and> (\<forall>x. ~(netord (net) x a) \<and> ~(netord(net) x b)))"
-
-
-lemma trivial_limit_within: "trivial_limit (at (a::real^'n::finite) within S) \<longleftrightarrow> ~(a islimpt S)"
+definition
+  trivial_limit :: "'a net \<Rightarrow> bool" where
+  "trivial_limit (net:: 'a net) \<longleftrightarrow>
+    (\<forall>(a::'a) b. a = b) \<or>
+    (\<exists>(a::'a) b. a \<noteq> b \<and> (\<forall>x. ~(netord (net) x a) \<and> ~(netord(net) x b)))"
+
+lemma trivial_limit_within:
+  fixes a :: "'a::perfect_space"
+  shows "trivial_limit (at a within S) \<longleftrightarrow> \<not> a islimpt S"
 proof-
-  {assume "\<forall>(a::real^'n) b. a = b" hence "\<not> a islimpt S"
+  {assume "\<forall>(a::'a) b. a = b" hence "\<not> a islimpt S"
       apply (simp add: islimpt_approachable_le)
       by (rule exI[where x=1], auto)}
   moreover
@@ -1029,35 +1096,41 @@
     then have "\<not> a islimpt S"
       using bc
       unfolding within at dist_nz islimpt_approachable_le
-      by(auto simp add: dist_triangle dist_sym dist_eq_0[THEN sym]) }
+      by (auto simp add: dist_triangle dist_commute dist_eq_0_iff [symmetric]
+               simp del: dist_eq_0_iff) }
   moreover
   {assume "\<not> a islimpt S"
     then obtain e where e: "e > 0" "\<forall>x' \<in> S. x' \<noteq> a \<longrightarrow> dist x' a > e"
       unfolding islimpt_approachable_le by (auto simp add: not_le)
-    from e vector_choose_dist[of e a] obtain b where b: "dist a b = e" by auto
-    from b e(1) have "a \<noteq> b" by (simp add: dist_nz)
+    from e perfect_choose_dist[of e a] obtain b where b: "b \<noteq> a" "dist b a < e" by auto
+    then have "a \<noteq> b" by auto
     moreover have "\<forall>x. \<not> ((0 < dist x a \<and> dist x a \<le> dist a a) \<and> x \<in> S) \<and>
                  \<not> ((0 < dist x a \<and> dist x a \<le> dist b a) \<and> x \<in> S)"
-      using e(2) b by (auto simp add: dist_refl dist_sym)
-    ultimately have "trivial_limit (at a within S)"  unfolding trivial_limit_def within at
+      using e(2) b by (auto simp add: dist_commute)
+    ultimately have "trivial_limit (at a within S)"
+      unfolding trivial_limit_def within at
       by blast}
   ultimately show ?thesis unfolding trivial_limit_def by blast
 qed
 
-lemma trivial_limit_at: "~(trivial_limit (at a))"
-  apply (subst within_UNIV[symmetric])
-  by (simp add: trivial_limit_within islimpt_UNIV)
-
-lemma trivial_limit_at_infinity: "~(trivial_limit (at_infinity :: ('a::{norm,zero_neq_one}) net))"
+lemma trivial_limit_at: "\<not> trivial_limit (at a)"
+  using trivial_limit_within [of a UNIV]
+  by (simp add: within_UNIV)
+
+lemma trivial_limit_at_infinity:
+  "\<not> trivial_limit (at_infinity :: ('a::{real_normed_vector,zero_neq_one}) net)"
   apply (simp add: trivial_limit_def at_infinity)
   by (metis order_refl zero_neq_one)
 
-lemma trivial_limit_sequentially:  "~(trivial_limit sequentially)"
+lemma trivial_limit_sequentially: "\<not> trivial_limit sequentially"
   by (auto simp add: trivial_limit_def sequentially)
 
 subsection{* Some property holds "sufficiently close" to the limit point. *}
 
-definition "eventually P net \<longleftrightarrow> trivial_limit net \<or> (\<exists>y. (\<exists>x. netord net x y) \<and> (\<forall>x. netord net x y \<longrightarrow> P x))"
+definition
+  eventually :: "('a \<Rightarrow> bool) \<Rightarrow> 'a net \<Rightarrow> bool" where
+  "eventually P net \<longleftrightarrow> trivial_limit net \<or>
+    (\<exists>y. (\<exists>x. netord net x y) \<and> (\<forall>x. netord net x y \<longrightarrow> P x))"
 
 lemma eventually_happens: "eventually P net ==> trivial_limit net \<or> (\<exists>x. P x)"
   by (metis eventually_def)
@@ -1083,7 +1156,7 @@
     unfolding eventually_def trivial_limit_within islimpt_approachable_le within at unfolding dist_nz[THEN sym] by (clarsimp, rule_tac x=d in exI, auto)
 qed
 
-lemma eventually_within:  " eventually P (at a within S) \<longleftrightarrow>
+lemma eventually_within: "eventually P (at a within S) \<longleftrightarrow>
         (\<exists>d>0. \<forall>x\<in>S. 0 < dist x a \<and> dist x a < d \<longrightarrow> P x)"
 proof-
   { fix d
@@ -1091,7 +1164,7 @@
     hence "\<forall>x\<in>S. 0 < dist x a \<and> dist x a \<le> (d/2) \<longrightarrow> P x" using order_less_imp_le by auto
   }
   thus ?thesis unfolding eventually_within_le using approachable_lt_le
-    by (auto, rule_tac x="d/2" in exI, auto)
+    apply auto  by (rule_tac x="d/2" in exI, auto)
 qed
 
 lemma eventually_at: "eventually P (at a) \<longleftrightarrow> (\<exists>d>0. \<forall>x. 0 < dist x a \<and> dist x a < d \<longrightarrow> P x)"
@@ -1117,9 +1190,17 @@
   thus "?lhs" unfolding eventually_def at_infinity using b y by auto
 qed
 
-lemma always_eventually: "(\<forall>(x::'a::zero_neq_one). P x) ==> eventually P net"
-  apply (auto simp add: eventually_def trivial_limit_def )
-  by (rule exI[where x=0], rule exI[where x=1], rule zero_neq_one)
+lemma always_eventually: "(\<forall>x. P x) ==> eventually P net"
+  unfolding eventually_def trivial_limit_def by (clarify, simp)
+
+lemma eventually_True [simp]: "eventually (\<lambda>x. True) net"
+  by (simp add: always_eventually)
+
+lemma trivial_limit_eventually: "trivial_limit net \<Longrightarrow> eventually P net"
+  unfolding eventually_def by simp
+
+lemma trivial_limit_eq: "trivial_limit net \<longleftrightarrow> (\<forall>P. eventually P net)"
+  unfolding eventually_def trivial_limit_def by auto
 
 text{* Combining theorems for "eventually" *}
 
@@ -1142,9 +1223,24 @@
 lemma not_eventually: "(\<forall>x. \<not> P x ) \<Longrightarrow> ~(trivial_limit net) ==> ~(eventually P net)"
   by (auto simp add: eventually_def)
 
+lemma eventually_rev_mono:
+  "eventually P net \<Longrightarrow> (\<forall>x. P x \<longrightarrow> Q x) \<Longrightarrow> eventually Q net"
+using eventually_mono [of P Q] by fast
+
+lemma eventually_rev_mp:
+  assumes 1: "eventually (\<lambda>x. P x) net"
+  assumes 2: "eventually (\<lambda>x. P x \<longrightarrow> Q x) net"
+  shows "eventually (\<lambda>x. Q x) net"
+using 2 1 by (rule eventually_mp)
+
+lemma eventually_conjI:
+  "\<lbrakk>eventually (\<lambda>x. P x) net; eventually (\<lambda>x. Q x) net\<rbrakk>
+    \<Longrightarrow> eventually (\<lambda>x. P x \<and> Q x) net"
+by (simp add: eventually_and)
+
 subsection{* Limits, defined as vacuously true when the limit is trivial. *}
 
-definition tendsto:: "('a \<Rightarrow> real ^'n::finite) \<Rightarrow> real ^'n \<Rightarrow> 'a net \<Rightarrow> bool" (infixr "--->" 55) where
+definition tendsto:: "('a \<Rightarrow> 'b::metric_space) \<Rightarrow> 'b \<Rightarrow> 'a net \<Rightarrow> bool" (infixr "--->" 55) where
   tendsto_def: "(f ---> l) net  \<longleftrightarrow> (\<forall>e>0. eventually (\<lambda>x. dist (f x) l < e) net)"
 
 lemma tendstoD: "(f ---> l) net \<Longrightarrow> e>0 \<Longrightarrow> eventually (\<lambda>x. dist (f x) l < e) net"
@@ -1156,9 +1252,8 @@
 lemma Lim:
  "(f ---> l) net \<longleftrightarrow>
         trivial_limit net \<or>
-        (\<forall>e>0. \<exists>y. (\<exists>x. netord net x y) \<and>
-                           (\<forall>x. netord(net) x y \<longrightarrow> dist (f x) l < e))"
-  by (auto simp add: tendsto_def eventually_def)
+        (\<forall>e>0. eventually (\<lambda>x. dist (f x) l < e) net)"
+  unfolding tendsto_def trivial_limit_eq by auto
 
 
 text{* Show that they yield usual definitions in the various cases. *}
@@ -1175,6 +1270,9 @@
         (\<forall>e >0. \<exists>d>0. \<forall>x. 0 < dist x a  \<and> dist x a  < d  \<longrightarrow> dist (f x) l < e)"
   by (auto simp add: tendsto_def eventually_at)
 
+lemma Lim_at_iff_LIM: "(f ---> l) (at a) \<longleftrightarrow> f -- a --> l"
+  unfolding Lim_at LIM_def by (simp only: zero_less_dist_iff)
+
 lemma Lim_at_infinity:
   "(f ---> l) at_infinity \<longleftrightarrow> (\<forall>e>0. \<exists>b. \<forall>x::real^'n::finite. norm x >= b \<longrightarrow> dist (f x) l < e)"
   by (auto simp add: tendsto_def eventually_at_infinity)
@@ -1184,12 +1282,15 @@
           (\<forall>e>0. \<exists>N. \<forall>n\<ge>N. dist (S n) l < e)"
   by (auto simp add: tendsto_def eventually_sequentially)
 
+lemma Lim_sequentially_iff_LIMSEQ: "(S ---> l) sequentially \<longleftrightarrow> S ----> l"
+  unfolding Lim_sequentially LIMSEQ_def ..
+
 lemma Lim_eventually: "eventually (\<lambda>x. f x = l) net \<Longrightarrow> (f ---> l) net"
-  by (auto simp add: eventually_def Lim dist_refl)
+  unfolding tendsto_def by (auto elim: eventually_rev_mono)
 
 text{* The expected monotonicity property. *}
 
-lemma Lim_within_empty:  "(f ---> l) (at x within {})"
+lemma Lim_within_empty: "(f ---> l) (at x within {})"
   by (simp add: Lim_within_le)
 
 lemma Lim_within_subset: "(f ---> l) (at a within S) \<Longrightarrow> T \<subseteq> S \<Longrightarrow> (f ---> l) (at a within T)"
@@ -1209,7 +1310,7 @@
 qed
 
 lemma Lim_Un_univ:
- "(f ---> l) (at x within S) \<Longrightarrow> (f ---> l) (at x within T) \<Longrightarrow>  S \<union> T = (UNIV::(real^'n::finite) set)
+ "(f ---> l) (at x within S) \<Longrightarrow> (f ---> l) (at x within T) \<Longrightarrow>  S \<union> T = UNIV
         ==> (f ---> l) (at x)"
   by (metis Lim_Un within_UNIV)
 
@@ -1263,7 +1364,7 @@
   ultimately show ?rhs apply (rule_tac x="(\<lambda>n::nat. f (inverse (real n + 1)))" in exI) by auto
 next
   assume ?rhs
-  then obtain f::"nat\<Rightarrow>real^'a"  where f:"(\<forall>n. f n \<in> S - {x})" "(\<forall>e>0. \<exists>N. \<forall>n\<ge>N. dist (f n) x < e)" unfolding Lim_sequentially by auto
+  then obtain f::"nat\<Rightarrow>'a"  where f:"(\<forall>n. f n \<in> S - {x})" "(\<forall>e>0. \<exists>N. \<forall>n\<ge>N. dist (f n) x < e)" unfolding Lim_sequentially by auto
   { fix e::real assume "e>0"
     then obtain N where "dist (f N) x < e" using f(2) by auto
     moreover have "f N\<in>S" "f N \<noteq> x" using f(1) by auto
@@ -1277,44 +1378,43 @@
 lemma Lim_linear: fixes f :: "('a \<Rightarrow> real^'n::finite)" and h :: "(real^'n \<Rightarrow> real^'m::finite)"
   assumes "(f ---> l) net" "linear h"
   shows "((\<lambda>x. h (f x)) ---> h l) net"
-proof (cases "trivial_limit net")
-  case True
-  thus ?thesis unfolding tendsto_def unfolding eventually_def by auto
-next
-  case False note cas = this
-  obtain b where b: "b>0" "\<forall>x. norm (h x) \<le> b * norm x" using assms(2) using linear_bounded_pos[of h] by auto
+proof -
+  obtain b where b: "b>0" "\<forall>x. norm (h x) \<le> b * norm x"
+    using assms(2) using linear_bounded_pos[of h] by auto
   { fix e::real assume "e >0"
     hence "e/b > 0" using `b>0` by (metis divide_pos_pos)
-    then have "(\<exists>y. (\<exists>x. netord net x y) \<and> (\<forall>x. netord net x y \<longrightarrow> dist (f x) l < e/b))" using assms `e>0` cas
-      unfolding tendsto_def unfolding eventually_def by auto
-    then obtain y where y: "\<exists>x. netord net x y" "\<forall>x. netord net x y \<longrightarrow> dist (f x) l < e/b" by auto
-    { fix x
-      have "netord net x y \<longrightarrow> dist (h (f x)) (h l) < e"
-	using y(2) b unfolding dist_def	using linear_sub[of h "f x" l] `linear h`
-	apply auto by (metis b(1) b(2) dist_def dist_sym less_le_not_le linorder_not_le mult_imp_div_pos_le real_mult_commute xt1(7))
-    }
-    hence " (\<exists>y. (\<exists>x. netord net x y) \<and> (\<forall>x. netord net x y \<longrightarrow> dist (h (f x)) (h l) < e))" using y
-      by(rule_tac x="y" in exI) auto
+    with `(f ---> l) net` have "eventually (\<lambda>x. dist (f x) l < e/b) net"
+      by (rule tendstoD)
+    then have "eventually (\<lambda>x. dist (h (f x)) (h l) < e) net"
+      apply (rule eventually_rev_mono [rule_format])
+      apply (simp add: dist_norm linear_sub [OF `linear h`, symmetric])
+      apply (rule le_less_trans [OF b(2) [rule_format]])
+      apply (simp add: pos_less_divide_eq `0 < b` mult_commute)
+      done
   }
-  thus ?thesis unfolding tendsto_def eventually_def using `b>0` by auto
+  thus ?thesis unfolding tendsto_def by simp
 qed
 
 lemma Lim_const: "((\<lambda>x. a) ---> a) net"
-  by (auto simp add: Lim dist_refl trivial_limit_def)
-
-lemma Lim_cmul: "(f ---> l) net ==> ((\<lambda>x. c *s f x) ---> c *s l) net"
+  by (auto simp add: Lim trivial_limit_def)
+
+lemma Lim_cmul:
+  fixes f :: "'a \<Rightarrow> real ^ 'n::finite"
+  shows "(f ---> l) net ==> ((\<lambda>x. c *s f x) ---> c *s l) net"
   apply (rule Lim_linear[where f = f])
   apply simp
   apply (rule linear_compose_cmul)
   apply (rule linear_id[unfolded id_def])
   done
 
-lemma Lim_neg: "(f ---> l) net ==> ((\<lambda>x. -(f x)) ---> -l) net"
-  apply (simp add: Lim dist_def  group_simps)
+lemma Lim_neg:
+  fixes f :: "'a \<Rightarrow> 'b::real_normed_vector"
+  shows "(f ---> l) net ==> ((\<lambda>x. -(f x)) ---> -l) net"
+  apply (simp add: Lim dist_norm  group_simps)
   apply (subst minus_diff_eq[symmetric])
   unfolding norm_minus_cancel by simp
 
-lemma Lim_add: fixes f :: "'a \<Rightarrow> real^'n::finite" shows
+lemma Lim_add: fixes f :: "'a \<Rightarrow> 'b::real_normed_vector" shows
  "(f ---> l) net \<Longrightarrow> (g ---> m) net \<Longrightarrow> ((\<lambda>x. f(x) + g(x)) ---> l + m) net"
 proof-
   assume as:"(f ---> l) net" "(g ---> m) net"
@@ -1324,34 +1424,32 @@
             "eventually (\<lambda>x. dist (g x) m < e/2) net" using as
       by (auto intro: tendstoD simp del: less_divide_eq_number_of1)
     hence "eventually (\<lambda>x. dist (f x + g x) (l + m) < e) net"
-    proof(cases "trivial_limit net")
-      case True
-      thus ?thesis unfolding eventually_def by auto
-    next
-      case False
-      hence fl:"(\<exists>y. (\<exists>x. netord net x y) \<and> (\<forall>x. netord net x y \<longrightarrow> dist (f x) l < e / 2))" and
-	    gl:"(\<exists>y. (\<exists>x. netord net x y) \<and> (\<forall>x. netord net x y \<longrightarrow> dist (g x) m < e / 2))"
-	using * unfolding eventually_def by auto
-      obtain c where c:"(\<exists>x. netord net x c)" "(\<forall>x. netord net x c \<longrightarrow> dist (f x) l < e / 2 \<and> dist (g x) m < e / 2)"
-	using net_dilemma[of net, OF fl gl] by auto
-      { fix x assume "netord net x c"
-	with c(2) have " dist (f x + g x) (l + m) < e" using dist_triangle_add[of "f x" "g x" l m] by auto
-      }
-      with c show ?thesis unfolding eventually_def by auto
-    qed
+      apply (elim eventually_rev_mp)
+      apply (rule always_eventually, clarify)
+      apply (rule le_less_trans [OF dist_triangle_add])
+      apply simp
+      done
   }
-  thus ?thesis unfolding tendsto_def by auto
-qed
-
-lemma Lim_sub: "(f ---> l) net \<Longrightarrow> (g ---> m) net \<Longrightarrow> ((\<lambda>x. f(x) - g(x)) ---> l - m) net"
+  thus ?thesis unfolding tendsto_def by simp
+qed
+
+lemma Lim_sub:
+  fixes f :: "'a \<Rightarrow> 'b::real_normed_vector"
+  shows "(f ---> l) net \<Longrightarrow> (g ---> m) net \<Longrightarrow> ((\<lambda>x. f(x) - g(x)) ---> l - m) net"
   unfolding diff_minus
   by (simp add: Lim_add Lim_neg)
 
-lemma Lim_null: "(f ---> l) net \<longleftrightarrow> ((\<lambda>x. f(x) - l) ---> 0) net" by (simp add: Lim dist_def)
-lemma Lim_null_norm: "(f ---> 0) net \<longleftrightarrow> ((\<lambda>x. vec1(norm(f x))) ---> 0) net"
-  by (simp add: Lim dist_def norm_vec1)
+lemma Lim_null:
+  fixes f :: "'a \<Rightarrow> 'b::real_normed_vector"
+  shows "(f ---> l) net \<longleftrightarrow> ((\<lambda>x. f(x) - l) ---> 0) net" by (simp add: Lim dist_norm)
+
+lemma Lim_null_norm:
+  fixes f :: "'a \<Rightarrow> 'b::real_normed_vector"
+  shows "(f ---> 0) net \<longleftrightarrow> ((\<lambda>x. vec1(norm(f x))) ---> 0) net"
+  by (simp add: Lim dist_norm norm_vec1)
 
 lemma Lim_null_comparison:
+  fixes f :: "'a \<Rightarrow> 'b::real_normed_vector"
   assumes "eventually (\<lambda>x. norm(f x) <= g x) net" "((\<lambda>x. vec1(g x)) ---> 0) net"
   shows "(f ---> 0) net"
 proof(simp add: tendsto_def, rule+)
@@ -1359,7 +1457,7 @@
   { fix x
     assume "norm (f x) \<le> g x" "dist (vec1 (g x)) 0 < e"
     hence "dist (f x) 0 < e"  unfolding vec_def using dist_vec1[of "g x" "0"]
-      by (vector dist_def norm_vec1 dist_refl real_vector_norm_def dot_def vec1_def)
+      by (vector dist_norm norm_vec1 real_vector_norm_def dot_def vec1_def)
   }
   thus "eventually (\<lambda>x. dist (f x) 0 < e) net"
     using eventually_and[of "\<lambda>x. norm(f x) <= g x" "\<lambda>x. dist (vec1 (g x)) 0 < e" net]
@@ -1369,24 +1467,27 @@
 
 lemma Lim_component: "(f ---> l) net
                       ==> ((\<lambda>a. vec1((f a :: real ^'n::finite)$i)) ---> vec1(l$i)) net"
-  apply (simp add: Lim dist_def vec1_sub[symmetric] norm_vec1  vector_minus_component[symmetric] del: vector_minus_component)
+  unfolding tendsto_def
+  apply (simp add: dist_norm vec1_sub[symmetric] norm_vec1  vector_minus_component[symmetric] del: vector_minus_component)
   apply (auto simp del: vector_minus_component)
   apply (erule_tac x=e in allE)
   apply clarify
-  apply (rule_tac x=y in exI)
+  apply (erule eventually_rev_mono)
   apply (auto simp del: vector_minus_component)
   apply (rule order_le_less_trans)
   apply (rule component_le_norm)
   by auto
 
 lemma Lim_transform_bound:
+  fixes f :: "'a \<Rightarrow> 'b::real_normed_vector"
+  fixes g :: "'a \<Rightarrow> 'c::real_normed_vector"
   assumes "eventually (\<lambda>n. norm(f n) <= norm(g n)) net"  "(g ---> 0) net"
   shows "(f ---> 0) net"
 proof(simp add: tendsto_def, rule+)
   fix e::real assume "e>0"
   { fix x
     assume "norm (f x) \<le> norm (g x)" "dist (g x) 0 < e"
-    hence "dist (f x) 0 < e" by norm}
+    hence "dist (f x) 0 < e" by (simp add: dist_norm)}
   thus "eventually (\<lambda>x. dist (f x) 0 < e) net"
     using eventually_and[of "\<lambda>x. norm (f x) \<le> norm (g x)" "\<lambda>x. dist (g x) 0 < e" net]
     using eventually_mono[of "\<lambda>x. norm (f x) \<le> norm (g x) \<and> dist (g x) 0 < e" "\<lambda>x. dist (f x) 0 < e" net]
@@ -1398,52 +1499,57 @@
 lemma Lim_in_closed_set:
   assumes "closed S" "eventually (\<lambda>x. f(x) \<in> S) net"  "\<not>(trivial_limit net)" "(f ---> l) net"
   shows "l \<in> S"
-proof-
-  { assume "l \<notin> S"
-    obtain e where e:"e>0" "ball l e \<subseteq> UNIV - S" using assms(1) `l \<notin> S` unfolding closed_def open_contains_ball by auto
-    hence *:"\<forall>x. dist l x < e \<longrightarrow> x \<notin> S" by auto
-    obtain y where "(\<exists>x. netord net x y) \<and> (\<forall>x. netord net x y \<longrightarrow> dist (f x) l < e)"
-      using assms(3,4) `e>0` unfolding tendsto_def eventually_def by blast
-    hence "(\<exists>x. netord net x y) \<and> (\<forall>x. netord net x y \<longrightarrow> f x \<notin> S)"  using * by (auto simp add: dist_sym)
-    hence False using assms(2,3)
-      using eventually_and[of "(\<lambda>x. f x \<in> S)" "(\<lambda>x. f x \<notin> S)"] not_eventually[of "(\<lambda>x. f x \<in> S \<and> f x \<notin> S)" net]
-      unfolding eventually_def by blast
-  }
-  thus ?thesis by blast
+proof (rule ccontr)
+  assume "l \<notin> S"
+  obtain e where e:"e>0" "ball l e \<subseteq> UNIV - S" using assms(1) `l \<notin> S` unfolding closed_def open_contains_ball by auto
+  hence *:"\<forall>x. dist l x < e \<longrightarrow> x \<notin> S" by auto
+  have "eventually (\<lambda>x. dist (f x) l < e) net"
+    using assms(4) `e>0` by (rule tendstoD)
+  with assms(2) have "eventually (\<lambda>x. f x \<in> S \<and> dist (f x) l < e) net"
+    by (rule eventually_conjI)
+  then obtain x where "f x \<in> S" "dist (f x) l < e"
+    using assms(3) eventually_happens by auto
+  with * show "False" by (simp add: dist_commute)
 qed
 
 text{* Need to prove closed(cball(x,e)) before deducing this as a corollary. *}
 
 lemma Lim_norm_ubound:
+  fixes f :: "'a \<Rightarrow> 'b::real_normed_vector"
   assumes "\<not>(trivial_limit net)" "(f ---> l) net" "eventually (\<lambda>x. norm(f x) <= e) net"
   shows "norm(l) <= e"
-proof-
-  obtain y where y: "\<exists>x. netord net x y"  "\<forall>x. netord net x y \<longrightarrow> norm (f x) \<le> e" using assms(1,3) unfolding eventually_def by auto
-  show ?thesis
-  proof(rule ccontr)
-    assume "\<not> norm l \<le> e"
-    then obtain z where z: "\<exists>x. netord net x z"  "\<forall>x. netord net x z \<longrightarrow> dist (f x) l < norm l - e"
-      using assms(2)[unfolded Lim] using assms(1) apply simp apply(erule_tac x="norm l - e" in allE) by auto
-    obtain w where w:"netord net w z"  "netord net w y" using net[of net] using z(1) y(1) by blast
-    hence "dist (f w) l < norm l - e \<and> norm (f w) <= e" using z(2) y(2) by auto
-    thus False using `\<not> norm l \<le> e` by norm
-  qed
+proof (rule ccontr)
+  assume "\<not> norm l \<le> e"
+  then have "0 < norm l - e" by simp
+  with assms(2) have "eventually (\<lambda>x. dist (f x) l < norm l - e) net"
+    by (rule tendstoD)
+  with assms(3) have "eventually (\<lambda>x. norm (f x) \<le> e \<and> dist (f x) l < norm l - e) net"
+    by (rule eventually_conjI)
+  then obtain w where "norm (f w) \<le> e" "dist (f w) l < norm l - e"
+    using assms(1) eventually_happens by auto
+  hence "norm (f w - l) < norm l - e" "norm (f w) \<le> e" by (simp_all add: dist_norm)
+  hence "norm (f w - l) + norm (f w) < norm l" by simp
+  hence "norm (f w - l - f w) < norm l" by (rule le_less_trans [OF norm_triangle_ineq4])
+  thus False using `\<not> norm l \<le> e` by simp
 qed
 
 lemma Lim_norm_lbound:
+  fixes f :: "'a \<Rightarrow> 'b::real_normed_vector"
   assumes "\<not> (trivial_limit net)"  "(f ---> l) net"  "eventually (\<lambda>x. e <= norm(f x)) net"
   shows "e \<le> norm l"
-proof-
-  obtain y where y: "\<exists>x. netord net x y"  "\<forall>x. netord net x y \<longrightarrow> e \<le> norm (f x)" using assms(1,3) unfolding eventually_def by auto
-  show ?thesis
-  proof(rule ccontr)
-    assume "\<not> e \<le> norm l"
-    then obtain z where z: "\<exists>x. netord net x z"  "\<forall>x. netord net x z \<longrightarrow> dist (f x) l < e - norm l"
-      using assms(2)[unfolded Lim] using assms(1) apply simp apply(erule_tac x="e - norm l" in allE) by auto
-    obtain w where w:"netord net w z"  "netord net w y" using net[of net] using z(1) y(1) by blast
-    hence "dist (f w) l < e - norm l \<and> e \<le> norm (f w)" using z(2) y(2) by auto
-    thus False using `\<not> e \<le> norm l` by norm
-  qed
+proof (rule ccontr)
+  assume "\<not> e \<le> norm l"
+  then have "0 < e - norm l" by simp
+  with assms(2) have "eventually (\<lambda>x. dist (f x) l < e - norm l) net"
+    by (rule tendstoD)
+  with assms(3) have "eventually (\<lambda>x. e \<le> norm (f x) \<and> dist (f x) l < e - norm l) net"
+    by (rule eventually_conjI)
+  then obtain w where "e \<le> norm (f w)" "dist (f w) l < e - norm l"
+    using assms(1) eventually_happens by auto
+  hence "norm (f w - l) + norm l < e" "e \<le> norm (f w)" by (simp_all add: dist_norm)
+  hence "norm (f w - l) + norm l < norm (f w)" by (rule less_le_trans)
+  hence "norm (f w - l + l) < norm (f w)" by (rule le_less_trans [OF norm_triangle_ineq])
+  thus False by simp
 qed
 
 text{* Uniqueness of the limit, when nontrivial. *}
@@ -1460,12 +1566,13 @@
   { assume "norm (l - l') > 0"
     hence "norm (l - l') = 0" using *[of "(norm (l - l')) /2"] using norm_ge_zero[of "l - l'"] by simp
   }
-  hence "l = l'" using norm_ge_zero[of "l - l'"] unfolding le_less and dist_nz[of l l', unfolded dist_def, THEN sym] by auto
+  hence "l = l'" using norm_ge_zero[of "l - l'"] unfolding le_less and dist_nz[of l l', unfolded dist_norm, THEN sym] by auto
   thus ?thesis using assms using Lim_sub[of f l net f l'] by simp
 qed
 
 lemma tendsto_Lim:
- "~(trivial_limit (net::('b::zero_neq_one net))) \<Longrightarrow> (f ---> l) net ==> Lim net f = l"
+  fixes f :: "'a::zero_neq_one \<Rightarrow> real ^ 'n::finite"
+  shows "~(trivial_limit net) \<Longrightarrow> (f ---> l) net ==> Lim net f = l"
   unfolding Lim_def using Lim_unique[of net f] by auto
 
 text{* Limit under bilinear function (surprisingly tedious, but important) *}
@@ -1504,10 +1611,7 @@
   fixes net :: "'a net" and h:: "real ^'m::finite \<Rightarrow> real ^'n::finite \<Rightarrow> real ^'p::finite"
   assumes "(f ---> l) net" and "(g ---> m) net" and "bilinear h"
   shows "((\<lambda>x. h (f x) (g x)) ---> (h l m)) net"
-proof(cases "trivial_limit net")
-  case True thus "((\<lambda>x. h (f x) (g x)) ---> h l m) net" unfolding Lim ..
-next
-  case False note ntriv = this
+proof -
   obtain B where "B>0" and B:"\<forall>x y. norm (h x y) \<le> B * norm x * norm y" using bilinear_bounded_pos[OF assms(3)] by auto
   { fix e::real assume "e>0"
     obtain d where "d>0" and d:"\<forall>x' y'. norm (x' - l) < d \<and> norm (y' - m) < d \<longrightarrow> norm x' * norm (y' - m) + norm (x' - l) * norm m < e / B" using `B>0` `e>0`
@@ -1517,20 +1621,29 @@
       unfolding bilinear_rsub[OF assms(3)]
       unfolding bilinear_lsub[OF assms(3)] by auto
 
+    have "eventually (\<lambda>x. dist (f x) l < d) net"
+      using assms(1) `d>0` by (rule tendstoD)
+    moreover
+    have "eventually (\<lambda>x. dist (g x) m < d) net"
+      using assms(2) `d>0` by (rule tendstoD)
+    ultimately
+    have "eventually (\<lambda>x. dist (f x) l < d \<and> dist (g x) m < d) net"
+      by (rule eventually_conjI)
+    moreover
     { fix x assume "dist (f x) l < d \<and> dist (g x) m < d"
       hence **:"norm (f x) * norm (g x - m) + norm (f x - l) * norm m < e / B"
-	using d[THEN spec[where x="f x"], THEN spec[where x="g x"]] unfolding dist_def  by auto
+	using d[THEN spec[where x="f x"], THEN spec[where x="g x"]] unfolding dist_norm  by auto
       have "norm (h (f x) (g x - m)) + norm (h (f x - l) m) \<le> B * norm (f x) * norm (g x - m) + B * norm (f x - l) * norm m"
 	using B[THEN spec[where x="f x"], THEN spec[where x="g x - m"]]
 	using B[THEN spec[where x="f x - l"], THEN spec[where x="m"]] by auto
       also have "\<dots> < e" using ** and `B>0` by(auto simp add: field_simps)
-      finally have "dist (h (f x) (g x)) (h l m) < e" unfolding dist_def and * using norm_triangle_lt by auto
+      finally have "dist (h (f x) (g x)) (h l m) < e" unfolding dist_norm and * using norm_triangle_lt by auto
     }
-    moreover
-    obtain c where "(\<exists>x. netord net x c) \<and> (\<forall>x. netord net x c \<longrightarrow> dist (f x) l < d \<and> dist (g x) m < d)"
-      using net_dilemma[of net "\<lambda>x. dist (f x) l < d" "\<lambda>x. dist (g x) m < d"] using assms(1,2) unfolding Lim using False and `d>0` by (auto elim!: allE[where x=d])
-    ultimately have "\<exists>y. (\<exists>x. netord net x y) \<and> (\<forall>x. netord net x y \<longrightarrow> dist (h (f x) (g x)) (h l m) < e)" by auto  }
-  thus "((\<lambda>x. h (f x) (g x)) ---> h l m) net" unfolding Lim by auto
+    ultimately have "eventually (\<lambda>x. dist (h (f x) (g x)) (h l m) < e) net"
+      by (auto elim: eventually_rev_mono)
+  }
+  thus "((\<lambda>x. h (f x) (g x)) ---> h l m) net"
+    unfolding tendsto_def by simp
 qed
 
 text{* These are special for limits out of the same vector space. *}
@@ -1539,14 +1652,16 @@
 lemma Lim_at_id: "(id ---> a) (at a)"
 apply (subst within_UNIV[symmetric]) by (simp add: Lim_within_id)
 
-lemma Lim_at_zero: "(f ---> l) (at (a::real^'a::finite)) \<longleftrightarrow> ((\<lambda>x. f(a + x)) ---> l) (at 0)" (is "?lhs = ?rhs")
+lemma Lim_at_zero:
+  fixes a :: "'a::{real_normed_vector, perfect_space}"
+  shows "(f ---> l) (at a) \<longleftrightarrow> ((\<lambda>x. f(a + x)) ---> l) (at 0)" (is "?lhs = ?rhs")
 proof
   assume "?lhs"
   { fix e::real assume "e>0"
     with `?lhs` obtain d where d:"d>0" "\<forall>x. 0 < dist x a \<and> dist x a < d \<longrightarrow> dist (f x) l < e" unfolding Lim_at by auto
-    { fix x::"real^'a" assume "0 < dist x 0 \<and> dist x 0 < d"
+    { fix x::"'a" assume "0 < dist x 0 \<and> dist x 0 < d"
       hence "dist (f (a + x)) l < e" using d
-      apply(erule_tac x="x+a" in allE) by(auto simp add: comm_monoid_add.mult_commute dist_def dist_sym)
+      apply(erule_tac x="x+a" in allE) by(auto simp add: comm_monoid_add.mult_commute dist_norm dist_commute)
     }
     hence "\<exists>d>0. \<forall>x. 0 < dist x 0 \<and> dist x 0 < d \<longrightarrow> dist (f (a + x)) l < e" using d(1) by auto
   }
@@ -1556,9 +1671,9 @@
   { fix e::real assume "e>0"
     with `?rhs` obtain d where d:"d>0" "\<forall>x. 0 < dist x 0 \<and> dist x 0 < d \<longrightarrow> dist (f (a + x)) l < e"
       unfolding Lim_at by auto
-    { fix x::"real^'a" assume "0 < dist x a \<and> dist x a < d"
+    { fix x::"'a" assume "0 < dist x a \<and> dist x a < d"
       hence "dist (f x) l < e" using d apply(erule_tac x="x-a" in allE)
-	by(auto simp add: comm_monoid_add.mult_commute dist_def dist_sym)
+	by(auto simp add: comm_monoid_add.mult_commute dist_norm dist_commute)
     }
     hence "\<exists>d>0. \<forall>x. 0 < dist x a \<and> dist x a < d \<longrightarrow> dist (f x) l < e" using d(1) by auto
   }
@@ -1575,31 +1690,38 @@
   { fix x assume "x \<noteq> a"
     then obtain y where y:"dist y a \<le> dist a a \<and> 0 < dist y a \<and> y \<in> S \<or> dist y a \<le> dist x a \<and> 0 < dist y a \<and> y \<in> S" using assms unfolding trivial_limit_def within at by blast
     assume "\<forall>y. \<not> netord (at a within S) y x"
-    hence "x = a" using y unfolding within at by (auto simp add: dist_refl dist_nz)
+    hence "x = a" using y unfolding within at by (auto simp add: dist_nz)
   }
   moreover
-  have "\<forall>y. \<not> netord (at a within S) y a"  using assms unfolding trivial_limit_def within at by (auto simp add: dist_refl)
+  have "\<forall>y. \<not> netord (at a within S) y a"  using assms unfolding trivial_limit_def within at by auto
   ultimately show ?thesis unfolding netlimit_def using some_equality[of "\<lambda>x. \<forall>y. \<not> netord (at a within S) y x"] by blast
 qed
 
-lemma netlimit_at: "netlimit(at a) = a"
+lemma netlimit_at: "netlimit (at a) = a"
   apply (subst within_UNIV[symmetric])
   using netlimit_within[of a UNIV]
   by (simp add: trivial_limit_at within_UNIV)
 
 text{* Transformation of limit. *}
 
-lemma Lim_transform: assumes "((\<lambda>x. f x - g x) ---> 0) net" "(f ---> l) net"
+lemma Lim_transform:
+  fixes f g :: "'a::type \<Rightarrow> 'b::real_normed_vector"
+  assumes "((\<lambda>x. f x - g x) ---> 0) net" "(f ---> l) net"
   shows "(g ---> l) net"
 proof-
   from assms have "((\<lambda>x. f x - g x - f x) ---> 0 - l) net" using Lim_sub[of "\<lambda>x. f x - g x" 0 net f l] by auto
   thus "?thesis" using Lim_neg [of "\<lambda> x. - g x" "-l" net] by auto
 qed
 
-lemma Lim_transform_eventually:  "eventually (\<lambda>x. f x = g x) net \<Longrightarrow> (f ---> l) net ==> (g ---> l) net"
+lemma Lim_transform_eventually:
+  fixes f g :: "'a::type \<Rightarrow> 'b::real_normed_vector"
+    (* FIXME: generalize to metric_space *)
+  shows "eventually (\<lambda>x. f x = g x) net \<Longrightarrow> (f ---> l) net ==> (g ---> l) net"
   using Lim_eventually[of "\<lambda>x. f x - g x" 0 net] Lim_transform[of f g net l] by auto
 
 lemma Lim_transform_within:
+  fixes f g :: "'a::perfect_space \<Rightarrow> 'b::real_normed_vector"
+    (* FIXME: generalize to metric_space *)
   assumes "0 < d" "(\<forall>x'\<in>S. 0 < dist x' x \<and> dist x' x < d \<longrightarrow> f x' = g x')"
           "(f ---> l) (at x within S)"
   shows   "(g ---> l) (at x within S)"
@@ -1608,7 +1730,10 @@
   thus ?thesis using Lim_transform[of f g "at x within S" l] using assms(3) by auto
 qed
 
-lemma Lim_transform_at: "0 < d \<Longrightarrow> (\<forall>x'. 0 < dist x' x \<and> dist x' x < d \<longrightarrow> f x' = g x') \<Longrightarrow>
+lemma Lim_transform_at:
+  fixes f g :: "'a::perfect_space \<Rightarrow> 'b::real_normed_vector"
+    (* FIXME: generalize to metric_space *)
+  shows "0 < d \<Longrightarrow> (\<forall>x'. 0 < dist x' x \<and> dist x' x < d \<longrightarrow> f x' = g x') \<Longrightarrow>
   (f ---> l) (at x) ==> (g ---> l) (at x)"
   apply (subst within_UNIV[symmetric])
   using Lim_transform_within[of d UNIV x f g l]
@@ -1617,18 +1742,20 @@
 text{* Common case assuming being away from some crucial point like 0. *}
 
 lemma Lim_transform_away_within:
-  fixes f:: "real ^'m::finite \<Rightarrow> real ^'n::finite"
+  fixes f:: "'a::perfect_space \<Rightarrow> 'b::real_normed_vector"
+    (* FIXME: generalize to metric_space *)
   assumes "a\<noteq>b" "\<forall>x\<in> S. x \<noteq> a \<and> x \<noteq> b \<longrightarrow> f x = g x"
   and "(f ---> l) (at a within S)"
   shows "(g ---> l) (at a within S)"
 proof-
   have "\<forall>x'\<in>S. 0 < dist x' a \<and> dist x' a < dist a b \<longrightarrow> f x' = g x'" using assms(2)
-    apply auto apply(erule_tac x=x' in ballE) by (auto simp add: dist_sym dist_refl)
+    apply auto apply(erule_tac x=x' in ballE) by (auto simp add: dist_commute)
   thus ?thesis using Lim_transform_within[of "dist a b" S a f g l] using assms(1,3) unfolding dist_nz by auto
 qed
 
 lemma Lim_transform_away_at:
-  fixes f:: "real ^'m::finite \<Rightarrow> real ^'n::finite"
+  fixes f:: "'a::perfect_space \<Rightarrow> 'b::real_normed_vector"
+    (* FIXME: generalize to metric_space *)
   assumes ab: "a\<noteq>b" and fg: "\<forall>x. x \<noteq> a \<and> x \<noteq> b \<longrightarrow> f x = g x"
   and fl: "(f ---> l) (at a)"
   shows "(g ---> l) (at a)"
@@ -1638,13 +1765,14 @@
 text{* Alternatively, within an open set. *}
 
 lemma Lim_transform_within_open:
-  fixes f:: "real ^'m::finite \<Rightarrow> real ^'n::finite"
+  fixes f:: "'a::perfect_space \<Rightarrow> 'b::real_normed_vector"
+    (* FIXME: generalize to metric_space *)
   assumes "open S"  "a \<in> S"  "\<forall>x\<in>S. x \<noteq> a \<longrightarrow> f x = g x"  "(f ---> l) (at a)"
   shows "(g ---> l) (at a)"
 proof-
   from assms(1,2) obtain e::real where "e>0" and e:"ball a e \<subseteq> S" unfolding open_contains_ball by auto
   hence "\<forall>x'. 0 < dist x' a \<and> dist x' a < e \<longrightarrow> f x' = g x'" using assms(3)
-    unfolding ball_def subset_eq apply auto apply(erule_tac x=x' in allE) apply(erule_tac x=x' in ballE) by(auto simp add: dist_refl dist_sym)
+    unfolding ball_def subset_eq apply auto apply(erule_tac x=x' in allE) apply(erule_tac x=x' in ballE) by(auto simp add: dist_commute)
   thus ?thesis using Lim_transform_at[of e a f g l] `e>0` assms(4) by auto
 qed
 
@@ -1683,7 +1811,7 @@
 
 lemma closure_approachable: "x \<in> closure S \<longleftrightarrow> (\<forall>e>0. \<exists>y\<in>S. dist y x < e)"
   apply (auto simp add: closure_def islimpt_approachable)
-  by (metis dist_refl)
+  by (metis dist_self)
 
 lemma closed_approachable: "closed S ==> (\<forall>e>0. \<exists>y\<in>S. dist y x < e) \<longleftrightarrow> x \<in> S"
   by (metis closure_closed closure_approachable)
@@ -1712,18 +1840,20 @@
       using real_arch_inv[of e] apply auto apply(rule_tac x=n in exI)
       by (metis dlo_simps(4) le_imp_inverse_le linorder_not_less real_of_nat_gt_zero_cancel_iff real_of_nat_less_iff xt1(7))
   }
-  thus ?thesis unfolding Lim_sequentially dist_def apply simp unfolding norm_vec1 by auto
+  thus ?thesis unfolding Lim_sequentially dist_norm apply simp unfolding norm_vec1 by auto
 qed
 
 text{* More properties of closed balls. *}
 
-lemma closed_cball: "closed(cball x e)"
+lemma closed_cball:
+  fixes x :: "'a::real_normed_vector" (* FIXME: generalize to metric_space *)
+  shows "closed (cball x e)"
 proof-
-  { fix xa::"nat\<Rightarrow>real^'a" and l assume as: "\<forall>n. dist x (xa n) \<le> e" "(xa ---> l) sequentially"
+  { fix xa::"nat\<Rightarrow>'a" and l assume as: "\<forall>n. dist x (xa n) \<le> e" "(xa ---> l) sequentially"
     from as(2) have "((\<lambda>n. x - xa n) ---> x - l) sequentially" using Lim_sub[of "\<lambda>n. x" x sequentially xa l] Lim_const[of x sequentially] by auto
-    moreover from as(1) have "eventually (\<lambda>n. norm (x - xa n) \<le> e) sequentially" unfolding eventually_sequentially dist_def by auto
+    moreover from as(1) have "eventually (\<lambda>n. norm (x - xa n) \<le> e) sequentially" unfolding eventually_sequentially dist_norm by auto
     ultimately have "dist x l \<le> e"
-      unfolding dist_def
+      unfolding dist_norm
       using Lim_norm_ubound[of sequentially _ "x - l" e] using trivial_limit_sequentially by auto
   }
   thus ?thesis unfolding closed_sequential_limits by auto
@@ -1744,10 +1874,16 @@
   by (metis open_contains_cball subset_eq order_less_imp_le centre_in_cball mem_def)
 
 lemma mem_interior_cball: "x \<in> interior S \<longleftrightarrow> (\<exists>e>0. cball x e \<subseteq> S)"
-  apply (simp add: interior_def)
-  by (metis open_contains_cball subset_trans ball_subset_cball centre_in_ball open_ball)
-
-lemma islimpt_ball: "y islimpt ball x e \<longleftrightarrow> 0 < e \<and> y \<in> cball x e" (is "?lhs = ?rhs")
+  apply (simp add: interior_def, safe)
+  apply (force simp add: open_contains_cball)
+  apply (rule_tac x="ball x e" in exI)
+  apply (simp add: open_ball centre_in_ball subset_trans [OF ball_subset_cball])
+  done
+
+lemma islimpt_ball:
+  fixes x y :: "'a::{real_normed_vector,perfect_space}"
+    (* FIXME: generalize to metric_space *)
+  shows "y islimpt ball x e \<longleftrightarrow> 0 < e \<and> y \<in> cball x e" (is "?lhs = ?rhs")
 proof
   assume "?lhs"
   { assume "e \<le> 0"
@@ -1765,61 +1901,69 @@
     proof(cases "d \<le> dist x y")
       case True thus "\<exists>x'\<in>ball x e. x' \<noteq> y \<and> dist x' y < d"
       proof(cases "x=y")
-	case True hence False using `d \<le> dist x y` `d>0` dist_refl[of x] by auto
+	case True hence False using `d \<le> dist x y` `d>0` by auto
 	thus "\<exists>x'\<in>ball x e. x' \<noteq> y \<and> dist x' y < d" by auto
       next
 	case False
 
-	have "dist x (y - (d / (2 * dist y x)) *s (y - x))
-	      = norm (x - y + (d / (2 * norm (y - x))) *s (y - x))"
-	  unfolding mem_cball mem_ball dist_def diff_diff_eq2 diff_add_eq[THEN sym] by auto
+	have "dist x (y - (d / (2 * dist y x)) *\<^sub>R (y - x))
+	      = norm (x - y + (d / (2 * norm (y - x))) *\<^sub>R (y - x))"
+	  unfolding mem_cball mem_ball dist_norm diff_diff_eq2 diff_add_eq[THEN sym] by auto
 	also have "\<dots> = \<bar>- 1 + d / (2 * norm (x - y))\<bar> * norm (x - y)"
-	  using vector_sadd_rdistrib[of "- 1" "d / (2 * norm (y - x))", THEN sym, of "y - x"]
-	  unfolding vector_smult_lneg vector_smult_lid
-	  by (auto simp add: dist_sym[unfolded dist_def] norm_mul)
+	  using scaleR_left_distrib[of "- 1" "d / (2 * norm (y - x))", THEN sym, of "y - x"]
+	  unfolding scaleR_minus_left scaleR_one
+	  by (auto simp add: norm_minus_commute norm_scaleR)
 	also have "\<dots> = \<bar>- norm (x - y) + d / 2\<bar>"
 	  unfolding abs_mult_pos[of "norm (x - y)", OF norm_ge_zero[of "x - y"]]
-	  unfolding real_add_mult_distrib using `x\<noteq>y`[unfolded dist_nz, unfolded dist_def] by auto
-	also have "\<dots> \<le> e - d/2" using `d \<le> dist x y` and `d>0` and `?rhs` by(auto simp add: dist_def)
-	finally have "y - (d / (2 * dist y x)) *s (y - x) \<in> ball x e" using `d>0` by auto
+	  unfolding real_add_mult_distrib using `x\<noteq>y`[unfolded dist_nz, unfolded dist_norm] by auto
+	also have "\<dots> \<le> e - d/2" using `d \<le> dist x y` and `d>0` and `?rhs` by(auto simp add: dist_norm)
+	finally have "y - (d / (2 * dist y x)) *\<^sub>R (y - x) \<in> ball x e" using `d>0` by auto
 
 	moreover
 
-	have "(d / (2*dist y x)) *s (y - x) \<noteq> 0"
-	  using `x\<noteq>y`[unfolded dist_nz] `d>0` unfolding vector_mul_eq_0 by (auto simp add: dist_sym dist_refl)
+	have "(d / (2*dist y x)) *\<^sub>R (y - x) \<noteq> 0"
+	  using `x\<noteq>y`[unfolded dist_nz] `d>0` unfolding scaleR_eq_0_iff by (auto simp add: dist_commute)
 	moreover
-	have "dist (y - (d / (2 * dist y x)) *s (y - x)) y < d" unfolding dist_def apply simp unfolding norm_minus_cancel norm_mul
-	  using `d>0` `x\<noteq>y`[unfolded dist_nz] dist_sym[of x y]
-	  unfolding dist_def by auto
-	ultimately show "\<exists>x'\<in>ball x e. x' \<noteq> y \<and> dist x' y < d" by (rule_tac  x="y - (d / (2*dist y x)) *s (y - x)" in bexI) auto
+	have "dist (y - (d / (2 * dist y x)) *\<^sub>R (y - x)) y < d" unfolding dist_norm apply simp unfolding norm_minus_cancel norm_scaleR
+	  using `d>0` `x\<noteq>y`[unfolded dist_nz] dist_commute[of x y]
+	  unfolding dist_norm by auto
+	ultimately show "\<exists>x'\<in>ball x e. x' \<noteq> y \<and> dist x' y < d" by (rule_tac  x="y - (d / (2*dist y x)) *\<^sub>R (y - x)" in bexI) auto
       qed
     next
       case False hence "d > dist x y" by auto
       show "\<exists>x'\<in>ball x e. x' \<noteq> y \<and> dist x' y < d"
       proof(cases "x=y")
 	case True
-	obtain z where **:"dist y z = (min e d) / 2" using vector_choose_dist[of "(min e d) / 2" y]
-	  using `d > 0` `e>0` by (auto simp add: dist_refl)
+	obtain z where **: "z \<noteq> y" "dist z y < min e d"
+          using perfect_choose_dist[of "min e d" y]
+	  using `d > 0` `e>0` by auto
 	show "\<exists>x'\<in>ball x e. x' \<noteq> y \<and> dist x' y < d"
-	  apply(rule_tac x=z in bexI) unfolding `x=y` dist_sym dist_refl dist_nz using **  `d > 0` `e>0` by auto
+          unfolding `x = y`
+          using `z \<noteq> y` **
+          by (rule_tac x=z in bexI, auto simp add: dist_commute)
       next
 	case False thus "\<exists>x'\<in>ball x e. x' \<noteq> y \<and> dist x' y < d"
-	  using `d>0` `d > dist x y` `?rhs` by(rule_tac x=x in bexI, auto simp add: dist_refl)
+	  using `d>0` `d > dist x y` `?rhs` by(rule_tac x=x in bexI, auto)
       qed
     qed  }
   thus "?lhs" unfolding mem_cball islimpt_approachable mem_ball by auto
 qed
 
-lemma closure_ball: "0 < e ==> (closure(ball x e) = cball x e)"
+lemma closure_ball:
+  fixes x y :: "'a::{real_normed_vector,perfect_space}"
+    (* FIXME: generalize to metric_space *)
+  shows "0 < e ==> (closure(ball x e) = cball x e)"
   apply (simp add: closure_def islimpt_ball expand_set_eq)
   by arith
 
-lemma interior_cball: "interior(cball x e) = ball x e"
+lemma interior_cball:
+  fixes x :: "real ^ _" (* FIXME: generalize *)
+  shows "interior(cball x e) = ball x e"
 proof(cases "e\<ge>0")
   case False note cs = this
   from cs have "ball x e = {}" using ball_empty[of e x] by auto moreover
   { fix y assume "y \<in> cball x e"
-    hence False unfolding mem_cball using dist_nz[of x y] cs by (auto simp add: dist_refl)  }
+    hence False unfolding mem_cball using dist_nz[of x y] cs by auto  }
   hence "cball x e = {}" by auto
   hence "interior (cball x e) = {}" using interior_empty by auto
   ultimately show ?thesis by blast
@@ -1831,16 +1975,16 @@
 
     then obtain xa where xa:"dist y xa = d / 2" using vector_choose_dist[of "d/2" y] by auto
     hence xa_y:"xa \<noteq> y" using dist_nz[of y xa] using `d>0` by auto
-    have "xa\<in>S" using d[THEN spec[where x=xa]] using xa apply(auto simp add: dist_sym) unfolding dist_nz[THEN sym] using xa_y by auto
+    have "xa\<in>S" using d[THEN spec[where x=xa]] using xa apply(auto simp add: dist_commute) unfolding dist_nz[THEN sym] using xa_y by auto
     hence xa_cball:"xa \<in> cball x e" using as(1) by auto
 
     hence "y \<in> ball x e" proof(cases "x = y")
       case True
-      hence "e>0" using xa_y[unfolded dist_nz] xa_cball[unfolded mem_cball] by (auto simp add: dist_sym)
+      hence "e>0" using xa_y[unfolded dist_nz] xa_cball[unfolded mem_cball] by (auto simp add: dist_commute)
       thus "y \<in> ball x e" using `x = y ` by simp
     next
       case False
-      have "dist (y + (d / 2 / dist y x) *s (y - x)) y < d" unfolding dist_def
+      have "dist (y + (d / 2 / dist y x) *s (y - x)) y < d" unfolding dist_norm
 	using `d>0` norm_ge_zero[of "y - x"] `x \<noteq> y` by auto
       hence *:"y + (d / 2 / dist y x) *s (y - x) \<in> cball x e" using d as(1)[unfolded subset_eq] by blast
       have "y - x \<noteq> 0" using `x \<noteq> y` by auto
@@ -1848,44 +1992,52 @@
 	using `d>0` divide_pos_pos[of d "2*norm (y - x)"] by auto
 
       have "dist (y + (d / 2 / dist y x) *s (y - x)) x = norm (y + (d / (2 * norm (y - x))) *s y - (d / (2 * norm (y - x))) *s x - x)"
-	by (auto simp add: dist_def vector_ssub_ldistrib add_diff_eq)
+	by (auto simp add: dist_norm vector_ssub_ldistrib add_diff_eq)
       also have "\<dots> = norm ((1 + d / (2 * norm (y - x))) *s (y - x))"
 	by (auto simp add: vector_sadd_rdistrib vector_smult_lid ring_simps vector_sadd_rdistrib vector_ssub_ldistrib)
       also have "\<dots> = \<bar>1 + d / (2 * norm (y - x))\<bar> * norm (y - x)" using ** by auto
-      also have "\<dots> = (dist y x) + d/2"using ** by (auto simp add: left_distrib dist_def)
-      finally have "e \<ge> dist x y +d/2" using *[unfolded mem_cball] by (auto simp add: dist_sym)
+      also have "\<dots> = (dist y x) + d/2"using ** by (auto simp add: left_distrib dist_norm)
+      finally have "e \<ge> dist x y +d/2" using *[unfolded mem_cball] by (auto simp add: dist_commute)
       thus "y \<in> ball x e" unfolding mem_ball using `d>0` by auto
     qed  }
   hence "\<forall>S \<subseteq> cball x e. open S \<longrightarrow> S \<subseteq> ball x e" by auto
   ultimately show ?thesis using interior_unique[of "ball x e" "cball x e"] using open_ball[of x e] by auto
 qed
 
-lemma frontier_ball: "0 < e ==> frontier(ball a e) = {x. dist a x = e}"
+lemma frontier_ball:
+  fixes a :: "real ^ _" (* FIXME: generalize *)
+  shows "0 < e ==> frontier(ball a e) = {x. dist a x = e}"
   apply (simp add: frontier_def closure_ball interior_open open_ball order_less_imp_le)
   apply (simp add: expand_set_eq)
   by arith
 
-lemma frontier_cball: "frontier(cball a e) = {x. dist a x = e}"
+lemma frontier_cball:
+  fixes a :: "real ^ _" (* FIXME: generalize *)
+  shows "frontier(cball a e) = {x. dist a x = e}"
   apply (simp add: frontier_def interior_cball closed_cball closure_closed order_less_imp_le)
   apply (simp add: expand_set_eq)
   by arith
 
 lemma cball_eq_empty: "(cball x e = {}) \<longleftrightarrow> e < 0"
   apply (simp add: expand_set_eq not_le)
-  by (metis dist_pos_le dist_refl order_less_le_trans)
+  by (metis zero_le_dist dist_self order_less_le_trans)
 lemma cball_empty: "e < 0 ==> cball x e = {}" by (simp add: cball_eq_empty)
 
-lemma cball_eq_sing: "(cball x e = {x}) \<longleftrightarrow> e = 0"
+lemma cball_eq_sing:
+  fixes x :: "real ^ _" (* FIXME: generalize *)
+  shows "(cball x e = {x}) \<longleftrightarrow> e = 0"
 proof-
   { assume as:"\<forall>xa. (dist x xa \<le> e) = (xa = x)"
-    hence "e \<ge> 0" apply (erule_tac x=x in allE) by (auto simp add: dist_pos_le dist_refl)
+    hence "e \<ge> 0" apply (erule_tac x=x in allE) by auto
     then obtain y where y:"dist x y = e" using vector_choose_dist[of e] by auto
-    hence "e = 0" using as apply(erule_tac x=y in allE) by (auto simp add: dist_pos_le dist_refl)
+    hence "e = 0" using as apply(erule_tac x=y in allE) by auto
   }
-  thus ?thesis unfolding expand_set_eq mem_cball by (auto simp add: dist_refl dist_nz dist_le_0)
-qed
-
-lemma cball_sing:  "e = 0 ==> cball x e = {x}" by (simp add: cball_eq_sing)
+  thus ?thesis unfolding expand_set_eq mem_cball by (auto simp add: dist_nz)
+qed
+
+lemma cball_sing:
+  fixes x :: "real ^ _" (* FIXME: generalize *)
+  shows "e = 0 ==> cball x e = {x}" by (simp add: cball_eq_sing)
 
 text{* For points in the interior, localization of limits makes no difference.   *}
 
@@ -1894,7 +2046,7 @@
 proof-
   from assms obtain e where e:"e>0" "\<forall>y. dist x y < e \<longrightarrow> y \<in> S" unfolding mem_interior ball_def subset_eq by auto
   { assume "?lhs" then obtain d where "d>0" "\<forall>xa\<in>S. 0 < dist xa x \<and> dist xa x < d \<longrightarrow> P xa" unfolding eventually_within by auto
-    hence "?rhs" unfolding eventually_at using e by (auto simp add: dist_sym intro!: add exI[of _ "min e d"])
+    hence "?rhs" unfolding eventually_at using e by (auto simp add: dist_commute intro!: add exI[of _ "min e d"])
   } moreover
   { assume "?rhs" hence "?lhs" unfolding eventually_within eventually_at by auto
   } ultimately
@@ -1904,7 +2056,10 @@
 lemma lim_within_interior: "x \<in> interior S  ==> ((f ---> l) (at x within S) \<longleftrightarrow> (f ---> l) (at x))"
   by (simp add: tendsto_def eventually_within_interior)
 
-lemma netlimit_within_interior: assumes "x \<in> interior S"
+lemma netlimit_within_interior:
+  fixes x :: "'a::{perfect_space, real_normed_vector}"
+    (* FIXME: generalize to perfect_space *)
+  assumes "x \<in> interior S"
   shows "netlimit(at x within S) = x" (is "?lhs = ?rhs")
 proof-
   from assms obtain e::real where e:"e>0" "ball x e \<subseteq> S" using open_interior[of S] unfolding open_contains_ball using interior_subset[of S] by auto
@@ -1929,9 +2084,15 @@
   from assms obtain a where a:"\<forall>x\<in>S. norm x \<le> a" unfolding bounded_def by auto
   { fix x assume "x\<in>closure S"
     then obtain xa where xa:"\<forall>n. xa n \<in> S"  "(xa ---> x) sequentially" unfolding closure_sequential by auto
-    moreover have "\<exists>y. \<exists>x. netord sequentially x y" using trivial_limit_sequentially unfolding trivial_limit_def by blast
-    hence "\<exists>y. (\<exists>x. netord sequentially x y) \<and> (\<forall>x. netord sequentially x y \<longrightarrow> norm (xa x) \<le> a)" unfolding sequentially_def using a xa(1) by auto
-    ultimately have "norm x \<le> a" using Lim_norm_ubound[of sequentially xa x a] trivial_limit_sequentially unfolding eventually_def by auto
+    have "\<forall>n. xa n \<in> S \<longrightarrow> norm (xa n) \<le> a" using a by simp
+    hence "eventually (\<lambda>n. norm (xa n) \<le> a) sequentially"
+      by (rule eventually_mono, simp add: xa(1))
+    have "norm x \<le> a"
+      apply (rule Lim_norm_ubound[of sequentially xa x a])
+      apply (rule trivial_limit_sequentially)
+      apply (rule xa(2))
+      apply fact
+      done
   }
   thus ?thesis unfolding bounded_def by auto
 qed
@@ -2239,7 +2400,7 @@
 	  < (\<Sum>i \<in> ?d. e / real_of_nat (card ?d))"
 	  using setsum_strict_mono[of "?d" "\<lambda>i. \<bar>((f \<circ> r) n - l) $ i\<bar>" "\<lambda>i. e / (real_of_nat (card ?d))"] by auto
 	hence "(\<Sum>i \<in> ?d. \<bar>((f \<circ> r) n - l) $ i\<bar>) < e" unfolding setsum_constant by auto
-	hence "dist ((f \<circ> r) n) l < e" unfolding dist_def using norm_le_l1[of "(f \<circ> r) n - l"] by auto  }
+	hence "dist ((f \<circ> r) n) l < e" unfolding dist_norm using norm_le_l1[of "(f \<circ> r) n - l"] by auto  }
       hence "\<exists>N. \<forall>n\<ge>N. dist ((f \<circ> r) n) l < e" by auto  }
     hence *:"((f \<circ> r) ---> l) sequentially" unfolding Lim_sequentially by auto
     moreover have "l\<in>s"
@@ -2250,14 +2411,14 @@
 
 subsection{* Completeness. *}
 
-  (* FIXME: Unify this with Cauchy from SEQ!!!!!*)
-
-definition cauchy_def:"cauchy s \<longleftrightarrow> (\<forall>e>0. \<exists>N. \<forall>m n. m \<ge> N \<and> n \<ge> N --> dist(s m)(s n) < e)"
-
-definition complete_def:"complete s \<longleftrightarrow> (\<forall>f::(nat=>real^'a::finite). (\<forall>n. f n \<in> s) \<and> cauchy f
+lemma cauchy_def:
+  "Cauchy s \<longleftrightarrow> (\<forall>e>0. \<exists>N. \<forall>m n. m \<ge> N \<and> n \<ge> N --> dist(s m)(s n) < e)"
+unfolding Cauchy_def by blast
+
+definition complete_def:"complete s \<longleftrightarrow> (\<forall>f::(nat=>real^'a::finite). (\<forall>n. f n \<in> s) \<and> Cauchy f
                       --> (\<exists>l \<in> s. (f ---> l) sequentially))"
 
-lemma cauchy: "cauchy s \<longleftrightarrow> (\<forall>e>0.\<exists> N::nat. \<forall>n\<ge>N. dist(s n)(s N) < e)" (is "?lhs = ?rhs")
+lemma cauchy: "Cauchy s \<longleftrightarrow> (\<forall>e>0.\<exists> N::nat. \<forall>n\<ge>N. dist(s n)(s N) < e)" (is "?lhs = ?rhs")
 proof-
   { assume ?rhs
     { fix e::real
@@ -2284,20 +2445,20 @@
 qed
 
 lemma convergent_imp_cauchy:
- "(s ---> l) sequentially ==> cauchy s"
+ "(s ---> l) sequentially ==> Cauchy s"
 proof(simp only: cauchy_def, rule, rule)
   fix e::real assume "e>0" "(s ---> l) sequentially"
   then obtain N::nat where N:"\<forall>n\<ge>N. dist (s n) l < e/2" unfolding Lim_sequentially by(erule_tac x="e/2" in allE) auto
   thus "\<exists>N. \<forall>m n. N \<le> m \<and> N \<le> n \<longrightarrow> dist (s m) (s n) < e"  using dist_triangle_half_l[of _ l e _] by (rule_tac x=N in exI) auto
 qed
 
-lemma cauchy_imp_bounded: assumes "cauchy s" shows "bounded {y. (\<exists>n::nat. y = s n)}"
+lemma cauchy_imp_bounded: assumes "Cauchy s" shows "bounded {y. (\<exists>n::nat. y = s n)}"
 proof-
   from assms obtain N::nat where "\<forall>m n. N \<le> m \<and> N \<le> n \<longrightarrow> dist (s m) (s n) < 1" unfolding cauchy_def apply(erule_tac x= 1 in allE) by auto
   hence N:"\<forall>n. N \<le> n \<longrightarrow> dist (s N) (s n) < 1" by auto
   { fix n::nat assume "n\<ge>N"
-    hence "norm (s n) \<le> norm (s N) + 1" using N apply(erule_tac x=n in allE) unfolding dist_def
-      using norm_triangle_sub[of "s N" "s n"] by (auto, metis dist_def dist_sym le_add_right_mono norm_triangle_sub real_less_def)
+    hence "norm (s n) \<le> norm (s N) + 1" using N apply(erule_tac x=n in allE) unfolding dist_norm
+      using norm_triangle_sub[of "s N" "s n"] by (auto, metis norm_minus_commute le_add_right_mono norm_triangle_sub real_less_def)
   }
   hence "\<forall>n\<ge>N. norm (s n) \<le> norm (s N) + 1" by auto
   moreover
@@ -2310,7 +2471,7 @@
 
 lemma compact_imp_complete: assumes "compact s" shows "complete s"
 proof-
-  { fix f assume as: "(\<forall>n::nat. f n \<in> s)" "cauchy f"
+  { fix f assume as: "(\<forall>n::nat. f n \<in> s)" "Cauchy f"
     from as(1) obtain l r where lr: "l\<in>s" "(\<forall>m n. m < n \<longrightarrow> r m < r n)" "((f \<circ> r) ---> l) sequentially" using assms unfolding compact_def by blast
 
     { fix n :: nat have lr':"n \<le> r n"
@@ -2327,7 +2488,7 @@
 	have "dist ((f \<circ> r) n) l < e/2" using n M by auto
 	moreover have "r n \<ge> N" using lr'[of n] n by auto
 	hence "dist (f n) ((f \<circ> r) n) < e / 2" using N using n by auto
-	ultimately have "dist (f n) l < e" using dist_triangle_half_r[of "f (r n)" "f n" e l] by (auto simp add: dist_sym)  }
+	ultimately have "dist (f n) l < e" using dist_triangle_half_r[of "f (r n)" "f n" e l] by (auto simp add: dist_commute)  }
       hence "\<exists>N. \<forall>n\<ge>N. dist (f n) l < e" by blast  }
     hence "\<exists>l\<in>s. (f ---> l) sequentially" using `l\<in>s` unfolding Lim_sequentially by auto  }
   thus ?thesis unfolding complete_def by auto
@@ -2336,11 +2497,11 @@
 lemma complete_univ:
  "complete UNIV"
 proof(simp add: complete_def, rule, rule)
-  fix f::"nat \<Rightarrow> real^'n::finite" assume "cauchy f"
+  fix f::"nat \<Rightarrow> real^'n::finite" assume "Cauchy f"
   hence "bounded (f`UNIV)" using cauchy_imp_bounded[of f] unfolding image_def by auto
   hence "compact (closure (f`UNIV))"  using bounded_closed_imp_compact[of "closure (range f)"] by auto
   hence "complete (closure (range f))" using compact_imp_complete by auto
-  thus "\<exists>l. (f ---> l) sequentially" unfolding complete_def[of "closure (range f)"] using `cauchy f` unfolding closure_def  by auto
+  thus "\<exists>l. (f ---> l) sequentially" unfolding complete_def[of "closure (range f)"] using `Cauchy f` unfolding closure_def  by auto
 qed
 
 lemma complete_eq_closed: "complete s \<longleftrightarrow> closed s" (is "?lhs = ?rhs")
@@ -2353,13 +2514,15 @@
   thus ?rhs unfolding closed_limpt by auto
 next
   assume ?rhs
-  { fix f assume as:"\<forall>n::nat. f n \<in> s" "cauchy f"
+  { fix f assume as:"\<forall>n::nat. f n \<in> s" "Cauchy f"
     then obtain l where "(f ---> l) sequentially" using complete_univ[unfolded complete_def, THEN spec[where x=f]] by auto
     hence "\<exists>l\<in>s. (f ---> l) sequentially" using `?rhs`[unfolded closed_sequential_limits, THEN spec[where x=f], THEN spec[where x=l]] using as(1) by auto  }
   thus ?lhs unfolding complete_def by auto
 qed
 
-lemma convergent_eq_cauchy: "(\<exists>l. (s ---> l) sequentially) \<longleftrightarrow> cauchy s" (is "?lhs = ?rhs")
+lemma convergent_eq_cauchy:
+  fixes s :: "nat \<Rightarrow> real ^ 'n::finite"
+  shows "(\<exists>l. (s ---> l) sequentially) \<longleftrightarrow> Cauchy s" (is "?lhs = ?rhs")
 proof
   assume ?lhs then obtain l where "(s ---> l) sequentially" by auto
   thus ?rhs using convergent_imp_cauchy by auto
@@ -2398,7 +2561,7 @@
     qed }
   hence "\<forall>n::nat. x n \<in> s" and x:"\<forall>n. \<forall>m < n. \<not> (dist (x m) (x n) < e)" by blast+
   then obtain l r where "l\<in>s" and r:"\<forall>m n. m < n \<longrightarrow> r m < r n" and "((x \<circ> r) ---> l) sequentially" using assms(1)[unfolded compact_def, THEN spec[where x=x]] by auto
-  from this(3) have "cauchy (x \<circ> r)" using convergent_imp_cauchy by auto
+  from this(3) have "Cauchy (x \<circ> r)" using convergent_imp_cauchy by auto
   then obtain N::nat where N:"\<forall>m n. N \<le> m \<and> N \<le> n \<longrightarrow> dist ((x \<circ> r) m) ((x \<circ> r) n) < e" unfolding cauchy_def using `e>0` by auto
   show False
     using N[THEN spec[where x=N], THEN spec[where x="N+1"]]
@@ -2443,7 +2606,7 @@
   then obtain y where y:"y \<in> ball x (inverse (real (r (N1 + N2) + 1)))" "y \<notin> b" by auto
 
   have "dist x l < e/2" using N1 unfolding x_def o_def by auto
-  hence "dist y l < e" using y N2' using dist_triangle[of y l x]by (auto simp add:dist_sym)
+  hence "dist y l < e" using y N2' using dist_triangle[of y l x]by (auto simp add:dist_commute)
 
   thus False using e and `y\<notin>b` by auto
 qed
@@ -2533,14 +2696,14 @@
     proof(cases "m<n")
       case True
       hence "1 < norm (x n) - norm (x m)" using *[of m n] by auto
-      thus ?thesis unfolding dist_sym[of "x m" "x n"] unfolding dist_def using norm_triangle_sub[of "x n" "x m"] by auto
+      thus ?thesis unfolding dist_commute[of "x m" "x n"] unfolding dist_norm using norm_triangle_sub[of "x n" "x m"] by auto
     next
       case False hence "n<m" using `m\<noteq>n` by auto
       hence "1 < norm (x m) - norm (x n)" using *[of n m] by auto
-      thus ?thesis unfolding dist_sym[of "x n" "x m"] unfolding dist_def using norm_triangle_sub[of "x m" "x n"] by auto
+      thus ?thesis unfolding dist_commute[of "x n" "x m"] unfolding dist_norm using norm_triangle_sub[of "x m" "x n"] by auto
     qed  } note ** = this
   { fix a b assume "x a = x b" "a \<noteq> b"
-    hence False using **[of a b] unfolding dist_eq_0[THEN sym] by auto  }
+    hence False using **[of a b] by auto  }
   hence "inj x" unfolding inj_on_def by auto
   moreover
   { fix n::nat
@@ -2583,7 +2746,7 @@
   then obtain N::nat where N:"\<forall>n\<ge>N. dist (f n) l < e / 2"
     using assms(2)[unfolded Lim_sequentially, THEN spec[where x="e/2"]] by auto
   def d \<equiv> "Min (insert (e/2) ((\<lambda>n. if dist (f n) l' = 0 then e/2 else dist (f n) l') ` {0 .. N}))"
-  have "d>0" using `e>0` unfolding d_def e_def using dist_pos_le[of _ l', unfolded order_le_less] by auto
+  have "d>0" using `e>0` unfolding d_def e_def using zero_le_dist[of _ l', unfolded order_le_less] by auto
   obtain k where k:"f k \<noteq> l'"  "dist (f k) l' < d" using `d>0` and assms(3)[unfolded islimpt_approachable, THEN spec[where x="d"]] by auto
   have "k\<ge>N" using k(1)[unfolded dist_nz] using k(2)[unfolded d_def]
     by force
@@ -2592,6 +2755,7 @@
 qed
 
 lemma bolzano_weierstrass_imp_closed:
+  fixes s :: "(real ^ 'n::finite) set"
   assumes "\<forall>t. infinite t \<and> t \<subseteq> s --> (\<exists>x \<in> s. x islimpt t)"
   shows "closed s"
 proof-
@@ -2688,7 +2852,8 @@
 qed
 
 lemma finite_imp_closed:
- "finite s ==> closed s"
+  fixes s :: "(real ^ _) set" (* FIXME: generalize *)
+  shows "finite s ==> closed s"
 proof-
   assume "finite s" hence "\<not>( \<exists>t. t \<subseteq> s \<and> infinite t)" using finite_subset by auto
   thus ?thesis using bolzano_weierstrass_imp_closed[of s] by auto
@@ -2706,7 +2871,8 @@
   by blast
 
 lemma closed_sing[simp]:
- "closed {a}"
+  fixes a :: "real ^ _" (* FIXME: generalize *)
+  shows "closed {a}"
   using compact_eq_bounded_closed compact_sing[of a]
   by blast
 
@@ -2732,7 +2898,8 @@
   by blast
 
 lemma open_delete:
- "open s ==> open(s - {x})"
+  fixes s :: "(real ^ _) set" (* FIXME: generalize *)
+  shows "open s ==> open(s - {x})"
   using open_diff[of s "{x}"] closed_sing
   by blast
 
@@ -2802,7 +2969,7 @@
     }
     hence "\<exists>N. \<forall>m n. N \<le> m \<and> N \<le> n \<longrightarrow> dist (t m) (t n) < e" by auto
   }
-  hence  "cauchy t" unfolding cauchy_def by auto
+  hence  "Cauchy t" unfolding cauchy_def by auto
   then obtain l where l:"(t ---> l) sequentially" using complete_univ unfolding complete_def by auto
   { fix n::nat
     { fix e::real assume "e>0"
@@ -2829,9 +2996,9 @@
     { fix e::real assume "e>0"
       hence "dist a b < e" using assms(4 )using b using a by blast
     }
-    hence "dist a b = 0" by (metis dist_eq_0 dist_nz real_less_def)
+    hence "dist a b = 0" by (metis dist_eq_0_iff dist_nz real_less_def)
   }
-  with a have "\<Inter>{t. \<exists>n. t = s n} = {a}"  unfolding dist_eq_0 by auto
+  with a have "\<Inter>{t. \<exists>n. t = s n} = {a}"  by auto
   thus ?thesis by auto
 qed
 
@@ -2854,7 +3021,7 @@
   thus ?rhs by auto
 next
   assume ?rhs
-  hence "\<forall>x. P x \<longrightarrow> cauchy (\<lambda>n. s n x)" unfolding cauchy_def apply auto by (erule_tac x=e in allE)auto
+  hence "\<forall>x. P x \<longrightarrow> Cauchy (\<lambda>n. s n x)" unfolding cauchy_def apply auto by (erule_tac x=e in allE)auto
   then obtain l where l:"\<forall>x. P x \<longrightarrow> ((\<lambda>n. s n x) ---> l x) sequentially" unfolding convergent_eq_cauchy[THEN sym]
     using choice[of "\<lambda>x l. P x \<longrightarrow> ((\<lambda>n. s n x) ---> l) sequentially"] by auto
   { fix e::real assume "e>0"
@@ -2865,12 +3032,13 @@
 	using l[THEN spec[where x=x], unfolded Lim_sequentially] using `e>0` by(auto elim!: allE[where x="e/2"])
       fix n::nat assume "n\<ge>N"
       hence "dist(s n x)(l x) < e"  using `P x`and N[THEN spec[where x=n], THEN spec[where x="N+M"], THEN spec[where x=x]]
-	using M[THEN spec[where x="N+M"]] and dist_triangle_half_l[of "s n x" "s (N+M) x" e "l x"] by (auto simp add: dist_sym)  }
+	using M[THEN spec[where x="N+M"]] and dist_triangle_half_l[of "s n x" "s (N+M) x" e "l x"] by (auto simp add: dist_commute)  }
     hence "\<exists>N. \<forall>n x. N \<le> n \<and> P x \<longrightarrow> dist(s n x)(l x) < e" by auto }
   thus ?lhs by auto
 qed
 
 lemma uniformly_cauchy_imp_uniformly_convergent:
+  fixes s :: "nat \<Rightarrow> 'a \<Rightarrow> real ^ 'n::finite"
   assumes "\<forall>e>0.\<exists>N. \<forall>m (n::nat) x. N \<le> m \<and> N \<le> n \<and> P x --> dist(s m x)(s n x) < e"
           "\<forall>x. P x --> (\<forall>e>0. \<exists>N. \<forall>n. N \<le> n --> dist(s n x)(l x) < e)"
   shows "\<forall>e>0. \<exists>N. \<forall>n x. N \<le> n \<and> P x --> dist(s n x)(l x) < e"
@@ -2890,17 +3058,16 @@
 
 lemma continuous_trivial_limit:
  "trivial_limit net ==> continuous net f"
-  unfolding continuous_def tendsto_def eventually_def by auto
+  unfolding continuous_def tendsto_def trivial_limit_eq by auto
 
 lemma continuous_within: "continuous (at x within s) f \<longleftrightarrow> (f ---> f(x)) (at x within s)"
   unfolding continuous_def
   unfolding tendsto_def
   using netlimit_within[of x s]
-  unfolding eventually_def
-  by (cases "trivial_limit (at x within s)") auto
-
-lemma continuous_at: "continuous (at x) f \<longleftrightarrow> (f ---> f(x)) (at x)" using within_UNIV[of x]
-  using continuous_within[of x UNIV f] by auto
+  by (cases "trivial_limit (at x within s)") (auto simp add: trivial_limit_eventually)
+
+lemma continuous_at: "continuous (at x) f \<longleftrightarrow> (f ---> f(x)) (at x)"
+  using continuous_within [of x UNIV f] by (simp add: within_UNIV)
 
 lemma continuous_at_within:
   assumes "continuous (at x) f"  shows "continuous (at x within s) f"
@@ -2937,32 +3104,37 @@
       using `?lhs`[unfolded continuous_within Lim_within] by auto
     { fix y assume "y\<in>f ` (ball x d \<inter> s)"
       hence "y \<in> ball (f x) e" using d(2) unfolding dist_nz[THEN sym]
-	apply (auto simp add: dist_sym mem_ball) apply(erule_tac x=xa in ballE) apply auto unfolding dist_refl using `e>0` by auto
+	apply (auto simp add: dist_commute mem_ball) apply(erule_tac x=xa in ballE) apply auto using `e>0` by auto
     }
-    hence "\<exists>d>0. f ` (ball x d \<inter> s) \<subseteq> ball (f x) e" using `d>0` unfolding subset_eq ball_def by (auto simp add: dist_sym)  }
+    hence "\<exists>d>0. f ` (ball x d \<inter> s) \<subseteq> ball (f x) e" using `d>0` unfolding subset_eq ball_def by (auto simp add: dist_commute)  }
   thus ?rhs by auto
 next
   assume ?rhs thus ?lhs unfolding continuous_within Lim_within ball_def subset_eq
-    apply (auto simp add: dist_sym) apply(erule_tac x=e in allE) by auto
-qed
-
-lemma continuous_at_ball: fixes f::"real^'a::finite \<Rightarrow> real^'a"
-  shows "continuous (at x) f \<longleftrightarrow> (\<forall>e>0. \<exists>d>0. f ` (ball x d) \<subseteq> ball (f x) e)" (is "?lhs = ?rhs")
+    apply (auto simp add: dist_commute) apply(erule_tac x=e in allE) by auto
+qed
+
+lemma continuous_at_ball:
+  "continuous (at x) f \<longleftrightarrow> (\<forall>e>0. \<exists>d>0. f ` (ball x d) \<subseteq> ball (f x) e)" (is "?lhs = ?rhs")
 proof
   assume ?lhs thus ?rhs unfolding continuous_at Lim_at subset_eq Ball_def Bex_def image_iff mem_ball
-    apply auto apply(erule_tac x=e in allE) apply auto apply(rule_tac x=d in exI) apply auto apply(erule_tac x=xa in allE) apply (auto simp add: dist_refl dist_sym dist_nz)
-    unfolding dist_nz[THEN sym] by (auto simp add: dist_refl)
+    apply auto apply(erule_tac x=e in allE) apply auto apply(rule_tac x=d in exI) apply auto apply(erule_tac x=xa in allE) apply (auto simp add: dist_commute dist_nz)
+    unfolding dist_nz[THEN sym] by auto
 next
   assume ?rhs thus ?lhs unfolding continuous_at Lim_at subset_eq Ball_def Bex_def image_iff mem_ball
-    apply auto apply(erule_tac x=e in allE) apply auto apply(rule_tac x=d in exI) apply auto apply(erule_tac x="f xa" in allE) by (auto simp add: dist_refl dist_sym dist_nz)
+    apply auto apply(erule_tac x=e in allE) apply auto apply(rule_tac x=d in exI) apply auto apply(erule_tac x="f xa" in allE) by (auto simp add: dist_commute dist_nz)
 qed
 
 text{* For setwise continuity, just start from the epsilon-delta definitions. *}
 
-definition "continuous_on s f \<longleftrightarrow> (\<forall>x \<in> s. \<forall>e>0. \<exists>d::real>0. \<forall>x' \<in> s. dist x' x < d --> dist (f x') (f x) < e)"
-
-
-definition "uniformly_continuous_on s f \<longleftrightarrow>
+definition
+  continuous_on :: "(real ^ 'n::finite) set \<Rightarrow> (real ^ 'n \<Rightarrow> real ^ 'm::finite) \<Rightarrow> bool" where
+  "continuous_on s f \<longleftrightarrow> (\<forall>x \<in> s. \<forall>e>0. \<exists>d::real>0. \<forall>x' \<in> s. dist x' x < d --> dist (f x') (f x) < e)"
+
+
+definition
+  uniformly_continuous_on ::
+    "(real ^ 'n::finite) set \<Rightarrow> (real ^ 'n \<Rightarrow> real ^ 'm::finite) \<Rightarrow> bool" where
+  "uniformly_continuous_on s f \<longleftrightarrow>
         (\<forall>e>0. \<exists>d>0. \<forall>x\<in>s. \<forall> x'\<in>s. dist x' x < d
                            --> dist (f x') (f x) < e)"
 
@@ -2985,7 +3157,7 @@
   { fix x' assume "\<not> 0 < dist x' x"
     hence "x=x'"
       using dist_nz[of x' x] by auto
-    hence "dist (f x') (f x) < e" using dist_refl[of "f x'"] `e>0` by auto
+    hence "dist (f x') (f x) < e" using `e>0` by auto
   }
   thus "\<exists>d>0. \<forall>x'\<in>s. dist x' x < d \<longrightarrow> dist (f x') (f x) < e" using d by auto
 qed
@@ -2999,8 +3171,8 @@
     assume "\<exists>d>0. \<forall>xa\<in>s. 0 < dist xa x \<and> dist xa x < d \<longrightarrow> dist (f xa) (f x) < e"
     then obtain d where "d>0" and d:"\<forall>xa\<in>s. 0 < dist xa x \<and> dist xa x < d \<longrightarrow> dist (f xa) (f x) < e" by auto
     { fix x' assume as:"x'\<in>s" "dist x' x < d"
-      hence "dist (f x') (f x) < e" using dist_refl[of "f x'"] `e>0` d `x'\<in>s` dist_eq_0[of x' x] dist_pos_le[of x' x] as(2) by (metis dist_eq_0 dist_nz) }
-    hence "\<exists>d>0. \<forall>x'\<in>s. dist x' x < d \<longrightarrow> dist (f x') (f x) < e" using `d>0` by (auto simp add: dist_refl)
+      hence "dist (f x') (f x) < e" using `e>0` d `x'\<in>s` dist_eq_0_iff[of x' x] zero_le_dist[of x' x] as(2) by (metis dist_eq_0_iff dist_nz) }
+    hence "\<exists>d>0. \<forall>x'\<in>s. dist x' x < d \<longrightarrow> dist (f x') (f x) < e" using `d>0` by auto
   }
   thus ?lhs using `?rhs` unfolding continuous_on_def continuous_within Lim_within by auto
 next
@@ -3044,14 +3216,14 @@
                      --> ((f o x) ---> f a) sequentially)" (is "?lhs = ?rhs")
 proof
   assume ?lhs
-  { fix x::"nat \<Rightarrow> real^'a" assume x:"\<forall>n. x n \<in> s" "\<forall>e>0. \<exists>N. \<forall>n\<ge>N. dist (x n) a < e"
+  { fix x::"nat \<Rightarrow> 'a" assume x:"\<forall>n. x n \<in> s" "\<forall>e>0. \<exists>N. \<forall>n\<ge>N. dist (x n) a < e"
     fix e::real assume "e>0"
     from `?lhs` obtain d where "d>0" and d:"\<forall>x\<in>s. 0 < dist x a \<and> dist x a < d \<longrightarrow> dist (f x) (f a) < e" unfolding continuous_within Lim_within using `e>0` by auto
     from x(2) `d>0` obtain N where N:"\<forall>n\<ge>N. dist (x n) a < d" by auto
     hence "\<exists>N. \<forall>n\<ge>N. dist ((f \<circ> x) n) (f a) < e"
       apply(rule_tac  x=N in exI) using N d  apply auto using x(1)
       apply(erule_tac x=n in allE) apply(erule_tac x=n in allE)
-      apply(erule_tac x="x n" in ballE)  apply auto unfolding dist_nz[THEN sym] apply auto unfolding dist_refl using `e>0` by auto
+      apply(erule_tac x="x n" in ballE)  apply auto unfolding dist_nz[THEN sym] apply auto using `e>0` by auto
   }
   thus ?rhs unfolding continuous_within unfolding Lim_sequentially by simp
 next
@@ -3102,13 +3274,13 @@
     { fix e::real assume "e>0"
       then obtain d where "d>0" and d:"\<forall>x\<in>s. \<forall>x'\<in>s. dist x' x < d \<longrightarrow> dist (f x') (f x) < e"
 	using `?lhs`[unfolded uniformly_continuous_on_def, THEN spec[where x=e]] by auto
-      obtain N where N:"\<forall>n\<ge>N. norm (x n - y n - 0) < d" using xy[unfolded Lim_sequentially dist_def] and `d>0` by auto
+      obtain N where N:"\<forall>n\<ge>N. norm (x n - y n - 0) < d" using xy[unfolded Lim_sequentially dist_norm] and `d>0` by auto
       { fix n assume "n\<ge>N"
 	hence "norm (f (x n) - f (y n) - 0) < e"
 	  using N[THEN spec[where x=n]] using d[THEN bspec[where x="x n"], THEN bspec[where x="y n"]] using x and y
-	  unfolding dist_sym and dist_def by simp  }
+	  unfolding dist_commute and dist_norm by simp  }
       hence "\<exists>N. \<forall>n\<ge>N. norm (f (x n) - f (y n) - 0) < e"  by auto  }
-    hence "((\<lambda>n. f(x n) - f(y n)) ---> 0) sequentially" unfolding Lim_sequentially and dist_def by auto  }
+    hence "((\<lambda>n. f(x n) - f(y n)) ---> 0) sequentially" unfolding Lim_sequentially and dist_norm by auto  }
   thus ?rhs by auto
 next
   assume ?rhs
@@ -3116,12 +3288,12 @@
     then obtain e where "e>0" "\<forall>d>0. \<exists>x\<in>s. \<exists>x'\<in>s. dist x' x < d \<and> \<not> dist (f x') (f x) < e" unfolding uniformly_continuous_on_def by auto
     then obtain fa where fa:"\<forall>x.  0 < x \<longrightarrow> fst (fa x) \<in> s \<and> snd (fa x) \<in> s \<and> dist (fst (fa x)) (snd (fa x)) < x \<and> \<not> dist (f (fst (fa x))) (f (snd (fa x))) < e"
       using choice[of "\<lambda>d x. d>0 \<longrightarrow> fst x \<in> s \<and> snd x \<in> s \<and> dist (snd x) (fst x) < d \<and> \<not> dist (f (snd x)) (f (fst x)) < e"] unfolding Bex_def
-      by (auto simp add: dist_sym)
+      by (auto simp add: dist_commute)
     def x \<equiv> "\<lambda>n::nat. fst (fa (inverse (real n + 1)))"
     def y \<equiv> "\<lambda>n::nat. snd (fa (inverse (real n + 1)))"
     have xyn:"\<forall>n. x n \<in> s \<and> y n \<in> s" and xy0:"\<forall>n. dist (x n) (y n) < inverse (real n + 1)" and fxy:"\<forall>n. \<not> dist (f (x n)) (f (y n)) < e"
       unfolding x_def and y_def using fa by auto
-    have *:"\<And>x y. dist (x - y) 0 = dist x y" unfolding dist_def by auto
+    have *:"\<And>x (y::real^_). dist (x - y) 0 = dist x y" unfolding dist_norm by auto
     { fix e::real assume "e>0"
       then obtain N::nat where "N \<noteq> 0" and N:"0 < inverse (real N) \<and> inverse (real N) < e" unfolding real_arch_inv[of e]   by auto
       { fix n::nat assume "n\<ge>N"
@@ -3138,6 +3310,7 @@
 text{* The usual transformation theorems. *}
 
 lemma continuous_transform_within:
+  fixes f g :: "real ^ 'n::finite \<Rightarrow> 'b::real_normed_vector"
   assumes "0 < d" "x \<in> s" "\<forall>x' \<in> s. dist x' x < d --> f x' = g x'"
           "continuous (at x within s) f"
   shows "continuous (at x within s) g"
@@ -3145,7 +3318,7 @@
   { fix e::real assume "e>0"
     then obtain d' where d':"d'>0" "\<forall>xa\<in>s. 0 < dist xa x \<and> dist xa x < d' \<longrightarrow> dist (f xa) (f x) < e" using assms(4) unfolding continuous_within Lim_within by auto
     { fix x' assume "x'\<in>s" "0 < dist x' x" "dist x' x < (min d d')"
-      hence "dist (f x') (g x) < e" using assms(2,3) apply(erule_tac x=x in ballE) unfolding dist_refl using d' by auto  }
+      hence "dist (f x') (g x) < e" using assms(2,3) apply(erule_tac x=x in ballE) using d' by auto  }
     hence "\<forall>xa\<in>s. 0 < dist xa x \<and> dist xa x < (min d d') \<longrightarrow> dist (f xa) (g x) < e" by blast
     hence "\<exists>d>0. \<forall>xa\<in>s. 0 < dist xa x \<and> dist xa x < d \<longrightarrow> dist (f xa) (g x) < e" using `d>0` `d'>0` by(rule_tac x="min d d'" in exI)auto  }
   hence "(f ---> g x) (at x within s)" unfolding Lim_within using assms(1) by auto
@@ -3153,6 +3326,7 @@
 qed
 
 lemma continuous_transform_at:
+  fixes f g :: "real ^ 'n::finite \<Rightarrow> 'b::real_normed_vector"
   assumes "0 < d" "\<forall>x'. dist x' x < d --> f x' = g x'"
           "continuous (at x) f"
   shows "continuous (at x) g"
@@ -3160,7 +3334,7 @@
   { fix e::real assume "e>0"
     then obtain d' where d':"d'>0" "\<forall>xa. 0 < dist xa x \<and> dist xa x < d' \<longrightarrow> dist (f xa) (f x) < e" using assms(3) unfolding continuous_at Lim_at by auto
     { fix x' assume "0 < dist x' x" "dist x' x < (min d d')"
-      hence "dist (f x') (g x) < e" using assms(2) apply(erule_tac x=x in allE) unfolding dist_refl using d' by auto
+      hence "dist (f x') (g x) < e" using assms(2) apply(erule_tac x=x in allE) using d' by auto
     }
     hence "\<forall>xa. 0 < dist xa x \<and> dist xa x < (min d d') \<longrightarrow> dist (f xa) (g x) < e" by blast
     hence "\<exists>d>0. \<forall>xa. 0 < dist xa x \<and> dist xa x < d \<longrightarrow> dist (f xa) (g x) < e" using `d>0` `d'>0` by(rule_tac x="min d d'" in exI)auto
@@ -3172,25 +3346,27 @@
 text{* Combination results for pointwise continuity. *}
 
 lemma continuous_const: "continuous net (\<lambda>x::'a::zero_neq_one. c)"
-  by(auto simp add: continuous_def Lim_const)
+  by (auto simp add: continuous_def Lim_const)
 
 lemma continuous_cmul:
- "continuous net f ==> continuous net (\<lambda>x. c *s f x)"
- by(auto simp add: continuous_def Lim_cmul)
+  fixes f :: "'a \<Rightarrow> real ^ 'n::finite"
+  shows "continuous net f ==> continuous net (\<lambda>x. c *s f x)"
+  by (auto simp add: continuous_def Lim_cmul)
 
 lemma continuous_neg:
- "continuous net f ==> continuous net (\<lambda>x. -(f x))"
- by(auto simp add: continuous_def Lim_neg)
+  fixes f :: "'a \<Rightarrow> 'b::real_normed_vector"
+  shows "continuous net f ==> continuous net (\<lambda>x. -(f x))"
+  by (auto simp add: continuous_def Lim_neg)
 
 lemma continuous_add:
- "continuous net f \<Longrightarrow> continuous net g
-           ==> continuous net (\<lambda>x. f x + g x)"
- by(auto simp add: continuous_def Lim_add)
+  fixes f g :: "'a \<Rightarrow> 'b::real_normed_vector"
+  shows "continuous net f \<Longrightarrow> continuous net g \<Longrightarrow> continuous net (\<lambda>x. f x + g x)"
+  by (auto simp add: continuous_def Lim_add)
 
 lemma continuous_sub:
- "continuous net f \<Longrightarrow> continuous net g
-           ==> continuous net (\<lambda>x. f(x) - g(x))"
- by(auto simp add: continuous_def Lim_sub)
+  fixes f g :: "'a \<Rightarrow> 'b::real_normed_vector"
+  shows "continuous net f \<Longrightarrow> continuous net g \<Longrightarrow> continuous net (\<lambda>x. f x - g x)"
+  by (auto simp add: continuous_def Lim_sub)
 
 text{* Same thing for setwise continuity. *}
 
@@ -3287,8 +3463,8 @@
     with assms(2)[unfolded continuous_within Lim_within] obtain d  where "d>0" and d:"\<forall>xa\<in>f ` s. 0 < dist xa (f x) \<and> dist xa (f x) < d \<longrightarrow> dist (g xa) (g (f x)) < e" by auto
     from assms(1)[unfolded continuous_within Lim_within] obtain d' where "d'>0" and d':"\<forall>xa\<in>s. 0 < dist xa x \<and> dist xa x < d' \<longrightarrow> dist (f xa) (f x) < d" using `d>0` by auto
     { fix y assume as:"y\<in>s"  "0 < dist y x"  "dist y x < d'"
-      hence "dist (f y) (f x) < d" using d'[THEN bspec[where x=y]] by (auto simp add:dist_sym)
-      hence "dist (g (f y)) (g (f x)) < e" using as(1) d[THEN bspec[where x="f y"]] unfolding dist_nz[THEN sym] using `e>0` by (auto simp add: dist_refl)   }
+      hence "dist (f y) (f x) < d" using d'[THEN bspec[where x=y]] by (auto simp add:dist_commute)
+      hence "dist (g (f y)) (g (f x)) < e" using as(1) d[THEN bspec[where x="f y"]] unfolding dist_nz[THEN sym] using `e>0` by auto   }
     hence "\<exists>d>0. \<forall>xa\<in>s. 0 < dist xa x \<and> dist xa x < d \<longrightarrow> dist (g (f xa)) (g (f x)) < e" using `d'>0` by auto  }
   thus ?thesis unfolding continuous_within Lim_within by auto
 qed
@@ -3332,7 +3508,7 @@
     moreover
     { fix x' assume "x'\<in>ball x d" hence "f x' \<in> t"
 	using e[unfolded subset_eq Ball_def mem_ball, THEN spec[where x="f x'"]]    d[THEN spec[where x=x']]
-	unfolding mem_ball apply (auto simp add: dist_sym)
+	unfolding mem_ball apply (auto simp add: dist_commute)
 	unfolding dist_nz[THEN sym] using as(2) by auto  }
     hence "\<forall>x'\<in>ball x d. f x' \<in> t" by auto
     ultimately have "\<exists>s. open s \<and> x \<in> s \<and> (\<forall>x'\<in>s. f x' \<in> t)"
@@ -3346,7 +3522,7 @@
     then obtain d where "d>0" and d:"ball x d \<subseteq> s" unfolding open_contains_ball by auto
     { fix y assume "0 < dist y x \<and> dist y x < d"
       hence "dist (f y) (f x) < e" using d[unfolded subset_eq Ball_def mem_ball, THEN spec[where x=y]]
-	using s(3)[THEN bspec[where x=y], unfolded mem_ball] by (auto simp add: dist_sym)  }
+	using s(3)[THEN bspec[where x=y], unfolded mem_ball] by (auto simp add: dist_commute)  }
     hence "\<exists>d>0. \<forall>xa. 0 < dist xa x \<and> dist xa x < d \<longrightarrow> dist (f xa) (f x) < e" using `d>0` by auto  }
   thus ?lhs unfolding continuous_at Lim_at by auto
 qed
@@ -3363,7 +3539,7 @@
     { fix x assume as':"x\<in>{x \<in> s. f x \<in> t}"
       then obtain e where e: "e>0" "\<forall>x'\<in>f ` s. dist x' (f x) < e \<longrightarrow> x' \<in> t" using as[unfolded openin_euclidean_subtopology_iff, THEN conjunct2, THEN bspec[where x="f x"]] by auto
       from this(1) obtain d where d: "d>0" "\<forall>xa\<in>s. 0 < dist xa x \<and> dist xa x < d \<longrightarrow> dist (f xa) (f x) < e" using `?lhs`[unfolded continuous_on Lim_within, THEN bspec[where x=x]] using as' by auto
-      have "\<exists>e>0. \<forall>x'\<in>s. dist x' x < e \<longrightarrow> x' \<in> {x \<in> s. f x \<in> t}" using d e unfolding dist_nz[THEN sym] by (rule_tac x=d in exI, auto simp add: dist_refl)  }
+      have "\<exists>e>0. \<forall>x'\<in>s. dist x' x < e \<longrightarrow> x' \<in> {x \<in> s. f x \<in> t}" using d e unfolding dist_nz[THEN sym] by (rule_tac x=d in exI, auto)  }
     ultimately have "openin (subtopology euclidean s) {x \<in> s. f x \<in> t}" unfolding openin_euclidean_subtopology_iff by auto  }
   thus ?rhs unfolding continuous_on Lim_within using openin by auto
 next
@@ -3371,12 +3547,12 @@
   { fix e::real and x assume "x\<in>s" "e>0"
     { fix xa x' assume "dist (f xa) (f x) < e" "xa \<in> s" "x' \<in> s" "dist (f xa) (f x') < e - dist (f xa) (f x)"
       hence "dist (f x') (f x) < e" using dist_triangle[of "f x'" "f x" "f xa"]
-	by (auto simp add: dist_sym)  }
+	by (auto simp add: dist_commute)  }
     hence "ball (f x) e \<inter> f ` s \<subseteq> f ` s \<and> (\<forall>xa\<in>ball (f x) e \<inter> f ` s. \<exists>ea>0. \<forall>x'\<in>f ` s. dist x' xa < ea \<longrightarrow> x' \<in> ball (f x) e \<inter> f ` s)" apply auto
-      apply(rule_tac x="e - dist (f xa) (f x)" in exI) using `e>0` by (auto simp add: dist_sym)
+      apply(rule_tac x="e - dist (f xa) (f x)" in exI) using `e>0` by (auto simp add: dist_commute)
     hence "\<forall>xa\<in>{xa \<in> s. f xa \<in> ball (f x) e \<inter> f ` s}. \<exists>ea>0. \<forall>x'\<in>s. dist x' xa < ea \<longrightarrow> x' \<in> {xa \<in> s. f xa \<in> ball (f x) e \<inter> f ` s}"
       using `?rhs`[unfolded openin_euclidean_subtopology_iff, THEN spec[where x="ball (f x) e \<inter> f ` s"]] by auto
-    hence "\<exists>d>0. \<forall>xa\<in>s. 0 < dist xa x \<and> dist xa x < d \<longrightarrow> dist (f xa) (f x) < e" apply(erule_tac x=x in ballE) apply auto unfolding dist_refl using `e>0` `x\<in>s` by (auto simp add: dist_sym)  }
+    hence "\<exists>d>0. \<forall>xa\<in>s. 0 < dist xa x \<and> dist xa x < d \<longrightarrow> dist (f xa) (f x) < e" apply(erule_tac x=x in ballE) apply auto using `e>0` `x\<in>s` by (auto simp add: dist_commute)  }
   thus ?lhs unfolding continuous_on Lim_within by auto
 qed
 
@@ -3448,11 +3624,13 @@
 qed
 
 lemma continuous_open_preimage_univ:
- "\<forall>x. continuous (at x) f \<Longrightarrow> open s \<Longrightarrow> open {x. f x \<in> s}"
+  fixes f :: "real ^ _ \<Rightarrow> real ^ _" (* FIXME: generalize *)
+  shows "\<forall>x. continuous (at x) f \<Longrightarrow> open s \<Longrightarrow> open {x. f x \<in> s}"
   using continuous_open_preimage[of UNIV f s] open_UNIV continuous_at_imp_continuous_on by auto
 
 lemma continuous_closed_preimage_univ:
- "(\<forall>x. continuous (at x) f) \<Longrightarrow> closed s ==> closed {x. f x \<in> s}"
+  fixes f :: "real ^ _ \<Rightarrow> real ^ _" (* FIXME: generalize *)
+  shows "(\<forall>x. continuous (at x) f) \<Longrightarrow> closed s ==> closed {x. f x \<in> s}"
   using continuous_closed_preimage[of UNIV f s] closed_UNIV continuous_at_imp_continuous_on by auto
 
 text{* Equality of continuous functions on closure and related results.          *}
@@ -3491,7 +3669,7 @@
   have *:"f ` s \<subseteq> cball 0 b" using assms(2)[unfolded mem_cball_0[THEN sym]] by auto
   show ?thesis
     using image_closure_subset[OF assms(1) closed_cball[of 0 b] *] assms(3)
-    unfolding subset_eq apply(erule_tac x="f x" in ballE) by (auto simp add: dist_def)
+    unfolding subset_eq apply(erule_tac x="f x" in ballE) by (auto simp add: dist_norm)
 qed
 
 text{* Making a continuous function avoid some value in a neighbourhood.         *}
@@ -3504,7 +3682,7 @@
     using assms(1)[unfolded continuous_within Lim_within, THEN spec[where x="dist (f x) a"]] assms(3)[unfolded dist_nz] by auto
   { fix y assume " y\<in>s"  "dist x y < d"
     hence "f y \<noteq> a" using d[THEN bspec[where x=y]] assms(3)[unfolded dist_nz]
-      apply auto unfolding dist_nz[THEN sym] by (auto simp add: dist_sym) }
+      apply auto unfolding dist_nz[THEN sym] by (auto simp add: dist_commute) }
   thus ?thesis using `d>0` by auto
 qed
 
@@ -3546,6 +3724,7 @@
 text{* Some arithmetical combinations (more to prove).                           *}
 
 lemma open_scaling[intro]:
+  fixes s :: "(real ^ _) set"
   assumes "c \<noteq> 0"  "open s"
   shows "open((\<lambda>x. c *s x) ` s)"
 proof-
@@ -3554,18 +3733,20 @@
     have "e * abs c > 0" using assms(1)[unfolded zero_less_abs_iff[THEN sym]] using real_mult_order[OF `e>0`] by auto
     moreover
     { fix y assume "dist y (c *s x) < e * \<bar>c\<bar>"
-      hence "norm ((1 / c) *s y - x) < e" unfolding dist_def
+      hence "norm ((1 / c) *s y - x) < e" unfolding dist_norm
 	using norm_mul[of c "(1 / c) *s y - x", unfolded vector_ssub_ldistrib, unfolded vector_smult_assoc] assms(1)
 	  assms(1)[unfolded zero_less_abs_iff[THEN sym]] by (simp del:zero_less_abs_iff)
-      hence "y \<in> op *s c ` s" using rev_image_eqI[of "(1 / c) *s y" s y "op *s c"]  e[THEN spec[where x="(1 / c) *s y"]]  assms(1) unfolding dist_def vector_smult_assoc by auto  }
+      hence "y \<in> op *s c ` s" using rev_image_eqI[of "(1 / c) *s y" s y "op *s c"]  e[THEN spec[where x="(1 / c) *s y"]]  assms(1) unfolding dist_norm vector_smult_assoc by auto  }
     ultimately have "\<exists>e>0. \<forall>x'. dist x' (c *s x) < e \<longrightarrow> x' \<in> op *s c ` s" apply(rule_tac x="e * abs c" in exI) by auto  }
   thus ?thesis unfolding open_def by auto
 qed
 
 lemma open_negations:
- "open s ==> open ((\<lambda> x. -x) ` s)" unfolding pth_3 by auto
+  fixes s :: "(real ^ _) set" (* FIXME: generalize *)
+  shows "open s ==> open ((\<lambda> x. -x) ` s)" unfolding pth_3 by auto
 
 lemma open_translation:
+  fixes s :: "(real ^ _) set" (* FIXME: generalize *)
   assumes "open s"  shows "open((\<lambda>x. a + x) ` s)"
 proof-
   { fix x have "continuous (at x) (\<lambda>x. x - a)" using continuous_sub[of "at x" "\<lambda>x. x" "\<lambda>x. a"] continuous_at_id[of x] continuous_const[of "at x" a] by auto  }
@@ -3574,6 +3755,7 @@
 qed
 
 lemma open_affinity:
+  fixes s :: "(real ^ _) set"
   assumes "open s"  "c \<noteq> 0"
   shows "open ((\<lambda>x. a + c *s x) ` s)"
 proof-
@@ -3582,18 +3764,20 @@
   thus ?thesis using assms open_translation[of "op *s c ` s" a] unfolding * by auto
 qed
 
-lemma interior_translation: "interior ((\<lambda>x. a + x) ` s) = (\<lambda>x. a + x) ` (interior s)"
+lemma interior_translation:
+  fixes s :: "'a::real_normed_vector set"
+  shows "interior ((\<lambda>x. a + x) ` s) = (\<lambda>x. a + x) ` (interior s)"
 proof (rule set_ext, rule)
   fix x assume "x \<in> interior (op + a ` s)"
   then obtain e where "e>0" and e:"ball x e \<subseteq> op + a ` s" unfolding mem_interior by auto
-  hence "ball (x - a) e \<subseteq> s" unfolding subset_eq Ball_def mem_ball dist_def apply auto apply(erule_tac x="a + xa" in allE) unfolding ab_group_add_class.diff_diff_eq[THEN sym] by auto
+  hence "ball (x - a) e \<subseteq> s" unfolding subset_eq Ball_def mem_ball dist_norm apply auto apply(erule_tac x="a + xa" in allE) unfolding ab_group_add_class.diff_diff_eq[THEN sym] by auto
   thus "x \<in> op + a ` interior s" unfolding image_iff apply(rule_tac x="x - a" in bexI) unfolding mem_interior using `e > 0` by auto
 next
   fix x assume "x \<in> op + a ` interior s"
   then obtain y e where "e>0" and e:"ball y e \<subseteq> s" and y:"x = a + y" unfolding image_iff Bex_def mem_interior by auto
   { fix z have *:"a + y - z = y + a - z" by auto
     assume "z\<in>ball x e"
-    hence "z - a \<in> s" using e[unfolded subset_eq, THEN bspec[where x="z - a"]] unfolding mem_ball dist_def y ab_group_add_class.diff_diff_eq2 * by auto
+    hence "z - a \<in> s" using e[unfolded subset_eq, THEN bspec[where x="z - a"]] unfolding mem_ball dist_norm y ab_group_add_class.diff_diff_eq2 * by auto
     hence "z \<in> op + a ` s" unfolding image_iff by(auto intro!: bexI[where x="z - a"])  }
   hence "ball x e \<subseteq> op + a ` s" unfolding subset_eq by auto
   thus "x \<in> interior (op + a ` s)" unfolding mem_interior using `e>0` by auto
@@ -3656,13 +3840,13 @@
       obtain z where "z\<in>s" and z:"ball x ea \<subseteq> ball z (d z (e / 2))" using ea[THEN bspec[where x=x]] and `x\<in>s` by auto
       hence "x\<in>ball z (d z (e / 2))" using `ea>0` unfolding subset_eq by auto
       hence "dist (f z) (f x) < e / 2" using d[THEN spec[where x="e/2"]] and `e>0` and `x\<in>s` and `z\<in>s`
-	by (auto  simp add: dist_sym)
+	by (auto  simp add: dist_commute)
       moreover have "y\<in>ball z (d z (e / 2))" using as and `ea>0` and z[unfolded subset_eq]
-	by (auto simp add: dist_sym)
+	by (auto simp add: dist_commute)
       hence "dist (f z) (f y) < e / 2" using d[THEN spec[where x="e/2"]] and `e>0` and `y\<in>s` and `z\<in>s`
-	by (auto  simp add: dist_sym)
+	by (auto  simp add: dist_commute)
       ultimately have "dist (f y) (f x) < e" using dist_triangle_half_r[of "f z" "f x" e "f y"]
-	by (auto simp add: dist_sym)  }
+	by (auto simp add: dist_commute)  }
     then have "\<exists>d>0. \<forall>x\<in>s. \<forall>x'\<in>s. dist x' x < d \<longrightarrow> dist (f x') (f x) < e" using `ea>0` by auto  }
   thus ?thesis unfolding uniformly_continuous_on_def by auto
 qed
@@ -3706,8 +3890,8 @@
     { fix y assume "y\<in>s" "dist y x < d"
       hence "dist (f n y) (f n x) < e / 3" using d[THEN bspec[where x=y]] by auto
       hence "norm (f n y - g x) < 2 * e / 3" using norm_triangle_lt[of "f n y - f n x" "f n x - g x" "2*e/3"]
-	using n(1)[THEN bspec[where x=x], OF `x\<in>s`] unfolding dist_def unfolding ab_group_add_class.ab_diff_minus by auto
-      hence "dist (g y) (g x) < e" unfolding dist_def using n(1)[THEN bspec[where x=y], OF `y\<in>s`]
+	using n(1)[THEN bspec[where x=x], OF `x\<in>s`] unfolding dist_norm unfolding ab_group_add_class.ab_diff_minus by auto
+      hence "dist (g y) (g x) < e" unfolding dist_norm using n(1)[THEN bspec[where x=y], OF `y\<in>s`]
 	unfolding norm_minus_cancel[of "f n y - g y", THEN sym] using norm_triangle_lt[of "f n y - g x" "g y - f n y" e] by (auto simp add: uminus_add_conv_diff)  }
     hence "\<exists>d>0. \<forall>x'\<in>s. dist x' x < d \<longrightarrow> dist (g x') (g x) < e" using `d>0` by auto  }
   thus ?thesis unfolding continuous_on_def by auto
@@ -3724,17 +3908,19 @@
       hence "B * norm x < e" using `B>0` using mult_strict_right_mono[of "norm x" " e / B" B] unfolding real_mult_commute by auto
       hence "norm (f x) < e" using B[THEN spec[where x=x]] `B>0` using order_le_less_trans[of "norm (f x)" "B * norm x" e] by auto   }
     moreover have "e / B > 0" using `e>0` `B>0` divide_pos_pos by auto
-    ultimately have "\<exists>d>0. \<forall>x. 0 < dist x 0 \<and> dist x 0 < d \<longrightarrow> dist (f x) 0 < e" unfolding dist_def by auto  }
+    ultimately have "\<exists>d>0. \<forall>x. 0 < dist x 0 \<and> dist x 0 < d \<longrightarrow> dist (f x) 0 < e" unfolding dist_norm by auto  }
   thus ?thesis unfolding Lim_at by auto
 qed
 
 lemma linear_continuous_at:
+  fixes f :: "real ^ _ \<Rightarrow> real ^ _"
   assumes "linear f"  shows "continuous (at a) f"
   unfolding continuous_at Lim_at_zero[of f "f a" a] using linear_lim_0[OF assms]
   unfolding Lim_null[of "\<lambda>x. f (a + x)"] unfolding linear_sub[OF assms, THEN sym] by auto
 
 lemma linear_continuous_within:
- "linear f ==> continuous (at x within s) f"
+  fixes f :: "real ^ _ \<Rightarrow> real ^ _"
+  shows "linear f ==> continuous (at x within s) f"
   using continuous_at_imp_continuous_within[of x f s] using linear_continuous_at[of f] by auto
 
 lemma linear_continuous_on:
@@ -3744,12 +3930,14 @@
 text{* Also bilinear functions, in composition form.                             *}
 
 lemma bilinear_continuous_at_compose:
- "continuous (at x) f \<Longrightarrow> continuous (at x) g \<Longrightarrow> bilinear h
+  fixes f :: "real ^ _ \<Rightarrow> real ^ _"
+  shows "continuous (at x) f \<Longrightarrow> continuous (at x) g \<Longrightarrow> bilinear h
         ==> continuous (at x) (\<lambda>x. h (f x) (g x))"
   unfolding continuous_at using Lim_bilinear[of f "f x" "(at x)" g "g x" h] by auto
 
 lemma bilinear_continuous_within_compose:
- "continuous (at x within s) f \<Longrightarrow> continuous (at x within s) g \<Longrightarrow> bilinear h
+  fixes f :: "real ^ _ \<Rightarrow> real ^ _"
+  shows "continuous (at x within s) f \<Longrightarrow> continuous (at x within s) g \<Longrightarrow> bilinear h
         ==> continuous (at x within s) (\<lambda>x. h (f x) (g x))"
   unfolding continuous_within using Lim_bilinear[of f "f x"] by auto
 
@@ -3763,16 +3951,19 @@
 
 
 lemma open_vec1:
+  fixes s :: "real set" shows
  "open(vec1 ` s) \<longleftrightarrow>
         (\<forall>x \<in> s. \<exists>e>0. \<forall>x'. abs(x' - x) < e --> x' \<in> s)" (is "?lhs = ?rhs")
   unfolding open_def apply simp unfolding forall_vec1 dist_vec1 vec1_in_image_vec1 by simp
 
 lemma islimpt_approachable_vec1:
+  fixes s :: "real set" shows
  "(vec1 x) islimpt (vec1 ` s) \<longleftrightarrow>
          (\<forall>e>0.  \<exists>x'\<in> s. x' \<noteq> x \<and> abs(x' - x) < e)"
   by (auto simp add: islimpt_approachable dist_vec1 vec1_eq)
 
 lemma closed_vec1:
+  fixes s :: "real set" shows
  "closed (vec1 ` s) \<longleftrightarrow>
         (\<forall>x. (\<forall>e>0.  \<exists>x' \<in> s. x' \<noteq> x \<and> abs(x' - x) < e)
             --> x \<in> s)"
@@ -3780,29 +3971,31 @@
   unfolding dist_vec1 vec1_in_image_vec1 abs_minus_commute by auto
 
 lemma continuous_at_vec1_range:
- "continuous (at x) (vec1 o f) \<longleftrightarrow> (\<forall>e>0. \<exists>d>0.
+  fixes f :: "real ^ _ \<Rightarrow> real"
+  shows "continuous (at x) (vec1 o f) \<longleftrightarrow> (\<forall>e>0. \<exists>d>0.
         \<forall>x'. norm(x' - x) < d --> abs(f x' - f x) < e)"
-  unfolding continuous_at unfolding Lim_at apply simp unfolding dist_vec1 unfolding dist_nz[THEN sym] unfolding dist_def apply auto
+  unfolding continuous_at unfolding Lim_at apply simp unfolding dist_vec1 unfolding dist_nz[THEN sym] unfolding dist_norm apply auto
   apply(erule_tac x=e in allE) apply auto apply (rule_tac x=d in exI) apply auto apply (erule_tac x=x' in allE) apply auto
   apply(erule_tac x=e in allE) by auto
 
 lemma continuous_on_vec1_range:
  " continuous_on s (vec1 o f) \<longleftrightarrow> (\<forall>x \<in> s. \<forall>e>0. \<exists>d>0. (\<forall>x' \<in> s. norm(x' - x) < d --> abs(f x' - f x) < e))"
-  unfolding continuous_on_def apply (simp del: dist_sym) unfolding dist_vec1 unfolding dist_def ..
+  unfolding continuous_on_def apply (simp del: dist_commute) unfolding dist_vec1 unfolding dist_norm ..
 
 lemma continuous_at_vec1_norm:
- "\<forall>x. continuous (at x) (vec1 o norm)"
+  fixes x :: "real ^ _"
+  shows "continuous (at x) (vec1 o norm)"
   unfolding continuous_at_vec1_range using real_abs_sub_norm order_le_less_trans by blast
 
 lemma continuous_on_vec1_norm:
- "\<forall>s. continuous_on s (vec1 o norm)"
+ "continuous_on s (vec1 o norm)"
 unfolding continuous_on_vec1_range norm_vec1[THEN sym] by (metis norm_vec1 order_le_less_trans real_abs_sub_norm)
 
 lemma continuous_at_vec1_component:
   shows "continuous (at (a::real^'a::finite)) (\<lambda> x. vec1(x$i))"
 proof-
   { fix e::real and x assume "0 < dist x a" "dist x a < e" "e>0"
-    hence "\<bar>x $ i - a $ i\<bar> < e" using component_le_norm[of "x - a" i] unfolding dist_def by auto  }
+    hence "\<bar>x $ i - a $ i\<bar> < e" using component_le_norm[of "x - a" i] unfolding dist_norm by auto  }
   thus ?thesis unfolding continuous_at tendsto_def eventually_at dist_vec1 by auto
 qed
 
@@ -3811,12 +4004,12 @@
 proof-
   { fix e::real and x xa assume "x\<in>s" "e>0" "xa\<in>s" "0 < norm (xa - x) \<and> norm (xa - x) < e"
     hence "\<bar>xa $ i - x $ i\<bar> < e" using component_le_norm[of "xa - x" i] by auto  }
-  thus ?thesis unfolding continuous_on Lim_within dist_vec1 unfolding dist_def by auto
+  thus ?thesis unfolding continuous_on Lim_within dist_vec1 unfolding dist_norm by auto
 qed
 
 lemma continuous_at_vec1_infnorm:
  "continuous (at x) (vec1 o infnorm)"
-  unfolding continuous_at Lim_at o_def unfolding dist_vec1 unfolding dist_def
+  unfolding continuous_at Lim_at o_def unfolding dist_vec1 unfolding dist_norm
   apply auto apply (rule_tac x=e in exI) apply auto
   using order_trans[OF real_abs_sub_infnorm infnorm_le_norm, of _ x] by (metis xt1(7))
 
@@ -3860,7 +4053,7 @@
 
 lemma continuous_attains_inf:
  "compact s \<Longrightarrow> s \<noteq> {} \<Longrightarrow> continuous_on s (vec1 o f)
-        ==> (\<exists>x \<in> s. \<forall>y \<in> s. f x \<le> f y)"
+        \<Longrightarrow> (\<exists>x \<in> s. \<forall>y \<in> s. f x \<le> f y)"
   using compact_attains_inf[of "f ` s"]
   using compact_continuous_image[of s "vec1 \<circ> f"] unfolding image_compose by auto
 
@@ -3872,21 +4065,22 @@
     { fix x' assume "x'\<in>s" and as:"norm (x' - x) < e"
       hence "\<bar>norm (x' - a) - norm (x - a)\<bar> < e"
 	using real_abs_sub_norm[of "x' - a" "x - a"]  by auto  }
-    hence "\<exists>d>0. \<forall>x'\<in>s. norm (x' - x) < d \<longrightarrow> \<bar>dist x' a - dist x a\<bar> < e" using `e>0` unfolding dist_def by auto }
+    hence "\<exists>d>0. \<forall>x'\<in>s. norm (x' - x) < d \<longrightarrow> \<bar>dist x' a - dist x a\<bar> < e" using `e>0` unfolding dist_norm by auto }
   thus ?thesis using assms
     using continuous_attains_sup[of s "\<lambda>x. dist a x"]
-    unfolding continuous_on_vec1_range by (auto simp add: dist_sym)
+    unfolding continuous_on_vec1_range by (auto simp add: dist_commute)
 qed
 
 text{* For *minimal* distance, we only need closure, not compactness.            *}
 
 lemma distance_attains_inf:
+  fixes a :: "real ^ _" (* FIXME: generalize *)
   assumes "closed s"  "s \<noteq> {}"
   shows "\<exists>x \<in> s. \<forall>y \<in> s. dist a x \<le> dist a y"
 proof-
   from assms(2) obtain b where "b\<in>s" by auto
   let ?B = "cball a (dist b a) \<inter> s"
-  have "b \<in> ?B" using `b\<in>s` by (simp add: dist_sym)
+  have "b \<in> ?B" using `b\<in>s` by (simp add: dist_commute)
   hence "?B \<noteq> {}" by auto
   moreover
   { fix x assume "x\<in>?B"
@@ -3894,9 +4088,9 @@
     { fix x' assume "x'\<in>?B" and as:"norm (x' - x) < e"
       hence "\<bar>norm (x' - a) - norm (x - a)\<bar> < e"
 	using real_abs_sub_norm[of "x' - a" "x - a"]  by auto  }
-    hence "\<exists>d>0. \<forall>x'\<in>?B. norm (x' - x) < d \<longrightarrow> \<bar>dist x' a - dist x a\<bar> < e" using `e>0` unfolding dist_def by auto }
+    hence "\<exists>d>0. \<forall>x'\<in>?B. norm (x' - x) < d \<longrightarrow> \<bar>dist x' a - dist x a\<bar> < e" using `e>0` unfolding dist_norm by auto }
   hence "continuous_on (cball a (dist b a) \<inter> s) (vec1 \<circ> dist a)" unfolding continuous_on_vec1_range
-    by (auto  simp add: dist_sym)
+    by (auto  simp add: dist_commute)
   moreover have "compact ?B" using compact_cball[of a "dist b a"] unfolding compact_eq_bounded_closed using bounded_Int and closed_Int and assms(1) by auto
   ultimately obtain x where "x\<in>cball a (dist b a) \<inter> s" "\<forall>y\<in>cball a (dist b a) \<inter> s. dist a x \<le> dist a y" using continuous_attains_inf[of ?B "dist a"] by fastsimp
   thus ?thesis by fastsimp
@@ -3905,6 +4099,7 @@
 subsection{* We can now extend limit compositions to consider the scalar multiplier.   *}
 
 lemma Lim_mul:
+  fixes f :: "'a \<Rightarrow> real ^ _"
   assumes "((vec1 o c) ---> vec1 d) net"  "(f ---> l) net"
   shows "((\<lambda>x. c(x) *s f x) ---> (d *s l)) net"
 proof-
@@ -3915,15 +4110,18 @@
 qed
 
 lemma Lim_vmul:
- "((vec1 o c) ---> vec1 d) net ==> ((\<lambda>x. c(x) *s v) ---> d *s v) net"
+  fixes c :: "'a \<Rightarrow> real"
+  shows "((vec1 o c) ---> vec1 d) net ==> ((\<lambda>x. c(x) *s v) ---> d *s v) net"
   using Lim_mul[of c d net "\<lambda>x. v" v] using Lim_const[of v] by auto
 
 lemma continuous_vmul:
- "continuous net (vec1 o c) ==> continuous net (\<lambda>x. c(x) *s v)"
+  fixes c :: "'a \<Rightarrow> real"
+  shows "continuous net (vec1 o c) ==> continuous net (\<lambda>x. c(x) *s v)"
   unfolding continuous_def using Lim_vmul[of c] by auto
 
 lemma continuous_mul:
- "continuous net (vec1 o c) \<Longrightarrow> continuous net f
+  fixes c :: "'a \<Rightarrow> real"
+  shows "continuous net (vec1 o c) \<Longrightarrow> continuous net f
              ==> continuous net (\<lambda>x. c(x) *s f x) "
   unfolding continuous_def using Lim_mul[of c] by auto
 
@@ -3939,19 +4137,18 @@
 text{* And so we have continuity of inverse.                                     *}
 
 lemma Lim_inv:
+  fixes f :: "'a \<Rightarrow> real"
   assumes "((vec1 o f) ---> vec1 l) (net::'a net)"  "l \<noteq> 0"
   shows "((vec1 o inverse o f) ---> vec1(inverse l)) net"
-proof(cases "trivial_limit net")
-  case True thus ?thesis unfolding tendsto_def unfolding eventually_def by auto
-next
-  case False note ntriv = this
+proof -
   { fix e::real assume "e>0"
-    hence "0 < min (\<bar>l\<bar> / 2) (l\<twosuperior> * e / 2)" using `l\<noteq>0` mult_pos_pos[of "l^2" "e/2"] by auto
-    then obtain y where y1:"\<exists>x. netord net x y" and
-      y:"\<forall>x. netord net x y \<longrightarrow> dist ((vec1 \<circ> f) x) (vec1 l) < min (\<bar>l\<bar> / 2) (l\<twosuperior> * e / 2)" using ntriv
-      using assms(1)[unfolded tendsto_def eventually_def, THEN spec[where x="min (abs l / 2) (l ^ 2 * e / 2)"]] by auto
-    { fix x assume "netord net x y"
-      hence *:"\<bar>f x - l\<bar> < min (\<bar>l\<bar> / 2) (l\<twosuperior> * e / 2)" using y[THEN spec[where x=x]] unfolding o_def dist_vec1 by auto
+    let ?d = "min (\<bar>l\<bar> / 2) (l\<twosuperior> * e / 2)"
+    have "0 < ?d" using `l\<noteq>0` `e>0` mult_pos_pos[of "l^2" "e/2"] by auto
+    with assms(1) have "eventually (\<lambda>x. dist ((vec1 o f) x) (vec1 l) < ?d) net"
+      by (rule tendstoD)
+    moreover
+    { fix x assume "dist ((vec1 o f) x) (vec1 l) < ?d"
+      hence *:"\<bar>f x - l\<bar> < min (\<bar>l\<bar> / 2) (l\<twosuperior> * e / 2)" unfolding o_def dist_vec1 by auto
       hence fx0:"f x \<noteq> 0" using `l \<noteq> 0` by auto
       hence fxl0: "(f x) * l \<noteq> 0" using `l \<noteq> 0` by auto
       from * have **:"\<bar>f x - l\<bar> < l\<twosuperior> * e / 2" by auto
@@ -3968,31 +4165,33 @@
 	unfolding divide_divide_eq_left
 	unfolding nonzero_abs_divide[OF fxl0]
 	using mult_less_le_imp_less[OF **, of "inverse \<bar>f x * l\<bar>", of "inverse (l^2 / 2)"] using *** using fx0 `l\<noteq>0`
-	unfolding inverse_eq_divide using `e>0` by auto   }
-    hence "(\<exists>y. (\<exists>x. netord net x y) \<and> (\<forall>x. netord net x y \<longrightarrow> dist ((vec1 \<circ> inverse \<circ> f) x) (vec1 (inverse l)) < e))"
-      using y1 by auto  }
-  thus ?thesis unfolding tendsto_def eventually_def by auto
+	unfolding inverse_eq_divide using `e>0` by auto
+    }
+    ultimately
+    have "eventually (\<lambda>x. dist ((vec1 o inverse o f) x) (vec1(inverse l)) < e) net"
+      by (auto elim: eventually_rev_mono)
+  }
+  thus ?thesis unfolding tendsto_def by auto
 qed
 
 lemma continuous_inv:
- "continuous net (vec1 o f) \<Longrightarrow> f(netlimit net) \<noteq> 0
+  fixes f :: "'a \<Rightarrow> real"
+  shows "continuous net (vec1 o f) \<Longrightarrow> f(netlimit net) \<noteq> 0
            ==> continuous net (vec1 o inverse o f)"
   unfolding continuous_def using Lim_inv by auto
 
 lemma continuous_at_within_inv:
+  fixes f :: "real ^ _ \<Rightarrow> real"
   assumes "continuous (at a within s) (vec1 o f)" "f a \<noteq> 0"
   shows "continuous (at a within s) (vec1 o inverse o f)"
-proof(cases "trivial_limit (at a within s)")
-  case True thus ?thesis unfolding continuous_def tendsto_def eventually_def by auto
-next
-  case False note cs = this
-  thus ?thesis using netlimit_within[OF cs] assms(2) continuous_inv[OF assms(1)] by auto
-qed
+  using assms unfolding continuous_within o_apply
+  by (rule Lim_inv)
 
 lemma continuous_at_inv:
- "continuous (at a) (vec1 o f) \<Longrightarrow> f a \<noteq> 0
+  fixes f :: "real ^ _ \<Rightarrow> real"
+  shows "continuous (at a) (vec1 o f) \<Longrightarrow> f a \<noteq> 0
          ==> continuous (at a) (vec1 o inverse o f) "
-  using within_UNIV[THEN sym, of a] using continuous_at_within_inv[of a UNIV] by auto
+  using within_UNIV[THEN sym, of "at a"] using continuous_at_within_inv[of a UNIV] by auto
 
 subsection{* Preservation properties for pasted sets.                                  *}
 
@@ -4008,6 +4207,7 @@
 qed
 
 lemma closed_pastecart:
+  fixes s :: "(real ^ 'a::finite) set" (* FIXME: generalize *)
   assumes "closed s"  "closed t"
   shows "closed {pastecart x y | x y . x \<in> s \<and> y \<in> t}"
 proof-
@@ -4094,7 +4294,7 @@
   have "{x - y | x y . x\<in>s \<and> y\<in>s} \<noteq> {}" using `s \<noteq> {}` by auto
   then obtain x where x:"x\<in>{x - y |x y. x \<in> s \<and> y \<in> s}"  "\<forall>y\<in>{x - y |x y. x \<in> s \<and> y \<in> s}. norm y \<le> norm x"
     using compact_differences[OF assms(1) assms(1)]
-    using distance_attains_sup[unfolded dist_def, of "{x - y | x y . x\<in>s \<and> y\<in>s}" 0] by(auto simp add: norm_minus_cancel)
+    using distance_attains_sup[unfolded dist_norm, of "{x - y | x y . x\<in>s \<and> y\<in>s}" 0] by(auto simp add: norm_minus_cancel)
   from x(1) obtain a b where "a\<in>s" "b\<in>s" "x = a - b" by auto
   thus ?thesis using x(2)[unfolded `x = a - b`] by blast
 qed
@@ -4150,6 +4350,7 @@
 text{* Related results with closure as the conclusion.                           *}
 
 lemma closed_scaling:
+  fixes s :: "(real ^ _) set"
   assumes "closed s" shows "closed ((\<lambda>x. c *s x) ` s)"
 proof(cases "s={}")
   case True thus ?thesis by auto
@@ -4167,7 +4368,7 @@
       { fix e::real assume "e>0"
 	hence "0 < e *\<bar>c\<bar>"  using `c\<noteq>0` mult_pos_pos[of e "abs c"] by auto
 	then obtain N where "\<forall>n\<ge>N. dist (x n) l < e * \<bar>c\<bar>" using as(2)[unfolded Lim_sequentially, THEN spec[where x="e * abs c"]] by auto
-	hence "\<exists>N. \<forall>n\<ge>N. dist ((1 / c) *s x n) ((1 / c) *s l) < e" unfolding dist_def unfolding vector_ssub_ldistrib[THEN sym] norm_mul
+	hence "\<exists>N. \<forall>n\<ge>N. dist ((1 / c) *s x n) ((1 / c) *s l) < e" unfolding dist_norm unfolding vector_ssub_ldistrib[THEN sym] norm_mul
 	  using mult_imp_div_pos_less[of "abs c" _ e] `c\<noteq>0` by auto  }
       hence "((\<lambda>n. (1 / c) *s x n) ---> (1 / c) *s l) sequentially" unfolding Lim_sequentially by auto
       ultimately have "l \<in> op *s c ` s"  using assms[unfolded closed_sequential_limits, THEN spec[where x="\<lambda>n. (1/c) *s x n"], THEN spec[where x="(1/c) *s l"]]
@@ -4177,6 +4378,7 @@
 qed
 
 lemma closed_negations:
+  fixes s :: "(real ^ _) set" (* FIXME: generalize *)
   assumes "closed s"  shows "closed ((\<lambda>x. -x) ` s)"
   using closed_scaling[OF assms, of "-1"] unfolding  pth_3 by auto
 
@@ -4227,6 +4429,7 @@
 qed
 
 lemma closed_translation:
+  fixes s :: "(real ^ _) set" (* FIXME: generalize *)
   assumes "closed s"  shows "closed ((\<lambda>x. a + x) ` s)"
 proof-
   have "{a + y |y. y \<in> s} = (op + a ` s)" by auto
@@ -4240,20 +4443,23 @@
 lemma translation_diff: "(\<lambda>x::real^'a. a + x) ` (s - t) = ((\<lambda>x. a + x) ` s) - ((\<lambda>x. a + x) ` t)" by auto
 
 lemma closure_translation:
- "closure ((\<lambda>x. a + x) ` s) = (\<lambda>x. a + x) ` (closure s)"
+  fixes s :: "(real ^ _) set" (* FIXME: generalize *)
+  shows "closure ((\<lambda>x. a + x) ` s) = (\<lambda>x. a + x) ` (closure s)"
 proof-
   have *:"op + a ` (UNIV - s) = UNIV - op + a ` s"  apply auto unfolding image_iff apply(rule_tac x="x - a" in bexI) by auto
   show ?thesis unfolding closure_interior translation_diff translation_UNIV using interior_translation[of a "UNIV - s"] unfolding * by auto
 qed
 
 lemma frontier_translation:
- "frontier((\<lambda>x. a + x) ` s) = (\<lambda>x. a + x) ` (frontier s)"
+  fixes s :: "(real ^ _) set" (* FIXME: generalize *)
+  shows "frontier((\<lambda>x. a + x) ` s) = (\<lambda>x. a + x) ` (frontier s)"
   unfolding frontier_def translation_diff interior_translation closure_translation by auto
 
 subsection{* Separation between points and sets.                                       *}
 
 lemma separate_point_closed:
- "closed s \<Longrightarrow> a \<notin> s  ==> (\<exists>d>0. \<forall>x\<in>s. d \<le> dist a x)"
+  fixes s :: "(real ^ _) set" (* FIXME: generalize *)
+  shows "closed s \<Longrightarrow> a \<notin> s  ==> (\<exists>d>0. \<forall>x\<in>s. d \<le> dist a x)"
 proof(cases "s = {}")
   case True
   thus ?thesis by(auto intro!: exI[where x=1])
@@ -4273,9 +4479,9 @@
     using separate_point_closed[OF compact_closed_differences[OF assms(1,2)], of 0] by auto
   { fix x y assume "x\<in>s" "y\<in>t"
     hence "x - y \<in> {x - y |x y. x \<in> s \<and> y \<in> t}" by auto
-    hence "d \<le> dist (x - y) 0" using d[THEN bspec[where x="x - y"]] using dist_sym
-      by (auto  simp add: dist_sym)
-    hence "d \<le> dist x y" unfolding dist_def by auto  }
+    hence "d \<le> dist (x - y) 0" using d[THEN bspec[where x="x - y"]] using dist_commute
+      by (auto  simp add: dist_commute)
+    hence "d \<le> dist x y" unfolding dist_norm by auto  }
   thus ?thesis using `d>0` by auto
 qed
 
@@ -4286,7 +4492,7 @@
   have *:"t \<inter> s = {}" using assms(3) by auto
   show ?thesis using separate_compact_closed[OF assms(2,1) *]
     apply auto apply(rule_tac x=d in exI) apply auto apply (erule_tac x=y in ballE)
-    by (auto simp add: dist_sym)
+    by (auto simp add: dist_commute)
 qed
 
 (* A cute way of denoting open and closed intervals using overloading.       *)
@@ -4299,8 +4505,12 @@
 lemma mem_interval: fixes a :: "'a::ord^'n::finite" shows
   "x \<in> {a<..<b} \<longleftrightarrow> (\<forall>i. a$i < x$i \<and> x$i < b$i)"
   "x \<in> {a .. b} \<longleftrightarrow> (\<forall>i. a$i \<le> x$i \<and> x$i \<le> b$i)"
-  using interval[of a b]
-  by(auto simp add: expand_set_eq vector_less_def vector_less_eq_def)
+  using interval[of a b] by(auto simp add: expand_set_eq vector_less_def vector_less_eq_def)
+
+lemma mem_interval_1: fixes x :: "real^1" shows
+ "(x \<in> {a .. b} \<longleftrightarrow> dest_vec1 a \<le> dest_vec1 x \<and> dest_vec1 x \<le> dest_vec1 b)"
+ "(x \<in> {a<..<b} \<longleftrightarrow> dest_vec1 a < dest_vec1 x \<and> dest_vec1 x < dest_vec1 b)"
+by(simp_all add: Cart_eq vector_less_def vector_less_eq_def dest_vec1_def forall_1)
 
 lemma interval_eq_empty: fixes a :: "real^'n::finite" shows
  "({a <..< b} = {} \<longleftrightarrow> (\<exists>i. b$i \<le> a$i))" (is ?th1) and
@@ -4357,7 +4567,6 @@
 apply (auto simp add: not_less less_imp_le)
 done
 
-
 lemma interval_open_subset_closed:  fixes a :: "'a::preorder^'n::finite" shows
  "{a<..<b} \<subseteq> {a .. b}"
 proof(simp add: subset_eq, rule)
@@ -4475,7 +4684,7 @@
     { fix x' assume as:"dist x' x < ?d"
       { fix i
 	have "\<bar>x'$i - x $ i\<bar> < d i"
-	  using norm_bound_component_lt[OF as[unfolded dist_def], of i]
+	  using norm_bound_component_lt[OF as[unfolded dist_norm], of i]
 	  unfolding vector_minus_component and Min_gr_iff[OF **] by auto
 	hence "a $ i < x' $ i" "x' $ i < b $ i" using d[THEN spec[where x=i]] by auto  }
       hence "a < x' \<and> x' < b" unfolding vector_less_def by auto  }
@@ -4489,13 +4698,13 @@
   { fix x i assume as:"\<forall>e>0. \<exists>x'\<in>{a..b}. x' \<noteq> x \<and> dist x' x < e"(* and xab:"a$i > x$i \<or> b$i < x$i"*)
     { assume xa:"a$i > x$i"
       with as obtain y where y:"y\<in>{a..b}" "y \<noteq> x" "dist y x < a$i - x$i" by(erule_tac x="a$i - x$i" in allE)auto
-      hence False unfolding mem_interval and dist_def
+      hence False unfolding mem_interval and dist_norm
 	using component_le_norm[of "y-x" i, unfolded vector_minus_component] and xa by(auto elim!: allE[where x=i])
     } hence "a$i \<le> x$i" by(rule ccontr)auto
     moreover
     { assume xb:"b$i < x$i"
       with as obtain y where y:"y\<in>{a..b}" "y \<noteq> x" "dist y x < x$i - b$i" by(erule_tac x="x$i - b$i" in allE)auto
-      hence False unfolding mem_interval and dist_def
+      hence False unfolding mem_interval and dist_norm
 	using component_le_norm[of "y-x" i, unfolded vector_minus_component] and xb by(auto elim!: allE[where x=i])
     } hence "x$i \<le> b$i" by(rule ccontr)auto
     ultimately
@@ -4514,7 +4723,7 @@
     { fix i
       have "dist (x - (e / 2) *s basis i) x < e"
 	   "dist (x + (e / 2) *s basis i) x < e"
-	unfolding dist_def apply auto
+	unfolding dist_norm apply auto
 	unfolding norm_minus_cancel and norm_mul using norm_basis[of i] and `e>0` by auto
       hence "a $ i \<le> (x - (e / 2) *s basis i) $ i"
                     "(x + (e / 2) *s basis i) $ i \<le> b $ i"
@@ -4601,8 +4810,8 @@
     def f == "\<lambda>n::nat. x + (inverse (real n + 1)) *s (?c - x)"
     { fix n assume fn:"f n < b \<longrightarrow> a < f n \<longrightarrow> f n = x" and xc:"x \<noteq> ?c"
       have *:"0 < inverse (real n + 1)" "inverse (real n + 1) \<le> 1" unfolding inverse_le_1_iff by auto
-      have "inverse (real n + 1) *s (1 / 2) *s (a + b) + (1 - inverse (real n + 1)) *s x =
-	x + inverse (real n + 1) *s ((1 / 2) *s (a + b) - x)" by (auto simp add: vector_ssub_ldistrib vector_add_ldistrib field_simps vector_sadd_rdistrib[THEN sym])
+      have "(inverse (real n + 1)) *s ((1 / 2) *s (a + b)) + (1 - inverse (real n + 1)) *s x =
+	x + (inverse (real n + 1)) *s ((1 / 2 *s (a + b)) - x)" by (auto simp add: vector_ssub_ldistrib vector_add_ldistrib field_simps vector_sadd_rdistrib[THEN sym])
       hence "f n < b" and "a < f n" using open_closed_interval_convex[OF open_interval_midpoint[OF assms] as *] unfolding f_def by auto
       hence False using fn unfolding f_def using xc by(auto simp add: vector_mul_lcancel vector_ssub_ldistrib)  }
     moreover
@@ -4651,11 +4860,13 @@
   using bounded_subset_closed_interval_symmetric[of s] by auto
 
 lemma frontier_closed_interval:
- "frontier {a .. b} = {a .. b} - {a<..<b}"
+  fixes a b :: "real ^ _"
+  shows "frontier {a .. b} = {a .. b} - {a<..<b}"
   unfolding frontier_def unfolding interior_closed_interval and closure_closed[OF closed_interval] ..
 
 lemma frontier_open_interval:
- "frontier {a<..<b} = (if {a<..<b} = {} then {} else {a .. b} - {a<..<b})"
+  fixes a b :: "real ^ _"
+  shows "frontier {a<..<b} = (if {a<..<b} = {} then {} else {a .. b} - {a<..<b})"
 proof(cases "{a<..<b} = {}")
   case True thus ?thesis using frontier_empty by auto
 next
@@ -4707,7 +4918,7 @@
 using set_eq_subset[of "{a .. b}" "{c .. d}"]
 using subset_interval_1(1)[of a b c d]
 using subset_interval_1(1)[of c d a b]
-by auto
+by auto (* FIXME: slow *)
 
 lemma disjoint_interval_1: fixes a :: "real^1" shows
   "{a .. b} \<inter> {c .. d} = {} \<longleftrightarrow> dest_vec1 b < dest_vec1 a \<or> dest_vec1 d < dest_vec1 c  \<or>  dest_vec1 b < dest_vec1 c \<or> dest_vec1 d < dest_vec1 a"
@@ -4732,7 +4943,7 @@
     fix x::"real^'n" assume x:"\<forall>e>0. \<exists>x'\<in>{x. \<forall>i. x $ i \<le> b $ i}. x' \<noteq> x \<and> dist x' x < e"
     { assume "x$i > b$i"
       then obtain y where "y $ i \<le> b $ i"  "y \<noteq> x"  "dist y x < x$i - b$i" using x[THEN spec[where x="x$i - b$i"]] by auto
-      hence False using component_le_norm[of "y - x" i] unfolding dist_def and vector_minus_component by auto   }
+      hence False using component_le_norm[of "y - x" i] unfolding dist_norm and vector_minus_component by auto   }
     hence "x$i \<le> b$i" by(rule ccontr)auto  }
   thus ?thesis unfolding closed_limpt unfolding islimpt_approachable by blast
 qed
@@ -4744,23 +4955,19 @@
     fix x::"real^'n" assume x:"\<forall>e>0. \<exists>x'\<in>{x. \<forall>i. a $ i \<le> x $ i}. x' \<noteq> x \<and> dist x' x < e"
     { assume "a$i > x$i"
       then obtain y where "a $ i \<le> y $ i"  "y \<noteq> x"  "dist y x < a$i - x$i" using x[THEN spec[where x="a$i - x$i"]] by auto
-      hence False using component_le_norm[of "y - x" i] unfolding dist_def and vector_minus_component by auto   }
+      hence False using component_le_norm[of "y - x" i] unfolding dist_norm and vector_minus_component by auto   }
     hence "a$i \<le> x$i" by(rule ccontr)auto  }
   thus ?thesis unfolding closed_limpt unfolding islimpt_approachable by blast
 qed
 
 subsection{* Intervals in general, including infinite and mixtures of open and closed. *}
 
-definition "is_interval s \<longleftrightarrow> (\<forall>a\<in>s. \<forall>b\<in>s. \<forall>x. a \<le> x \<and> x \<le> b \<longrightarrow> x \<in> s)"
-
-lemma is_interval_interval: fixes a::"real^'n::finite" shows
-  "is_interval {a<..<b}" "is_interval {a .. b}"
-  unfolding is_interval_def apply(auto simp add: vector_less_def vector_less_eq_def)
-  apply(erule_tac x=i in allE)+ apply simp
-  apply(erule_tac x=i in allE)+ apply simp
-  apply(erule_tac x=i in allE)+ apply simp
-  apply(erule_tac x=i in allE)+ apply simp
-  done
+definition "is_interval s \<longleftrightarrow> (\<forall>a\<in>s. \<forall>b\<in>s. \<forall>x. (\<forall>i. ((a$i \<le> x$i \<and> x$i \<le> b$i) \<or> (b$i \<le> x$i \<and> x$i \<le> a$i)))  \<longrightarrow> x \<in> s)"
+
+lemma is_interval_interval: "is_interval {a .. b::real^'n::finite}" (is ?th1) "is_interval {a<..<b}" (is ?th2) proof - 
+  have *:"\<And>x y z::real. x < y \<Longrightarrow> y < z \<Longrightarrow> x < z" by auto
+  show ?th1 ?th2  unfolding is_interval_def mem_interval Ball_def atLeastAtMost_iff
+    by(meson real_le_trans le_less_trans less_le_trans *)+ qed
 
 lemma is_interval_empty:
  "is_interval {}"
@@ -4781,20 +4988,27 @@
 next
   case False
   { fix e::real
-    assume "0 < e"  "\<forall>e>0. \<exists>y. (\<exists>x. netord net x y) \<and> (\<forall>x. netord net x y \<longrightarrow> dist l (f x) < e)"
-    then obtain x y where x:"netord net x y" and y:"\<forall>x. netord net x y \<longrightarrow> dist l (f x) < e / norm a" apply(erule_tac x="e / norm a" in allE) apply auto using False using norm_ge_zero[of a] apply auto
-      using divide_pos_pos[of e "norm a"] by auto
-    { fix z assume "netord net z y" hence "dist l (f z) < e / norm a" using y by blast
-      hence "norm a * norm (l - f z) < e" unfolding dist_def and
+    assume "0 < e"
+    with `a \<noteq> vec 0` have "0 < e / norm a" by (simp add: divide_pos_pos)
+    with assms(1) have "eventually (\<lambda>x. dist (f x) l < e / norm a) net"
+      by (rule tendstoD)
+    moreover
+    { fix z assume "dist (f z) l < e / norm a"
+      hence "norm a * norm (f z - l) < e" unfolding dist_norm and
 	pos_less_divide_eq[OF False[unfolded vec_0 zero_less_norm_iff[of a, THEN sym]]] and real_mult_commute by auto
-      hence "\<bar>a \<bullet> l - a \<bullet> f z\<bar> < e" using order_le_less_trans[OF norm_cauchy_schwarz_abs[of a "l - f z"], of e] unfolding dot_rsub[symmetric] by auto  }
-    hence "\<exists>y. (\<exists>x. netord net x y) \<and> (\<forall>x. netord net x y \<longrightarrow> \<bar>a \<bullet> l - a \<bullet> f x\<bar> < e)" using x by auto  }
-  thus ?thesis using assms unfolding Lim apply (auto simp add: dist_sym)
-    unfolding dist_vec1 by auto
+      hence "\<bar>a \<bullet> f z - a \<bullet> l\<bar> < e"
+        using order_le_less_trans[OF norm_cauchy_schwarz_abs[of a "f z - l"], of e]
+        unfolding dot_rsub[symmetric] by auto  }
+    ultimately have "eventually (\<lambda>x. \<bar>a \<bullet> f x - a \<bullet> l\<bar> < e) net"
+      by (auto elim: eventually_rev_mono)
+  }
+  thus ?thesis unfolding tendsto_def
+    by (auto simp add: dist_vec1)
 qed
 
 lemma continuous_at_vec1_dot:
- "continuous (at x) (vec1 o (\<lambda>y. a \<bullet> y))"
+  fixes x :: "real ^ _"
+  shows "continuous (at x) (vec1 o (\<lambda>y. a \<bullet> y))"
 proof-
   have "((\<lambda>x. x) ---> x) (at x)" unfolding Lim_at by auto
   thus ?thesis unfolding continuous_at and o_def using Lim_vec1_dot[of "\<lambda>x. x" x "at x" a] by auto
@@ -4821,10 +5035,10 @@
   thus ?thesis unfolding closed_closedin[THEN sym] and * by auto
 qed
 
-lemma closed_halfspace_ge: "closed {x. a \<bullet> x \<ge> b}"
+lemma closed_halfspace_ge: "closed {x::real^_. a \<bullet> x \<ge> b}"
   using closed_halfspace_le[of "-a" "-b"] unfolding dot_lneg by auto
 
-lemma closed_hyperplane: "closed {x. a \<bullet> x = b}"
+lemma closed_hyperplane: "closed {x::real^_. a \<bullet> x = b}"
 proof-
   have "{x. a \<bullet> x = b} = {x. a \<bullet> x \<ge> b} \<inter> {x. a \<bullet> x \<le> b}" by auto
   thus ?thesis using closed_halfspace_le[of a b] and closed_halfspace_ge[of b a] using closed_Int by auto
@@ -4840,13 +5054,13 @@
 
 text{* Openness of halfspaces.                                                   *}
 
-lemma open_halfspace_lt: "open {x. a \<bullet> x < b}"
+lemma open_halfspace_lt: "open {x::real^_. a \<bullet> x < b}"
 proof-
   have "UNIV - {x. b \<le> a \<bullet> x} = {x. a \<bullet> x < b}" by auto
   thus ?thesis using closed_halfspace_ge[unfolded closed_def, of b a] by auto
 qed
 
-lemma open_halfspace_gt: "open {x. a \<bullet> x > b}"
+lemma open_halfspace_gt: "open {x::real^_. a \<bullet> x > b}"
 proof-
   have "UNIV - {x. b \<ge> a \<bullet> x} = {x. a \<bullet> x > b}" by auto
   thus ?thesis using closed_halfspace_le[unfolded closed_def, of a b] by auto
@@ -4955,7 +5169,7 @@
   hence "\<forall>m n. m \<le> n \<longrightarrow> dest_vec1 (s m) \<le> dest_vec1 (s n)" by auto
   then obtain l where "\<forall>e>0. \<exists>N. \<forall>n\<ge>N. \<bar>dest_vec1 (s n) - l\<bar> < e" using convergent_bounded_monotone[OF a] by auto
   thus ?thesis unfolding Lim_sequentially apply(rule_tac x="vec1 l" in exI)
-    unfolding dist_def unfolding abs_dest_vec1 and dest_vec1_sub by auto
+    unfolding dist_norm unfolding abs_dest_vec1 and dest_vec1_sub by auto
 qed
 
 subsection{* Basic homeomorphism definitions.                                          *}
@@ -5094,19 +5308,19 @@
   show ?th unfolding homeomorphic_minimal
     apply(rule_tac x="\<lambda>x. b + (e/d) *s (x - a)" in exI)
     apply(rule_tac x="\<lambda>x. a + (d/e) *s (x - b)" in exI)
-    apply (auto simp add: dist_sym) unfolding dist_def and vector_smult_assoc using assms apply auto
+    apply (auto simp add: dist_commute) unfolding dist_norm and vector_smult_assoc using assms apply auto
     unfolding norm_minus_cancel and norm_mul
     using continuous_on_add[OF continuous_on_const continuous_on_cmul[OF continuous_on_sub[OF continuous_on_id continuous_on_const]]]
-    apply (auto simp add: dist_sym)
+    apply (auto simp add: dist_commute)
     using pos_less_divide_eq[OF *(1), THEN sym] unfolding real_mult_commute[of _ "\<bar>e / d\<bar>"]
     using pos_less_divide_eq[OF *(2), THEN sym] unfolding real_mult_commute[of _ "\<bar>d / e\<bar>"]
-    by (auto simp add: dist_sym)
+    by (auto simp add: dist_commute)
 next
   have *:"\<bar>e / d\<bar> > 0" "\<bar>d / e\<bar> >0" using assms using divide_pos_pos by auto
   show ?cth unfolding homeomorphic_minimal
     apply(rule_tac x="\<lambda>x. b + (e/d) *s (x - a)" in exI)
     apply(rule_tac x="\<lambda>x. a + (d/e) *s (x - b)" in exI)
-    apply (auto simp add: dist_sym) unfolding dist_def and vector_smult_assoc using assms apply auto
+    apply (auto simp add: dist_commute) unfolding dist_norm and vector_smult_assoc using assms apply auto
     unfolding norm_minus_cancel and norm_mul
     using continuous_on_add[OF continuous_on_const continuous_on_cmul[OF continuous_on_sub[OF continuous_on_id continuous_on_const]]]
     apply auto
@@ -5118,12 +5332,13 @@
 text{* "Isometry" (up to constant bounds) of injective linear map etc.           *}
 
 lemma cauchy_isometric:
-  assumes e:"0 < e" and s:"subspace s" and f:"linear f" and normf:"\<forall>x\<in>s. norm(f x) \<ge> e * norm(x)" and xs:"\<forall>n::nat. x n \<in> s" and cf:"cauchy(f o x)"
-  shows "cauchy x"
+  fixes x :: "nat \<Rightarrow> real ^ 'n::finite"
+  assumes e:"0 < e" and s:"subspace s" and f:"linear f" and normf:"\<forall>x\<in>s. norm(f x) \<ge> e * norm(x)" and xs:"\<forall>n::nat. x n \<in> s" and cf:"Cauchy(f o x)"
+  shows "Cauchy x"
 proof-
   { fix d::real assume "d>0"
     then obtain N where N:"\<forall>n\<ge>N. norm (f (x n) - f (x N)) < e * d"
-      using cf[unfolded cauchy o_def dist_def, THEN spec[where x="e*d"]] and e and mult_pos_pos[of e d] by auto
+      using cf[unfolded cauchy o_def dist_norm, THEN spec[where x="e*d"]] and e and mult_pos_pos[of e d] by auto
     { fix n assume "n\<ge>N"
       hence "norm (f (x n - x N)) < e * d" using N[THEN spec[where x=n]] unfolding linear_sub[OF f, THEN sym] by auto
       moreover have "e * norm (x n - x N) \<le> norm (f (x n - x N))"
@@ -5132,14 +5347,14 @@
       ultimately have "norm (x n - x N) < d" using `e>0`
 	using mult_left_less_imp_less[of e "norm (x n - x N)" d] by auto   }
     hence "\<exists>N. \<forall>n\<ge>N. norm (x n - x N) < d" by auto }
-  thus ?thesis unfolding cauchy and dist_def by auto
+  thus ?thesis unfolding cauchy and dist_norm by auto
 qed
 
 lemma complete_isometric_image:
   assumes "0 < e" and s:"subspace s" and f:"linear f" and normf:"\<forall>x\<in>s. norm(f x) \<ge> e * norm(x)" and cs:"complete s"
   shows "complete(f ` s)"
 proof-
-  { fix g assume as:"\<forall>n::nat. g n \<in> f ` s" and cfg:"cauchy g"
+  { fix g assume as:"\<forall>n::nat. g n \<in> f ` s" and cfg:"Cauchy g"
     then obtain x where "\<forall>n. x n \<in> s \<and> g n = f (x n)" unfolding image_iff and Bex_def
       using choice[of "\<lambda> n xa. xa \<in> s \<and> g n = f xa"] by auto
     hence x:"\<forall>n. x n \<in> s"  "\<forall>n. g n = f (x n)" by auto
@@ -5153,7 +5368,10 @@
   thus ?thesis unfolding complete_def by auto
 qed
 
-lemma dist_0_norm:"dist 0 x = norm x" unfolding dist_def by(auto simp add: norm_minus_cancel)
+lemma dist_0_norm:
+  fixes x :: "'a::real_normed_vector"
+  shows "dist 0 x = norm x"
+unfolding dist_norm by simp
 
 lemma injective_imp_isometric: fixes f::"real^'m::finite \<Rightarrow> real^'n::finite"
   assumes s:"closed s"  "subspace s"  and f:"linear f" "\<forall>x\<in>s. (f x = 0) \<longrightarrow> (x = 0)"
@@ -5172,7 +5390,7 @@
   let ?S' = "{x::real^'m. x\<in>s \<and> norm x = norm a}"
   let ?S'' = "{x::real^'m. norm x = norm a}"
 
-  have "?S'' = frontier(cball 0 (norm a))" unfolding frontier_cball and dist_def by (auto simp add: norm_minus_cancel)
+  have "?S'' = frontier(cball 0 (norm a))" unfolding frontier_cball and dist_norm by (auto simp add: norm_minus_cancel)
   hence "compact ?S''" using compact_frontier[OF compact_cball, of 0 "norm a"] by auto
   moreover have "?S' = s \<inter> ?S''" by auto
   ultimately have "compact ?S'" using closed_inter_compact[of s ?S''] using s(1) by auto
@@ -5206,6 +5424,7 @@
 qed
 
 lemma closed_injective_image_subspace:
+  fixes s :: "(real ^ _) set"
   assumes "subspace s" "linear f" "\<forall>x\<in>s. f x = 0 --> x = 0" "closed s"
   shows "closed(f ` s)"
 proof-
@@ -5330,7 +5549,8 @@
   by auto
 
 lemma dim_closure:
- "dim(closure s) = dim s" (is "?dc = ?d")
+  fixes s :: "(real ^ _) set"
+  shows "dim(closure s) = dim s" (is "?dc = ?d")
 proof-
   have "?dc \<le> ?d" using closure_minimal[OF span_inc, of s]
     using closed_subspace[OF subspace_span, of s]
@@ -5431,7 +5651,11 @@
   ultimately show ?thesis using False by auto
 qed
 
-subsection{* Banach fixed point theorem (not really topological...)                    *}
+lemma image_smult_interval:"(\<lambda>x. m *s (x::real^'n::finite)) ` {a..b} =
+  (if {a..b} = {} then {} else if 0 \<le> m then {m *s a..m *s b} else {m *s b..m *s a})"
+  using image_affinity_interval[of m 0 a b] by auto
+
+subsection{* Banach fixed point theorem (not really topological...) *}
 
 lemma banach_fix:
   assumes s:"complete s" "s \<noteq> {}" and c:"0 \<le> c" "c < 1" and f:"(f ` s) \<subseteq> s" and
@@ -5479,7 +5703,7 @@
       also have "\<dots> = (c ^ m) * (d * (1 - c ^ k) + (1 - c) * c ^ k * d)"
 	unfolding power_add by (auto simp add: ring_simps)
       also have "\<dots> \<le> (c ^ m) * d * (1 - c ^ Suc k)"
-	using c by (auto simp add: ring_simps dist_pos_le)
+	using c by (auto simp add: ring_simps)
       finally show ?case by auto
     qed
   } note cf_z2 = this
@@ -5487,10 +5711,10 @@
     hence "\<exists>N. \<forall>m n. N \<le> m \<and> N \<le> n \<longrightarrow> dist (z m) (z n) < e"
     proof(cases "d = 0")
       case True
-      hence "\<And>n. z n = z0" using cf_z2[of 0] and c unfolding z_def by (auto simp add: pos_prod_le[OF `1 - c > 0`] dist_le_0)
+      hence "\<And>n. z n = z0" using cf_z2[of 0] and c unfolding z_def by (auto simp add: pos_prod_le[OF `1 - c > 0`])
       thus ?thesis using `e>0` by auto
     next
-      case False hence "d>0" unfolding d_def using dist_pos_le[of "z 0" "z 1"]
+      case False hence "d>0" unfolding d_def using zero_le_dist[of "z 0" "z 1"]
 	by (metis False d_def real_less_def)
       hence "0 < e * (1 - c) / d" using `e>0` and `1-c>0`
 	using divide_pos_pos[of "e * (1 - c)" d] and mult_pos_pos[of e "1 - c"] by auto
@@ -5505,7 +5729,7 @@
 
 	have "dist (z m) (z n) \<le> c ^ n * d * (1 - c ^ (m - n)) / (1 - c)"
 	  using cf_z2[of n "m - n"] and `m>n` unfolding pos_le_divide_eq[OF `1-c>0`]
-	  by (auto simp add: real_mult_commute dist_sym)
+	  by (auto simp add: real_mult_commute dist_commute)
 	also have "\<dots> \<le> c ^ N * d * (1 - c ^ (m - n)) / (1 - c)"
 	  using mult_right_mono[OF * order_less_imp_le[OF **]]
 	  unfolding real_mult_assoc by auto
@@ -5520,25 +5744,25 @@
 	proof(cases "n = m")
 	  case True thus ?thesis using `e>0` by auto
 	next
-	  case False thus ?thesis using as and *[of n m] *[of m n] unfolding nat_neq_iff by (auto simp add: dist_sym)
+	  case False thus ?thesis using as and *[of n m] *[of m n] unfolding nat_neq_iff by (auto simp add: dist_commute)
 	qed }
       thus ?thesis by auto
     qed
   }
-  hence "cauchy z" unfolding cauchy_def by auto
+  hence "Cauchy z" unfolding cauchy_def by auto
   then obtain x where "x\<in>s" and x:"(z ---> x) sequentially" using s(1)[unfolded compact_def complete_def, THEN spec[where x=z]] and z_in_s by auto
 
   def e \<equiv> "dist (f x) x"
   have "e = 0" proof(rule ccontr)
-    assume "e \<noteq> 0" hence "e>0" unfolding e_def using dist_pos_le[of "f x" x]
-      by (metis dist_eq_0 dist_nz dist_sym e_def)
+    assume "e \<noteq> 0" hence "e>0" unfolding e_def using zero_le_dist[of "f x" x]
+      by (metis dist_eq_0_iff dist_nz e_def)
     then obtain N where N:"\<forall>n\<ge>N. dist (z n) x < e / 2"
       using x[unfolded Lim_sequentially, THEN spec[where x="e/2"]] by auto
     hence N':"dist (z N) x < e / 2" by auto
 
     have *:"c * dist (z N) x \<le> dist (z N) x" unfolding mult_le_cancel_right2
-      using dist_pos_le[of "z N" x] and c
-      by (metis dist_eq_0 dist_nz dist_sym order_less_asym real_less_def)
+      using zero_le_dist[of "z N" x] and c
+      by (metis dist_eq_0_iff dist_nz order_less_asym real_less_def)
     have "dist (f (z N)) (f x) \<le> c * dist (z N) x" using lipschitz[THEN bspec[where x="z N"], THEN bspec[where x=x]]
       using z_in_s[of N] `x\<in>s` using c by auto
     also have "\<dots> < e / 2" using N' and c using * by auto
@@ -5546,14 +5770,14 @@
       using N[THEN spec[where x="Suc N"]] and dist_triangle_half_r[of "z (Suc N)" "f x" e x]
       unfolding e_def by auto
   qed
-  hence "f x = x" unfolding e_def and dist_eq_0 by auto
+  hence "f x = x" unfolding e_def by auto
   moreover
   { fix y assume "f y = y" "y\<in>s"
     hence "dist x y \<le> c * dist x y" using lipschitz[THEN bspec[where x=x], THEN bspec[where x=y]]
       using `x\<in>s` and `f x = x` by auto
     hence "dist x y = 0" unfolding mult_le_cancel_right1
-      using c and dist_pos_le[of x y] by auto
-    hence "y = x" unfolding dist_eq_0 by auto
+      using c and zero_le_dist[of x y] by auto
+    hence "y = x" by auto
   }
   ultimately show ?thesis unfolding Bex1_def using `x\<in>s` by blast+
 qed
@@ -5623,9 +5847,9 @@
     unfolding o_def and h_def a_def b_def  by auto
 
   { fix n::nat
-    have *:"\<And>fx fy x y. dist fx fy \<le> dist x y \<Longrightarrow> \<not> (dist (fx - fy) (a - b) < dist a b - dist x y)" unfolding dist_def by norm
+    have *:"\<And>fx fy (x::real^_) y. dist fx fy \<le> dist x y \<Longrightarrow> \<not> (dist (fx - fy) (a - b) < dist a b - dist x y)" unfolding dist_norm by norm
     { fix x y ::"real^'a"
-      have "dist (-x) (-y) = dist x y" unfolding dist_def
+      have "dist (-x) (-y) = dist x y" unfolding dist_norm
 	using norm_minus_cancel[of "x - y"] by (auto simp add: uminus_add_conv_diff) } note ** = this
 
     { assume as:"dist a b > dist (f n x) (f n y)"
@@ -5637,7 +5861,7 @@
 	apply(erule_tac x="Na+Nb+n" in allE) apply simp
 	using dist_triangle_add_half[of a "f (r (Na + Nb + n)) x" "dist a b - dist (f n x) (f n y)"
           "-b"  "- f (r (Na + Nb + n)) y"]
-	unfolding ** unfolding group_simps(12) by (auto simp add: dist_sym)
+	unfolding ** unfolding group_simps(12) by (auto simp add: dist_commute)
       moreover
       have "dist (f (r (Na + Nb + n)) x - f (r (Na + Nb + n)) y) (a - b) \<ge> dist a b - dist (f n x) (f n y)"
 	using distf[of n "r (Na+Nb+n)", OF _ `x\<in>s` `y\<in>s`]
--- a/src/HOL/Library/comm_ring.ML	Mon Jun 01 09:26:28 2009 +0200
+++ b/src/HOL/Library/comm_ring.ML	Tue Jun 02 12:18:08 2009 +0200
@@ -100,13 +100,10 @@
     THEN (simp_tac cring_ss i)
   end);
 
-val comm_ring_meth =
-  Method.ctxt_args (SIMPLE_METHOD' o comm_ring_tac);
-
 val setup =
-  Method.add_method ("comm_ring", comm_ring_meth,
-    "reflective decision procedure for equalities over commutative rings") #>
-  Method.add_method ("algebra", comm_ring_meth,
-    "method for proving algebraic properties (same as comm_ring)");
+  Method.setup @{binding comm_ring} (Scan.succeed (SIMPLE_METHOD' o comm_ring_tac))
+    "reflective decision procedure for equalities over commutative rings" #>
+  Method.setup @{binding algebra} (Scan.succeed (SIMPLE_METHOD' o comm_ring_tac))
+    "method for proving algebraic properties (same as comm_ring)";
 
 end;
--- a/src/HOL/Library/normarith.ML	Mon Jun 01 09:26:28 2009 +0200
+++ b/src/HOL/Library/normarith.ML	Tue Jun 02 12:18:08 2009 +0200
@@ -391,7 +391,7 @@
 
   fun init_conv ctxt = 
    Simplifier.rewrite (Simplifier.context ctxt 
-     (HOL_basic_ss addsimps ([@{thm vec_0}, @{thm vec_1}, @{thm dist_def}, @{thm diff_0_right}, @{thm right_minus}, @{thm diff_self}, @{thm norm_0}] @ @{thms arithmetic_simps} @ @{thms norm_pths})))
+     (HOL_basic_ss addsimps ([@{thm vec_0}, @{thm vec_1}, @{thm vector_dist_norm}, @{thm diff_0_right}, @{thm right_minus}, @{thm diff_self}, @{thm norm_0}] @ @{thms arithmetic_simps} @ @{thms norm_pths})))
    then_conv field_comp_conv 
    then_conv nnf_conv
 
--- a/src/HOL/Lim.thy	Mon Jun 01 09:26:28 2009 +0200
+++ b/src/HOL/Lim.thy	Tue Jun 02 12:18:08 2009 +0200
@@ -13,90 +13,102 @@
 text{*Standard Definitions*}
 
 definition
-  LIM :: "['a::real_normed_vector => 'b::real_normed_vector, 'a, 'b] => bool"
+  at :: "'a::metric_space \<Rightarrow> 'a filter" where
+  [code del]: "at a = Abs_filter (\<lambda>P. \<exists>r>0. \<forall>x. x \<noteq> a \<and> dist x a < r \<longrightarrow> P x)"
+
+definition
+  LIM :: "['a::metric_space \<Rightarrow> 'b::metric_space, 'a, 'b] \<Rightarrow> bool"
         ("((_)/ -- (_)/ --> (_))" [60, 0, 60] 60) where
   [code del]: "f -- a --> L =
-     (\<forall>r > 0. \<exists>s > 0. \<forall>x. x \<noteq> a & norm (x - a) < s
-        --> norm (f x - L) < r)"
+     (\<forall>r > 0. \<exists>s > 0. \<forall>x. x \<noteq> a & dist x a < s
+        --> dist (f x) L < r)"
 
 definition
-  isCont :: "['a::real_normed_vector => 'b::real_normed_vector, 'a] => bool" where
+  isCont :: "['a::metric_space \<Rightarrow> 'b::metric_space, 'a] \<Rightarrow> bool" where
   "isCont f a = (f -- a --> (f a))"
 
 definition
-  isUCont :: "['a::real_normed_vector => 'b::real_normed_vector] => bool" where
-  [code del]: "isUCont f = (\<forall>r>0. \<exists>s>0. \<forall>x y. norm (x - y) < s \<longrightarrow> norm (f x - f y) < r)"
+  isUCont :: "['a::metric_space \<Rightarrow> 'b::metric_space] \<Rightarrow> bool" where
+  [code del]: "isUCont f = (\<forall>r>0. \<exists>s>0. \<forall>x y. dist x y < s \<longrightarrow> dist (f x) (f y) < r)"
+
+subsection {* Neighborhood Filter *}
 
+lemma eventually_at:
+  "eventually P (at a) \<longleftrightarrow> (\<exists>d>0. \<forall>x. x \<noteq> a \<and> dist x a < d \<longrightarrow> P x)"
+unfolding at_def
+apply (rule eventually_Abs_filter)
+apply (rule_tac x=1 in exI, simp)
+apply (clarify, rule_tac x=r in exI, simp)
+apply (clarify, rename_tac r s)
+apply (rule_tac x="min r s" in exI, simp)
+done
+
+lemma LIM_conv_tendsto: "(f -- a --> L) \<longleftrightarrow> tendsto f L (at a)"
+unfolding LIM_def tendsto_def eventually_at ..
 
 subsection {* Limits of Functions *}
 
-subsubsection {* Purely standard proofs *}
+lemma metric_LIM_I:
+  "(\<And>r. 0 < r \<Longrightarrow> \<exists>s>0. \<forall>x. x \<noteq> a \<and> dist x a < s \<longrightarrow> dist (f x) L < r)
+    \<Longrightarrow> f -- a --> L"
+by (simp add: LIM_def)
+
+lemma metric_LIM_D:
+  "\<lbrakk>f -- a --> L; 0 < r\<rbrakk>
+    \<Longrightarrow> \<exists>s>0. \<forall>x. x \<noteq> a \<and> dist x a < s \<longrightarrow> dist (f x) L < r"
+by (simp add: LIM_def)
 
 lemma LIM_eq:
-     "f -- a --> L =
+  fixes a :: "'a::real_normed_vector" and L :: "'b::real_normed_vector"
+  shows "f -- a --> L =
      (\<forall>r>0.\<exists>s>0.\<forall>x. x \<noteq> a & norm (x-a) < s --> norm (f x - L) < r)"
-by (simp add: LIM_def diff_minus)
+by (simp add: LIM_def dist_norm)
 
 lemma LIM_I:
-     "(!!r. 0<r ==> \<exists>s>0.\<forall>x. x \<noteq> a & norm (x-a) < s --> norm (f x - L) < r)
+  fixes a :: "'a::real_normed_vector" and L :: "'b::real_normed_vector"
+  shows "(!!r. 0<r ==> \<exists>s>0.\<forall>x. x \<noteq> a & norm (x-a) < s --> norm (f x - L) < r)
       ==> f -- a --> L"
 by (simp add: LIM_eq)
 
 lemma LIM_D:
-     "[| f -- a --> L; 0<r |]
+  fixes a :: "'a::real_normed_vector" and L :: "'b::real_normed_vector"
+  shows "[| f -- a --> L; 0<r |]
       ==> \<exists>s>0.\<forall>x. x \<noteq> a & norm (x-a) < s --> norm (f x - L) < r"
 by (simp add: LIM_eq)
 
-lemma LIM_offset: "f -- a --> L \<Longrightarrow> (\<lambda>x. f (x + k)) -- a - k --> L"
-apply (rule LIM_I)
-apply (drule_tac r="r" in LIM_D, safe)
+lemma LIM_offset:
+  fixes a :: "'a::real_normed_vector" and L :: "'b::metric_space"
+  shows "f -- a --> L \<Longrightarrow> (\<lambda>x. f (x + k)) -- a - k --> L"
+unfolding LIM_def dist_norm
+apply clarify
+apply (drule_tac x="r" in spec, safe)
 apply (rule_tac x="s" in exI, safe)
 apply (drule_tac x="x + k" in spec)
 apply (simp add: algebra_simps)
 done
 
-lemma LIM_offset_zero: "f -- a --> L \<Longrightarrow> (\<lambda>h. f (a + h)) -- 0 --> L"
+lemma LIM_offset_zero:
+  fixes a :: "'a::real_normed_vector" and L :: "'b::metric_space"
+  shows "f -- a --> L \<Longrightarrow> (\<lambda>h. f (a + h)) -- 0 --> L"
 by (drule_tac k="a" in LIM_offset, simp add: add_commute)
 
-lemma LIM_offset_zero_cancel: "(\<lambda>h. f (a + h)) -- 0 --> L \<Longrightarrow> f -- a --> L"
+lemma LIM_offset_zero_cancel:
+  fixes a :: "'a::real_normed_vector" and L :: "'b::metric_space"
+  shows "(\<lambda>h. f (a + h)) -- 0 --> L \<Longrightarrow> f -- a --> L"
 by (drule_tac k="- a" in LIM_offset, simp)
 
 lemma LIM_const [simp]: "(%x. k) -- x --> k"
 by (simp add: LIM_def)
 
 lemma LIM_add:
-  fixes f g :: "'a::real_normed_vector \<Rightarrow> 'b::real_normed_vector"
+  fixes f g :: "'a::metric_space \<Rightarrow> 'b::real_normed_vector"
   assumes f: "f -- a --> L" and g: "g -- a --> M"
-  shows "(%x. f x + g(x)) -- a --> (L + M)"
-proof (rule LIM_I)
-  fix r :: real
-  assume r: "0 < r"
-  from LIM_D [OF f half_gt_zero [OF r]]
-  obtain fs
-    where fs:    "0 < fs"
-      and fs_lt: "\<forall>x. x \<noteq> a & norm (x-a) < fs --> norm (f x - L) < r/2"
-  by blast
-  from LIM_D [OF g half_gt_zero [OF r]]
-  obtain gs
-    where gs:    "0 < gs"
-      and gs_lt: "\<forall>x. x \<noteq> a & norm (x-a) < gs --> norm (g x - M) < r/2"
-  by blast
-  show "\<exists>s>0.\<forall>x. x \<noteq> a \<and> norm (x-a) < s \<longrightarrow> norm (f x + g x - (L + M)) < r"
-  proof (intro exI conjI strip)
-    show "0 < min fs gs"  by (simp add: fs gs)
-    fix x :: 'a
-    assume "x \<noteq> a \<and> norm (x-a) < min fs gs"
-    hence "x \<noteq> a \<and> norm (x-a) < fs \<and> norm (x-a) < gs" by simp
-    with fs_lt gs_lt
-    have "norm (f x - L) < r/2" and "norm (g x - M) < r/2" by blast+
-    hence "norm (f x - L) + norm (g x - M) < r" by arith
-    thus "norm (f x + g x - (L + M)) < r"
-      by (blast intro: norm_diff_triangle_ineq order_le_less_trans)
-  qed
-qed
+  shows "(\<lambda>x. f x + g x) -- a --> (L + M)"
+using assms unfolding LIM_conv_tendsto by (rule tendsto_add)
 
 lemma LIM_add_zero:
-  "\<lbrakk>f -- a --> 0; g -- a --> 0\<rbrakk> \<Longrightarrow> (\<lambda>x. f x + g x) -- a --> 0"
+  fixes f g :: "'a::metric_space \<Rightarrow> 'b::real_normed_vector"
+  shows "\<lbrakk>f -- a --> 0; g -- a --> 0\<rbrakk> \<Longrightarrow> (\<lambda>x. f x + g x) -- a --> 0"
 by (drule (1) LIM_add, simp)
 
 lemma minus_diff_minus:
@@ -104,46 +116,75 @@
   shows "(- a) - (- b) = - (a - b)"
 by simp
 
-lemma LIM_minus: "f -- a --> L ==> (%x. -f(x)) -- a --> -L"
-by (simp only: LIM_eq minus_diff_minus norm_minus_cancel)
+lemma LIM_minus:
+  fixes f :: "'a::metric_space \<Rightarrow> 'b::real_normed_vector"
+  shows "f -- a --> L \<Longrightarrow> (\<lambda>x. - f x) -- a --> - L"
+unfolding LIM_conv_tendsto by (rule tendsto_minus)
 
+(* TODO: delete *)
 lemma LIM_add_minus:
-    "[| f -- x --> l; g -- x --> m |] ==> (%x. f(x) + -g(x)) -- x --> (l + -m)"
+  fixes f g :: "'a::metric_space \<Rightarrow> 'b::real_normed_vector"
+  shows "[| f -- x --> l; g -- x --> m |] ==> (%x. f(x) + -g(x)) -- x --> (l + -m)"
 by (intro LIM_add LIM_minus)
 
 lemma LIM_diff:
-    "[| f -- x --> l; g -- x --> m |] ==> (%x. f(x) - g(x)) -- x --> l-m"
-by (simp only: diff_minus LIM_add LIM_minus)
+  fixes f g :: "'a::metric_space \<Rightarrow> 'b::real_normed_vector"
+  shows "\<lbrakk>f -- x --> l; g -- x --> m\<rbrakk> \<Longrightarrow> (\<lambda>x. f x - g x) -- x --> l - m"
+unfolding LIM_conv_tendsto by (rule tendsto_diff)
 
-lemma LIM_zero: "f -- a --> l \<Longrightarrow> (\<lambda>x. f x - l) -- a --> 0"
-by (simp add: LIM_def)
-
-lemma LIM_zero_cancel: "(\<lambda>x. f x - l) -- a --> 0 \<Longrightarrow> f -- a --> l"
-by (simp add: LIM_def)
+lemma LIM_zero:
+  fixes f :: "'a::metric_space \<Rightarrow> 'b::real_normed_vector"
+  shows "f -- a --> l \<Longrightarrow> (\<lambda>x. f x - l) -- a --> 0"
+by (simp add: LIM_def dist_norm)
 
-lemma LIM_zero_iff: "(\<lambda>x. f x - l) -- a --> 0 = f -- a --> l"
-by (simp add: LIM_def)
+lemma LIM_zero_cancel:
+  fixes f :: "'a::metric_space \<Rightarrow> 'b::real_normed_vector"
+  shows "(\<lambda>x. f x - l) -- a --> 0 \<Longrightarrow> f -- a --> l"
+by (simp add: LIM_def dist_norm)
 
-lemma LIM_imp_LIM:
+lemma LIM_zero_iff:
+  fixes f :: "'a::metric_space \<Rightarrow> 'b::real_normed_vector"
+  shows "(\<lambda>x. f x - l) -- a --> 0 = f -- a --> l"
+by (simp add: LIM_def dist_norm)
+
+lemma metric_LIM_imp_LIM:
   assumes f: "f -- a --> l"
-  assumes le: "\<And>x. x \<noteq> a \<Longrightarrow> norm (g x - m) \<le> norm (f x - l)"
+  assumes le: "\<And>x. x \<noteq> a \<Longrightarrow> dist (g x) m \<le> dist (f x) l"
   shows "g -- a --> m"
-apply (rule LIM_I, drule LIM_D [OF f], safe)
+apply (rule metric_LIM_I, drule metric_LIM_D [OF f], safe)
 apply (rule_tac x="s" in exI, safe)
 apply (drule_tac x="x" in spec, safe)
 apply (erule (1) order_le_less_trans [OF le])
 done
 
-lemma LIM_norm: "f -- a --> l \<Longrightarrow> (\<lambda>x. norm (f x)) -- a --> norm l"
-by (erule LIM_imp_LIM, simp add: norm_triangle_ineq3)
+lemma LIM_imp_LIM:
+  fixes f :: "'a::metric_space \<Rightarrow> 'b::real_normed_vector"
+  fixes g :: "'a::metric_space \<Rightarrow> 'c::real_normed_vector"
+  assumes f: "f -- a --> l"
+  assumes le: "\<And>x. x \<noteq> a \<Longrightarrow> norm (g x - m) \<le> norm (f x - l)"
+  shows "g -- a --> m"
+apply (rule metric_LIM_imp_LIM [OF f])
+apply (simp add: dist_norm le)
+done
 
-lemma LIM_norm_zero: "f -- a --> 0 \<Longrightarrow> (\<lambda>x. norm (f x)) -- a --> 0"
+lemma LIM_norm:
+  fixes f :: "'a::metric_space \<Rightarrow> 'b::real_normed_vector"
+  shows "f -- a --> l \<Longrightarrow> (\<lambda>x. norm (f x)) -- a --> norm l"
+unfolding LIM_conv_tendsto by (rule tendsto_norm)
+
+lemma LIM_norm_zero:
+  fixes f :: "'a::metric_space \<Rightarrow> 'b::real_normed_vector"
+  shows "f -- a --> 0 \<Longrightarrow> (\<lambda>x. norm (f x)) -- a --> 0"
 by (drule LIM_norm, simp)
 
-lemma LIM_norm_zero_cancel: "(\<lambda>x. norm (f x)) -- a --> 0 \<Longrightarrow> f -- a --> 0"
+lemma LIM_norm_zero_cancel:
+  fixes f :: "'a::metric_space \<Rightarrow> 'b::real_normed_vector"
+  shows "(\<lambda>x. norm (f x)) -- a --> 0 \<Longrightarrow> f -- a --> 0"
 by (erule LIM_imp_LIM, simp)
 
-lemma LIM_norm_zero_iff: "(\<lambda>x. norm (f x)) -- a --> 0 = f -- a --> 0"
+lemma LIM_norm_zero_iff:
+  fixes f :: "'a::metric_space \<Rightarrow> 'b::real_normed_vector"
+  shows "(\<lambda>x. norm (f x)) -- a --> 0 = f -- a --> 0"
 by (rule iffI [OF LIM_norm_zero_cancel LIM_norm_zero])
 
 lemma LIM_rabs: "f -- a --> (l::real) \<Longrightarrow> (\<lambda>x. \<bar>f x\<bar>) -- a --> \<bar>l\<bar>"
@@ -161,9 +202,9 @@
 lemma LIM_const_not_eq:
   fixes a :: "'a::real_normed_algebra_1"
   shows "k \<noteq> L \<Longrightarrow> \<not> (\<lambda>x. k) -- a --> L"
-apply (simp add: LIM_eq)
-apply (rule_tac x="norm (k - L)" in exI, simp, safe)
-apply (rule_tac x="a + of_real (s/2)" in exI, simp add: norm_of_real)
+apply (simp add: LIM_def)
+apply (rule_tac x="dist k L" in exI, simp add: zero_less_dist_iff, safe)
+apply (rule_tac x="a + of_real (s/2)" in exI, simp add: dist_norm)
 done
 
 lemmas LIM_not_zero = LIM_const_not_eq [where L = 0]
@@ -176,10 +217,21 @@
 done
 
 lemma LIM_unique:
-  fixes a :: "'a::real_normed_algebra_1"
+  fixes a :: "'a::real_normed_algebra_1" -- {* TODO: find a more appropriate class *}
   shows "\<lbrakk>f -- a --> L; f -- a --> M\<rbrakk> \<Longrightarrow> L = M"
-apply (drule (1) LIM_diff)
-apply (auto dest!: LIM_const_eq)
+apply (rule ccontr)
+apply (drule_tac r="dist L M / 2" in metric_LIM_D, simp add: zero_less_dist_iff)
+apply (drule_tac r="dist L M / 2" in metric_LIM_D, simp add: zero_less_dist_iff)
+apply (clarify, rename_tac r s)
+apply (subgoal_tac "min r s \<noteq> 0")
+apply (subgoal_tac "dist L M < dist L M / 2 + dist L M / 2", simp)
+apply (subgoal_tac "dist L M \<le> dist (f (a + of_real (min r s / 2))) L +
+                               dist (f (a + of_real (min r s / 2))) M")
+apply (erule le_less_trans, rule add_strict_mono)
+apply (drule spec, erule mp, simp add: dist_norm)
+apply (drule spec, erule mp, simp add: dist_norm)
+apply (subst dist_commute, rule dist_triangle)
+apply simp
 done
 
 lemma LIM_ident [simp]: "(\<lambda>x. x) -- a --> a"
@@ -195,9 +247,9 @@
    \<Longrightarrow> ((\<lambda>x. f x) -- a --> l) = ((\<lambda>x. g x) -- b --> m)"
 by (simp add: LIM_def)
 
-lemma LIM_equal2:
+lemma metric_LIM_equal2:
   assumes 1: "0 < R"
-  assumes 2: "\<And>x. \<lbrakk>x \<noteq> a; norm (x - a) < R\<rbrakk> \<Longrightarrow> f x = g x"
+  assumes 2: "\<And>x. \<lbrakk>x \<noteq> a; dist x a < R\<rbrakk> \<Longrightarrow> f x = g x"
   shows "g -- a --> l \<Longrightarrow> f -- a --> l"
 apply (unfold LIM_def, safe)
 apply (drule_tac x="r" in spec, safe)
@@ -206,9 +258,22 @@
 apply (simp add: 2)
 done
 
-text{*Two uses in Hyperreal/Transcendental.ML*}
+lemma LIM_equal2:
+  fixes f g :: "'a::real_normed_vector \<Rightarrow> 'b::metric_space"
+  assumes 1: "0 < R"
+  assumes 2: "\<And>x. \<lbrakk>x \<noteq> a; norm (x - a) < R\<rbrakk> \<Longrightarrow> f x = g x"
+  shows "g -- a --> l \<Longrightarrow> f -- a --> l"
+apply (unfold LIM_def dist_norm, safe)
+apply (drule_tac x="r" in spec, safe)
+apply (rule_tac x="min s R" in exI, safe)
+apply (simp add: 1)
+apply (simp add: 2)
+done
+
+text{*Two uses in Transcendental.ML*}
 lemma LIM_trans:
-     "[| (%x. f(x) + -g(x)) -- a --> 0;  g -- a --> l |] ==> f -- a --> l"
+  fixes f g :: "'a::metric_space \<Rightarrow> 'b::real_normed_vector"
+  shows "[| (%x. f(x) + -g(x)) -- a --> 0;  g -- a --> l |] ==> f -- a --> l"
 apply (drule LIM_add, assumption)
 apply (auto simp add: add_assoc)
 done
@@ -217,62 +282,70 @@
   assumes g: "g -- l --> g l"
   assumes f: "f -- a --> l"
   shows "(\<lambda>x. g (f x)) -- a --> g l"
-proof (rule LIM_I)
+proof (rule metric_LIM_I)
   fix r::real assume r: "0 < r"
   obtain s where s: "0 < s"
-    and less_r: "\<And>y. \<lbrakk>y \<noteq> l; norm (y - l) < s\<rbrakk> \<Longrightarrow> norm (g y - g l) < r"
-    using LIM_D [OF g r] by fast
+    and less_r: "\<And>y. \<lbrakk>y \<noteq> l; dist y l < s\<rbrakk> \<Longrightarrow> dist (g y) (g l) < r"
+    using metric_LIM_D [OF g r] by fast
   obtain t where t: "0 < t"
-    and less_s: "\<And>x. \<lbrakk>x \<noteq> a; norm (x - a) < t\<rbrakk> \<Longrightarrow> norm (f x - l) < s"
-    using LIM_D [OF f s] by fast
+    and less_s: "\<And>x. \<lbrakk>x \<noteq> a; dist x a < t\<rbrakk> \<Longrightarrow> dist (f x) l < s"
+    using metric_LIM_D [OF f s] by fast
 
-  show "\<exists>t>0. \<forall>x. x \<noteq> a \<and> norm (x - a) < t \<longrightarrow> norm (g (f x) - g l) < r"
+  show "\<exists>t>0. \<forall>x. x \<noteq> a \<and> dist x a < t \<longrightarrow> dist (g (f x)) (g l) < r"
   proof (rule exI, safe)
     show "0 < t" using t .
   next
-    fix x assume "x \<noteq> a" and "norm (x - a) < t"
-    hence "norm (f x - l) < s" by (rule less_s)
-    thus "norm (g (f x) - g l) < r"
+    fix x assume "x \<noteq> a" and "dist x a < t"
+    hence "dist (f x) l < s" by (rule less_s)
+    thus "dist (g (f x)) (g l) < r"
       using r less_r by (case_tac "f x = l", simp_all)
   qed
 qed
 
+lemma metric_LIM_compose2:
+  assumes f: "f -- a --> b"
+  assumes g: "g -- b --> c"
+  assumes inj: "\<exists>d>0. \<forall>x. x \<noteq> a \<and> dist x a < d \<longrightarrow> f x \<noteq> b"
+  shows "(\<lambda>x. g (f x)) -- a --> c"
+proof (rule metric_LIM_I)
+  fix r :: real
+  assume r: "0 < r"
+  obtain s where s: "0 < s"
+    and less_r: "\<And>y. \<lbrakk>y \<noteq> b; dist y b < s\<rbrakk> \<Longrightarrow> dist (g y) c < r"
+    using metric_LIM_D [OF g r] by fast
+  obtain t where t: "0 < t"
+    and less_s: "\<And>x. \<lbrakk>x \<noteq> a; dist x a < t\<rbrakk> \<Longrightarrow> dist (f x) b < s"
+    using metric_LIM_D [OF f s] by fast
+  obtain d where d: "0 < d"
+    and neq_b: "\<And>x. \<lbrakk>x \<noteq> a; dist x a < d\<rbrakk> \<Longrightarrow> f x \<noteq> b"
+    using inj by fast
+
+  show "\<exists>t>0. \<forall>x. x \<noteq> a \<and> dist x a < t \<longrightarrow> dist (g (f x)) c < r"
+  proof (safe intro!: exI)
+    show "0 < min d t" using d t by simp
+  next
+    fix x
+    assume "x \<noteq> a" and "dist x a < min d t"
+    hence "f x \<noteq> b" and "dist (f x) b < s"
+      using neq_b less_s by simp_all
+    thus "dist (g (f x)) c < r"
+      by (rule less_r)
+  qed
+qed
+
 lemma LIM_compose2:
+  fixes a :: "'a::real_normed_vector"
   assumes f: "f -- a --> b"
   assumes g: "g -- b --> c"
   assumes inj: "\<exists>d>0. \<forall>x. x \<noteq> a \<and> norm (x - a) < d \<longrightarrow> f x \<noteq> b"
   shows "(\<lambda>x. g (f x)) -- a --> c"
-proof (rule LIM_I)
-  fix r :: real
-  assume r: "0 < r"
-  obtain s where s: "0 < s"
-    and less_r: "\<And>y. \<lbrakk>y \<noteq> b; norm (y - b) < s\<rbrakk> \<Longrightarrow> norm (g y - c) < r"
-    using LIM_D [OF g r] by fast
-  obtain t where t: "0 < t"
-    and less_s: "\<And>x. \<lbrakk>x \<noteq> a; norm (x - a) < t\<rbrakk> \<Longrightarrow> norm (f x - b) < s"
-    using LIM_D [OF f s] by fast
-  obtain d where d: "0 < d"
-    and neq_b: "\<And>x. \<lbrakk>x \<noteq> a; norm (x - a) < d\<rbrakk> \<Longrightarrow> f x \<noteq> b"
-    using inj by fast
-
-  show "\<exists>t>0. \<forall>x. x \<noteq> a \<and> norm (x - a) < t \<longrightarrow> norm (g (f x) - c) < r"
-  proof (safe intro!: exI)
-    show "0 < min d t" using d t by simp
-  next
-    fix x
-    assume "x \<noteq> a" and "norm (x - a) < min d t"
-    hence "f x \<noteq> b" and "norm (f x - b) < s"
-      using neq_b less_s by simp_all
-    thus "norm (g (f x) - c) < r"
-      by (rule less_r)
-  qed
-qed
+by (rule metric_LIM_compose2 [OF f g inj [folded dist_norm]])
 
 lemma LIM_o: "\<lbrakk>g -- l --> g l; f -- a --> l\<rbrakk> \<Longrightarrow> (g \<circ> f) -- a --> g l"
 unfolding o_def by (rule LIM_compose)
 
 lemma real_LIM_sandwich_zero:
-  fixes f g :: "'a::real_normed_vector \<Rightarrow> real"
+  fixes f g :: "'a::metric_space \<Rightarrow> real"
   assumes f: "f -- a --> 0"
   assumes 1: "\<And>x. x \<noteq> a \<Longrightarrow> 0 \<le> g x"
   assumes 2: "\<And>x. x \<noteq> a \<Longrightarrow> g x \<le> f x"
@@ -288,26 +361,12 @@
 
 text {* Bounded Linear Operators *}
 
-lemma (in bounded_linear) cont: "f -- a --> f a"
-proof (rule LIM_I)
-  fix r::real assume r: "0 < r"
-  obtain K where K: "0 < K" and norm_le: "\<And>x. norm (f x) \<le> norm x * K"
-    using pos_bounded by fast
-  show "\<exists>s>0. \<forall>x. x \<noteq> a \<and> norm (x - a) < s \<longrightarrow> norm (f x - f a) < r"
-  proof (rule exI, safe)
-    from r K show "0 < r / K" by (rule divide_pos_pos)
-  next
-    fix x assume x: "norm (x - a) < r / K"
-    have "norm (f x - f a) = norm (f (x - a))" by (simp only: diff)
-    also have "\<dots> \<le> norm (x - a) * K" by (rule norm_le)
-    also from K x have "\<dots> < r" by (simp only: pos_less_divide_eq)
-    finally show "norm (f x - f a) < r" .
-  qed
-qed
-
 lemma (in bounded_linear) LIM:
   "g -- a --> l \<Longrightarrow> (\<lambda>x. f (g x)) -- a --> f l"
-by (rule LIM_compose [OF cont])
+unfolding LIM_conv_tendsto by (rule tendsto)
+
+lemma (in bounded_linear) cont: "f -- a --> f a"
+by (rule LIM [OF LIM_ident])
 
 lemma (in bounded_linear) LIM_zero:
   "g -- a --> 0 \<Longrightarrow> (\<lambda>x. f (g x)) -- a --> 0"
@@ -315,39 +374,16 @@
 
 text {* Bounded Bilinear Operators *}
 
+lemma (in bounded_bilinear) LIM:
+  "\<lbrakk>f -- a --> L; g -- a --> M\<rbrakk> \<Longrightarrow> (\<lambda>x. f x ** g x) -- a --> L ** M"
+unfolding LIM_conv_tendsto by (rule tendsto)
+
 lemma (in bounded_bilinear) LIM_prod_zero:
+  fixes a :: "'d::metric_space"
   assumes f: "f -- a --> 0"
   assumes g: "g -- a --> 0"
   shows "(\<lambda>x. f x ** g x) -- a --> 0"
-proof (rule LIM_I)
-  fix r::real assume r: "0 < r"
-  obtain K where K: "0 < K"
-    and norm_le: "\<And>x y. norm (x ** y) \<le> norm x * norm y * K"
-    using pos_bounded by fast
-  from K have K': "0 < inverse K"
-    by (rule positive_imp_inverse_positive)
-  obtain s where s: "0 < s"
-    and norm_f: "\<And>x. \<lbrakk>x \<noteq> a; norm (x - a) < s\<rbrakk> \<Longrightarrow> norm (f x) < r"
-    using LIM_D [OF f r] by auto
-  obtain t where t: "0 < t"
-    and norm_g: "\<And>x. \<lbrakk>x \<noteq> a; norm (x - a) < t\<rbrakk> \<Longrightarrow> norm (g x) < inverse K"
-    using LIM_D [OF g K'] by auto
-  show "\<exists>s>0. \<forall>x. x \<noteq> a \<and> norm (x - a) < s \<longrightarrow> norm (f x ** g x - 0) < r"
-  proof (rule exI, safe)
-    from s t show "0 < min s t" by simp
-  next
-    fix x assume x: "x \<noteq> a"
-    assume "norm (x - a) < min s t"
-    hence xs: "norm (x - a) < s" and xt: "norm (x - a) < t" by simp_all
-    from x xs have 1: "norm (f x) < r" by (rule norm_f)
-    from x xt have 2: "norm (g x) < inverse K" by (rule norm_g)
-    have "norm (f x ** g x) \<le> norm (f x) * norm (g x) * K" by (rule norm_le)
-    also from 1 2 K have "\<dots> < r * inverse K * K"
-      by (intro mult_strict_right_mono mult_strict_mono' norm_ge_zero)
-    also from K have "r * inverse K * K = r" by simp
-    finally show "norm (f x ** g x - 0) < r" by simp
-  qed
-qed
+using LIM [OF f g] by (simp add: zero_left)
 
 lemma (in bounded_bilinear) LIM_left_zero:
   "f -- a --> 0 \<Longrightarrow> (\<lambda>x. f x ** c) -- a --> 0"
@@ -357,19 +393,6 @@
   "f -- a --> 0 \<Longrightarrow> (\<lambda>x. c ** f x) -- a --> 0"
 by (rule bounded_linear.LIM_zero [OF bounded_linear_right])
 
-lemma (in bounded_bilinear) LIM:
-  "\<lbrakk>f -- a --> L; g -- a --> M\<rbrakk> \<Longrightarrow> (\<lambda>x. f x ** g x) -- a --> L ** M"
-apply (drule LIM_zero)
-apply (drule LIM_zero)
-apply (rule LIM_zero_cancel)
-apply (subst prod_diff_prod)
-apply (rule LIM_add_zero)
-apply (rule LIM_add_zero)
-apply (erule (1) LIM_prod_zero)
-apply (erule LIM_left_zero)
-apply (erule LIM_right_zero)
-done
-
 lemmas LIM_mult = mult.LIM
 
 lemmas LIM_mult_zero = mult.LIM_prod_zero
@@ -383,7 +406,7 @@
 lemmas LIM_of_real = of_real.LIM
 
 lemma LIM_power:
-  fixes f :: "'a::real_normed_vector \<Rightarrow> 'b::{power,real_normed_algebra}"
+  fixes f :: "'a::metric_space \<Rightarrow> 'b::{power,real_normed_algebra}"
   assumes f: "f -- a --> l"
   shows "(\<lambda>x. f x ^ n) -- a --> l ^ n"
 by (induct n, simp, simp add: LIM_mult f)
@@ -453,19 +476,22 @@
 by (rule LIM_inverse_fun [THEN LIM_compose])
 
 lemma LIM_sgn:
-  "\<lbrakk>f -- a --> l; l \<noteq> 0\<rbrakk> \<Longrightarrow> (\<lambda>x. sgn (f x)) -- a --> sgn l"
+  fixes f :: "'a::metric_space \<Rightarrow> 'b::real_normed_vector"
+  shows "\<lbrakk>f -- a --> l; l \<noteq> 0\<rbrakk> \<Longrightarrow> (\<lambda>x. sgn (f x)) -- a --> sgn l"
 unfolding sgn_div_norm
 by (simp add: LIM_scaleR LIM_inverse LIM_norm)
 
 
 subsection {* Continuity *}
 
-subsubsection {* Purely standard proofs *}
-
-lemma LIM_isCont_iff: "(f -- a --> f a) = ((\<lambda>h. f (a + h)) -- 0 --> f a)"
+lemma LIM_isCont_iff:
+  fixes f :: "'a::real_normed_vector \<Rightarrow> 'b::metric_space"
+  shows "(f -- a --> f a) = ((\<lambda>h. f (a + h)) -- 0 --> f a)"
 by (rule iffI [OF LIM_offset_zero LIM_offset_zero_cancel])
 
-lemma isCont_iff: "isCont f x = (\<lambda>h. f (x + h)) -- 0 --> f x"
+lemma isCont_iff:
+  fixes f :: "'a::real_normed_vector \<Rightarrow> 'b::metric_space"
+  shows "isCont f x = (\<lambda>h. f (x + h)) -- 0 --> f x"
 by (simp add: isCont_def LIM_isCont_iff)
 
 lemma isCont_ident [simp]: "isCont (\<lambda>x. x) a"
@@ -474,28 +500,36 @@
 lemma isCont_const [simp]: "isCont (\<lambda>x. k) a"
   unfolding isCont_def by (rule LIM_const)
 
-lemma isCont_norm: "isCont f a \<Longrightarrow> isCont (\<lambda>x. norm (f x)) a"
+lemma isCont_norm:
+  fixes f :: "'a::metric_space \<Rightarrow> 'b::real_normed_vector"
+  shows "isCont f a \<Longrightarrow> isCont (\<lambda>x. norm (f x)) a"
   unfolding isCont_def by (rule LIM_norm)
 
 lemma isCont_rabs: "isCont f a \<Longrightarrow> isCont (\<lambda>x. \<bar>f x :: real\<bar>) a"
   unfolding isCont_def by (rule LIM_rabs)
 
-lemma isCont_add: "\<lbrakk>isCont f a; isCont g a\<rbrakk> \<Longrightarrow> isCont (\<lambda>x. f x + g x) a"
+lemma isCont_add:
+  fixes f :: "'a::metric_space \<Rightarrow> 'b::real_normed_vector"
+  shows "\<lbrakk>isCont f a; isCont g a\<rbrakk> \<Longrightarrow> isCont (\<lambda>x. f x + g x) a"
   unfolding isCont_def by (rule LIM_add)
 
-lemma isCont_minus: "isCont f a \<Longrightarrow> isCont (\<lambda>x. - f x) a"
+lemma isCont_minus:
+  fixes f :: "'a::metric_space \<Rightarrow> 'b::real_normed_vector"
+  shows "isCont f a \<Longrightarrow> isCont (\<lambda>x. - f x) a"
   unfolding isCont_def by (rule LIM_minus)
 
-lemma isCont_diff: "\<lbrakk>isCont f a; isCont g a\<rbrakk> \<Longrightarrow> isCont (\<lambda>x. f x - g x) a"
+lemma isCont_diff:
+  fixes f :: "'a::metric_space \<Rightarrow> 'b::real_normed_vector"
+  shows "\<lbrakk>isCont f a; isCont g a\<rbrakk> \<Longrightarrow> isCont (\<lambda>x. f x - g x) a"
   unfolding isCont_def by (rule LIM_diff)
 
 lemma isCont_mult:
-  fixes f g :: "'a::real_normed_vector \<Rightarrow> 'b::real_normed_algebra"
+  fixes f g :: "'a::metric_space \<Rightarrow> 'b::real_normed_algebra"
   shows "\<lbrakk>isCont f a; isCont g a\<rbrakk> \<Longrightarrow> isCont (\<lambda>x. f x * g x) a"
   unfolding isCont_def by (rule LIM_mult)
 
 lemma isCont_inverse:
-  fixes f :: "'a::real_normed_vector \<Rightarrow> 'b::real_normed_div_algebra"
+  fixes f :: "'a::metric_space \<Rightarrow> 'b::real_normed_div_algebra"
   shows "\<lbrakk>isCont f a; f a \<noteq> 0\<rbrakk> \<Longrightarrow> isCont (\<lambda>x. inverse (f x)) a"
   unfolding isCont_def by (rule LIM_inverse)
 
@@ -503,7 +537,15 @@
   "\<lbrakk>isCont g l; f -- a --> l\<rbrakk> \<Longrightarrow> (\<lambda>x. g (f x)) -- a --> g l"
   unfolding isCont_def by (rule LIM_compose)
 
+lemma metric_isCont_LIM_compose2:
+  assumes f [unfolded isCont_def]: "isCont f a"
+  assumes g: "g -- f a --> l"
+  assumes inj: "\<exists>d>0. \<forall>x. x \<noteq> a \<and> dist x a < d \<longrightarrow> f x \<noteq> f a"
+  shows "(\<lambda>x. g (f x)) -- a --> l"
+by (rule metric_LIM_compose2 [OF f g inj])
+
 lemma isCont_LIM_compose2:
+  fixes a :: "'a::real_normed_vector"
   assumes f [unfolded isCont_def]: "isCont f a"
   assumes g: "g -- f a --> l"
   assumes inj: "\<exists>d>0. \<forall>x. x \<noteq> a \<and> norm (x - a) < d \<longrightarrow> f x \<noteq> f a"
@@ -526,22 +568,25 @@
 lemmas isCont_scaleR = scaleR.isCont
 
 lemma isCont_of_real:
-  "isCont f a \<Longrightarrow> isCont (\<lambda>x. of_real (f x)) a"
+  "isCont f a \<Longrightarrow> isCont (\<lambda>x. of_real (f x)::'b::real_normed_algebra_1) a"
   unfolding isCont_def by (rule LIM_of_real)
 
 lemma isCont_power:
-  fixes f :: "'a::real_normed_vector \<Rightarrow> 'b::{power,real_normed_algebra}"
+  fixes f :: "'a::metric_space \<Rightarrow> 'b::{power,real_normed_algebra}"
   shows "isCont f a \<Longrightarrow> isCont (\<lambda>x. f x ^ n) a"
   unfolding isCont_def by (rule LIM_power)
 
 lemma isCont_sgn:
-  "\<lbrakk>isCont f a; f a \<noteq> 0\<rbrakk> \<Longrightarrow> isCont (\<lambda>x. sgn (f x)) a"
+  fixes f :: "'a::metric_space \<Rightarrow> 'b::real_normed_vector"
+  shows "\<lbrakk>isCont f a; f a \<noteq> 0\<rbrakk> \<Longrightarrow> isCont (\<lambda>x. sgn (f x)) a"
   unfolding isCont_def by (rule LIM_sgn)
 
 lemma isCont_abs [simp]: "isCont abs (a::real)"
 by (rule isCont_rabs [OF isCont_ident])
 
-lemma isCont_setsum: fixes A :: "nat set" assumes "finite A"
+lemma isCont_setsum:
+  fixes f :: "'a \<Rightarrow> 'b::metric_space \<Rightarrow> 'c::real_normed_vector"
+  fixes A :: "'a set" assumes "finite A"
   shows "\<forall> i \<in> A. isCont (f i) x \<Longrightarrow> isCont (\<lambda> x. \<Sum> i \<in> A. f i x) x"
   using `finite A`
 proof induct
@@ -578,7 +623,7 @@
   hence "f ?x < 0" using `f x < 0` by auto
   thus False using `0 \<le> f ?x` by auto
 qed
-  
+
 
 subsection {* Uniform Continuity *}
 
@@ -588,14 +633,14 @@
 lemma isUCont_Cauchy:
   "\<lbrakk>isUCont f; Cauchy X\<rbrakk> \<Longrightarrow> Cauchy (\<lambda>n. f (X n))"
 unfolding isUCont_def
-apply (rule CauchyI)
+apply (rule metric_CauchyI)
 apply (drule_tac x=e in spec, safe)
-apply (drule_tac e=s in CauchyD, safe)
+apply (drule_tac e=s in metric_CauchyD, safe)
 apply (rule_tac x=M in exI, simp)
 done
 
 lemma (in bounded_linear) isUCont: "isUCont f"
-unfolding isUCont_def
+unfolding isUCont_def dist_norm
 proof (intro allI impI)
   fix r::real assume r: "0 < r"
   obtain K where K: "0 < K" and norm_le: "\<And>x. norm (f x) \<le> norm x * K"
@@ -620,44 +665,46 @@
 subsection {* Relation of LIM and LIMSEQ *}
 
 lemma LIMSEQ_SEQ_conv1:
-  fixes a :: "'a::real_normed_vector"
+  fixes a :: "'a::metric_space"
   assumes X: "X -- a --> L"
   shows "\<forall>S. (\<forall>n. S n \<noteq> a) \<and> S ----> a \<longrightarrow> (\<lambda>n. X (S n)) ----> L"
-proof (safe intro!: LIMSEQ_I)
+proof (safe intro!: metric_LIMSEQ_I)
   fix S :: "nat \<Rightarrow> 'a"
   fix r :: real
   assume rgz: "0 < r"
   assume as: "\<forall>n. S n \<noteq> a"
   assume S: "S ----> a"
-  from LIM_D [OF X rgz] obtain s
+  from metric_LIM_D [OF X rgz] obtain s
     where sgz: "0 < s"
-    and aux: "\<And>x. \<lbrakk>x \<noteq> a; norm (x - a) < s\<rbrakk> \<Longrightarrow> norm (X x - L) < r"
+    and aux: "\<And>x. \<lbrakk>x \<noteq> a; dist x a < s\<rbrakk> \<Longrightarrow> dist (X x) L < r"
     by fast
-  from LIMSEQ_D [OF S sgz]
-  obtain no where "\<forall>n\<ge>no. norm (S n - a) < s" by blast
-  hence "\<forall>n\<ge>no. norm (X (S n) - L) < r" by (simp add: aux as)
-  thus "\<exists>no. \<forall>n\<ge>no. norm (X (S n) - L) < r" ..
+  from metric_LIMSEQ_D [OF S sgz]
+  obtain no where "\<forall>n\<ge>no. dist (S n) a < s" by blast
+  hence "\<forall>n\<ge>no. dist (X (S n)) L < r" by (simp add: aux as)
+  thus "\<exists>no. \<forall>n\<ge>no. dist (X (S n)) L < r" ..
 qed
 
+
 lemma LIMSEQ_SEQ_conv2:
   fixes a :: real
   assumes "\<forall>S. (\<forall>n. S n \<noteq> a) \<and> S ----> a \<longrightarrow> (\<lambda>n. X (S n)) ----> L"
   shows "X -- a --> L"
 proof (rule ccontr)
   assume "\<not> (X -- a --> L)"
-  hence "\<not> (\<forall>r > 0. \<exists>s > 0. \<forall>x. x \<noteq> a & norm (x - a) < s --> norm (X x - L) < r)" by (unfold LIM_def)
-  hence "\<exists>r > 0. \<forall>s > 0. \<exists>x. \<not>(x \<noteq> a \<and> \<bar>x - a\<bar> < s --> norm (X x - L) < r)" by simp
-  hence "\<exists>r > 0. \<forall>s > 0. \<exists>x. (x \<noteq> a \<and> \<bar>x - a\<bar> < s \<and> norm (X x - L) \<ge> r)" by (simp add: linorder_not_less)
-  then obtain r where rdef: "r > 0 \<and> (\<forall>s > 0. \<exists>x. (x \<noteq> a \<and> \<bar>x - a\<bar> < s \<and> norm (X x - L) \<ge> r))" by auto
+  hence "\<not> (\<forall>r > 0. \<exists>s > 0. \<forall>x. x \<noteq> a & norm (x - a) < s --> dist (X x) L < r)"
+    unfolding LIM_def dist_norm .
+  hence "\<exists>r > 0. \<forall>s > 0. \<exists>x. \<not>(x \<noteq> a \<and> \<bar>x - a\<bar> < s --> dist (X x) L < r)" by simp
+  hence "\<exists>r > 0. \<forall>s > 0. \<exists>x. (x \<noteq> a \<and> \<bar>x - a\<bar> < s \<and> dist (X x) L \<ge> r)" by (simp add: not_less)
+  then obtain r where rdef: "r > 0 \<and> (\<forall>s > 0. \<exists>x. (x \<noteq> a \<and> \<bar>x - a\<bar> < s \<and> dist (X x) L \<ge> r))" by auto
 
-  let ?F = "\<lambda>n::nat. SOME x. x\<noteq>a \<and> \<bar>x - a\<bar> < inverse (real (Suc n)) \<and> norm (X x - L) \<ge> r"
-  have "\<And>n. \<exists>x. x\<noteq>a \<and> \<bar>x - a\<bar> < inverse (real (Suc n)) \<and> norm (X x - L) \<ge> r"
+  let ?F = "\<lambda>n::nat. SOME x. x\<noteq>a \<and> \<bar>x - a\<bar> < inverse (real (Suc n)) \<and> dist (X x) L \<ge> r"
+  have "\<And>n. \<exists>x. x\<noteq>a \<and> \<bar>x - a\<bar> < inverse (real (Suc n)) \<and> dist (X x) L \<ge> r"
     using rdef by simp
-  hence F: "\<And>n. ?F n \<noteq> a \<and> \<bar>?F n - a\<bar> < inverse (real (Suc n)) \<and> norm (X (?F n) - L) \<ge> r"
+  hence F: "\<And>n. ?F n \<noteq> a \<and> \<bar>?F n - a\<bar> < inverse (real (Suc n)) \<and> dist (X (?F n)) L \<ge> r"
     by (rule someI_ex)
   hence F1: "\<And>n. ?F n \<noteq> a"
     and F2: "\<And>n. \<bar>?F n - a\<bar> < inverse (real (Suc n))"
-    and F3: "\<And>n. norm (X (?F n) - L) \<ge> r"
+    and F3: "\<And>n. dist (X (?F n)) L \<ge> r"
     by fast+
 
   have "?F ----> a"
@@ -694,13 +741,13 @@
       obtain n where "n = no + 1" by simp
       then have nolen: "no \<le> n" by simp
         (* We prove this by showing that for any m there is an n\<ge>m such that |X (?F n) - L| \<ge> r *)
-      have "norm (X (?F n) - L) \<ge> r"
+      have "dist (X (?F n)) L \<ge> r"
         by (rule F3)
-      with nolen have "\<exists>n. no \<le> n \<and> norm (X (?F n) - L) \<ge> r" by fast
+      with nolen have "\<exists>n. no \<le> n \<and> dist (X (?F n)) L \<ge> r" by fast
     }
-    then have "(\<forall>no. \<exists>n. no \<le> n \<and> norm (X (?F n) - L) \<ge> r)" by simp
-    with rdef have "\<exists>e>0. (\<forall>no. \<exists>n. no \<le> n \<and> norm (X (?F n) - L) \<ge> e)" by auto
-    thus ?thesis by (unfold LIMSEQ_def, auto simp add: linorder_not_less)
+    then have "(\<forall>no. \<exists>n. no \<le> n \<and> dist (X (?F n)) L \<ge> r)" by simp
+    with rdef have "\<exists>e>0. (\<forall>no. \<exists>n. no \<le> n \<and> dist (X (?F n)) L \<ge> e)" by auto
+    thus ?thesis by (unfold LIMSEQ_def, auto simp add: not_less)
   qed
   ultimately show False by simp
 qed
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/HOL/Limits.thy	Tue Jun 02 12:18:08 2009 +0200
@@ -0,0 +1,296 @@
+(*  Title       : Limits.thy
+    Author      : Brian Huffman
+*)
+
+header {* Filters and Limits *}
+
+theory Limits
+imports RealVector RComplete
+begin
+
+subsection {* Filters *}
+
+typedef (open) 'a filter =
+  "{f :: ('a \<Rightarrow> bool) \<Rightarrow> bool. f (\<lambda>x. True)
+    \<and> (\<forall>P Q. (\<forall>x. P x \<longrightarrow> Q x) \<longrightarrow> f P \<longrightarrow> f Q)
+    \<and> (\<forall>P Q. f P \<longrightarrow> f Q \<longrightarrow> f (\<lambda>x. P x \<and> Q x))}"
+proof
+  show "(\<lambda>P. True) \<in> ?filter" by simp
+qed
+
+definition
+  eventually :: "('a \<Rightarrow> bool) \<Rightarrow> 'a filter \<Rightarrow> bool" where
+  [simp del]: "eventually P F \<longleftrightarrow> Rep_filter F P"
+
+lemma eventually_True [simp]: "eventually (\<lambda>x. True) F"
+unfolding eventually_def using Rep_filter [of F] by blast
+
+lemma eventually_mono:
+  "(\<forall>x. P x \<longrightarrow> Q x) \<Longrightarrow> eventually P F \<Longrightarrow> eventually Q F"
+unfolding eventually_def using Rep_filter [of F] by blast
+
+lemma eventually_conj:
+  "\<lbrakk>eventually (\<lambda>x. P x) F; eventually (\<lambda>x. Q x) F\<rbrakk>
+    \<Longrightarrow> eventually (\<lambda>x. P x \<and> Q x) F"
+unfolding eventually_def using Rep_filter [of F] by blast
+
+lemma eventually_mp:
+  assumes "eventually (\<lambda>x. P x \<longrightarrow> Q x) F"
+  assumes "eventually (\<lambda>x. P x) F"
+  shows "eventually (\<lambda>x. Q x) F"
+proof (rule eventually_mono)
+  show "\<forall>x. (P x \<longrightarrow> Q x) \<and> P x \<longrightarrow> Q x" by simp
+  show "eventually (\<lambda>x. (P x \<longrightarrow> Q x) \<and> P x) F"
+    using assms by (rule eventually_conj)
+qed
+
+lemma eventually_rev_mp:
+  assumes "eventually (\<lambda>x. P x) F"
+  assumes "eventually (\<lambda>x. P x \<longrightarrow> Q x) F"
+  shows "eventually (\<lambda>x. Q x) F"
+using assms(2) assms(1) by (rule eventually_mp)
+
+lemma eventually_conj_iff:
+  "eventually (\<lambda>x. P x \<and> Q x) net \<longleftrightarrow> eventually P net \<and> eventually Q net"
+by (auto intro: eventually_conj elim: eventually_rev_mp)
+
+lemma eventually_Abs_filter:
+  assumes "f (\<lambda>x. True)"
+  assumes "\<And>P Q. (\<forall>x. P x \<longrightarrow> Q x) \<Longrightarrow> f P \<Longrightarrow> f Q"
+  assumes "\<And>P Q. f P \<Longrightarrow> f Q \<Longrightarrow> f (\<lambda>x. P x \<and> Q x)"
+  shows "eventually P (Abs_filter f) \<longleftrightarrow> f P"
+unfolding eventually_def using assms
+by (subst Abs_filter_inverse, auto)
+
+lemma filter_ext:
+  "(\<And>P. eventually P F \<longleftrightarrow> eventually P F') \<Longrightarrow> F = F'"
+unfolding eventually_def
+by (simp add: Rep_filter_inject [THEN iffD1] ext)
+
+lemma eventually_elim1:
+  assumes "eventually (\<lambda>i. P i) F"
+  assumes "\<And>i. P i \<Longrightarrow> Q i"
+  shows "eventually (\<lambda>i. Q i) F"
+using assms by (auto elim!: eventually_rev_mp)
+
+lemma eventually_elim2:
+  assumes "eventually (\<lambda>i. P i) F"
+  assumes "eventually (\<lambda>i. Q i) F"
+  assumes "\<And>i. P i \<Longrightarrow> Q i \<Longrightarrow> R i"
+  shows "eventually (\<lambda>i. R i) F"
+using assms by (auto elim!: eventually_rev_mp)
+
+
+subsection {* Convergence to Zero *}
+
+definition
+  Zfun :: "('a \<Rightarrow> 'b::real_normed_vector) \<Rightarrow> 'a filter \<Rightarrow> bool" where
+  [code del]: "Zfun S F = (\<forall>r>0. eventually (\<lambda>i. norm (S i) < r) F)"
+
+lemma ZfunI:
+  "(\<And>r. 0 < r \<Longrightarrow> eventually (\<lambda>i. norm (S i) < r) F) \<Longrightarrow> Zfun S F"
+unfolding Zfun_def by simp
+
+lemma ZfunD:
+  "\<lbrakk>Zfun S F; 0 < r\<rbrakk> \<Longrightarrow> eventually (\<lambda>i. norm (S i) < r) F"
+unfolding Zfun_def by simp
+
+lemma Zfun_zero: "Zfun (\<lambda>i. 0) F"
+unfolding Zfun_def by simp
+
+lemma Zfun_norm_iff: "Zfun (\<lambda>i. norm (S i)) F = Zfun (\<lambda>i. S i) F"
+unfolding Zfun_def by simp
+
+lemma Zfun_imp_Zfun:
+  assumes X: "Zfun X F"
+  assumes Y: "\<And>n. norm (Y n) \<le> norm (X n) * K"
+  shows "Zfun (\<lambda>n. Y n) F"
+proof (cases)
+  assume K: "0 < K"
+  show ?thesis
+  proof (rule ZfunI)
+    fix r::real assume "0 < r"
+    hence "0 < r / K"
+      using K by (rule divide_pos_pos)
+    then have "eventually (\<lambda>i. norm (X i) < r / K) F"
+      using ZfunD [OF X] by fast
+    then show "eventually (\<lambda>i. norm (Y i) < r) F"
+    proof (rule eventually_elim1)
+      fix i assume "norm (X i) < r / K"
+      hence "norm (X i) * K < r"
+        by (simp add: pos_less_divide_eq K)
+      thus "norm (Y i) < r"
+        by (simp add: order_le_less_trans [OF Y])
+    qed
+  qed
+next
+  assume "\<not> 0 < K"
+  hence K: "K \<le> 0" by (simp only: not_less)
+  {
+    fix i
+    have "norm (Y i) \<le> norm (X i) * K" by (rule Y)
+    also have "\<dots> \<le> norm (X i) * 0"
+      using K norm_ge_zero by (rule mult_left_mono)
+    finally have "norm (Y i) = 0" by simp
+  }
+  thus ?thesis by (simp add: Zfun_zero)
+qed
+
+lemma Zfun_le: "\<lbrakk>Zfun Y F; \<forall>n. norm (X n) \<le> norm (Y n)\<rbrakk> \<Longrightarrow> Zfun X F"
+by (erule_tac K="1" in Zfun_imp_Zfun, simp)
+
+lemma Zfun_add:
+  assumes X: "Zfun X F" and Y: "Zfun Y F"
+  shows "Zfun (\<lambda>n. X n + Y n) F"
+proof (rule ZfunI)
+  fix r::real assume "0 < r"
+  hence r: "0 < r / 2" by simp
+  have "eventually (\<lambda>i. norm (X i) < r/2) F"
+    using X r by (rule ZfunD)
+  moreover
+  have "eventually (\<lambda>i. norm (Y i) < r/2) F"
+    using Y r by (rule ZfunD)
+  ultimately
+  show "eventually (\<lambda>i. norm (X i + Y i) < r) F"
+  proof (rule eventually_elim2)
+    fix i
+    assume *: "norm (X i) < r/2" "norm (Y i) < r/2"
+    have "norm (X i + Y i) \<le> norm (X i) + norm (Y i)"
+      by (rule norm_triangle_ineq)
+    also have "\<dots> < r/2 + r/2"
+      using * by (rule add_strict_mono)
+    finally show "norm (X i + Y i) < r"
+      by simp
+  qed
+qed
+
+lemma Zfun_minus: "Zfun X F \<Longrightarrow> Zfun (\<lambda>i. - X i) F"
+unfolding Zfun_def by simp
+
+lemma Zfun_diff: "\<lbrakk>Zfun X F; Zfun Y F\<rbrakk> \<Longrightarrow> Zfun (\<lambda>i. X i - Y i) F"
+by (simp only: diff_minus Zfun_add Zfun_minus)
+
+lemma (in bounded_linear) Zfun:
+  assumes X: "Zfun X F"
+  shows "Zfun (\<lambda>n. f (X n)) F"
+proof -
+  obtain K where "\<And>x. norm (f x) \<le> norm x * K"
+    using bounded by fast
+  with X show ?thesis
+    by (rule Zfun_imp_Zfun)
+qed
+
+lemma (in bounded_bilinear) Zfun:
+  assumes X: "Zfun X F"
+  assumes Y: "Zfun Y F"
+  shows "Zfun (\<lambda>n. X n ** Y n) F"
+proof (rule ZfunI)
+  fix r::real assume r: "0 < r"
+  obtain K where K: "0 < K"
+    and norm_le: "\<And>x y. norm (x ** y) \<le> norm x * norm y * K"
+    using pos_bounded by fast
+  from K have K': "0 < inverse K"
+    by (rule positive_imp_inverse_positive)
+  have "eventually (\<lambda>i. norm (X i) < r) F"
+    using X r by (rule ZfunD)
+  moreover
+  have "eventually (\<lambda>i. norm (Y i) < inverse K) F"
+    using Y K' by (rule ZfunD)
+  ultimately
+  show "eventually (\<lambda>i. norm (X i ** Y i) < r) F"
+  proof (rule eventually_elim2)
+    fix i
+    assume *: "norm (X i) < r" "norm (Y i) < inverse K"
+    have "norm (X i ** Y i) \<le> norm (X i) * norm (Y i) * K"
+      by (rule norm_le)
+    also have "norm (X i) * norm (Y i) * K < r * inverse K * K"
+      by (intro mult_strict_right_mono mult_strict_mono' norm_ge_zero * K)
+    also from K have "r * inverse K * K = r"
+      by simp
+    finally show "norm (X i ** Y i) < r" .
+  qed
+qed
+
+lemma (in bounded_bilinear) Zfun_left:
+  "Zfun X F \<Longrightarrow> Zfun (\<lambda>n. X n ** a) F"
+by (rule bounded_linear_left [THEN bounded_linear.Zfun])
+
+lemma (in bounded_bilinear) Zfun_right:
+  "Zfun X F \<Longrightarrow> Zfun (\<lambda>n. a ** X n) F"
+by (rule bounded_linear_right [THEN bounded_linear.Zfun])
+
+lemmas Zfun_mult = mult.Zfun
+lemmas Zfun_mult_right = mult.Zfun_right
+lemmas Zfun_mult_left = mult.Zfun_left
+
+
+subsection{* Limits *}
+
+definition
+  tendsto :: "('a \<Rightarrow> 'b::metric_space) \<Rightarrow> 'b \<Rightarrow> 'a filter \<Rightarrow> bool" where
+  [code del]: "tendsto f l net \<longleftrightarrow> (\<forall>e>0. eventually (\<lambda>x. dist (f x) l < e) net)"
+
+lemma tendstoI:
+  "(\<And>e. 0 < e \<Longrightarrow> eventually (\<lambda>x. dist (f x) l < e) net)
+    \<Longrightarrow> tendsto f l net"
+  unfolding tendsto_def by auto
+
+lemma tendstoD:
+  "tendsto f l net \<Longrightarrow> 0 < e \<Longrightarrow> eventually (\<lambda>x. dist (f x) l < e) net"
+  unfolding tendsto_def by auto
+
+lemma tendsto_Zfun_iff: "tendsto (\<lambda>n. X n) L F = Zfun (\<lambda>n. X n - L) F"
+by (simp only: tendsto_def Zfun_def dist_norm)
+
+lemma tendsto_const: "tendsto (\<lambda>n. k) k F"
+by (simp add: tendsto_def)
+
+lemma tendsto_norm:
+  fixes a :: "'a::real_normed_vector"
+  shows "tendsto X a F \<Longrightarrow> tendsto (\<lambda>n. norm (X n)) (norm a) F"
+apply (simp add: tendsto_def dist_norm, safe)
+apply (drule_tac x="e" in spec, safe)
+apply (erule eventually_elim1)
+apply (erule order_le_less_trans [OF norm_triangle_ineq3])
+done
+
+lemma add_diff_add:
+  fixes a b c d :: "'a::ab_group_add"
+  shows "(a + c) - (b + d) = (a - b) + (c - d)"
+by simp
+
+lemma minus_diff_minus:
+  fixes a b :: "'a::ab_group_add"
+  shows "(- a) - (- b) = - (a - b)"
+by simp
+
+lemma tendsto_add:
+  fixes a b :: "'a::real_normed_vector"
+  shows "\<lbrakk>tendsto X a F; tendsto Y b F\<rbrakk> \<Longrightarrow> tendsto (\<lambda>n. X n + Y n) (a + b) F"
+by (simp only: tendsto_Zfun_iff add_diff_add Zfun_add)
+
+lemma tendsto_minus:
+  fixes a :: "'a::real_normed_vector"
+  shows "tendsto X a F \<Longrightarrow> tendsto (\<lambda>n. - X n) (- a) F"
+by (simp only: tendsto_Zfun_iff minus_diff_minus Zfun_minus)
+
+lemma tendsto_minus_cancel:
+  fixes a :: "'a::real_normed_vector"
+  shows "tendsto (\<lambda>n. - X n) (- a) F \<Longrightarrow> tendsto X a F"
+by (drule tendsto_minus, simp)
+
+lemma tendsto_diff:
+  fixes a b :: "'a::real_normed_vector"
+  shows "\<lbrakk>tendsto X a F; tendsto Y b F\<rbrakk> \<Longrightarrow> tendsto (\<lambda>n. X n - Y n) (a - b) F"
+by (simp add: diff_minus tendsto_add tendsto_minus)
+
+lemma (in bounded_linear) tendsto:
+  "tendsto X a F \<Longrightarrow> tendsto (\<lambda>n. f (X n)) (f a) F"
+by (simp only: tendsto_Zfun_iff diff [symmetric] Zfun)
+
+lemma (in bounded_bilinear) tendsto:
+  "\<lbrakk>tendsto X a F; tendsto Y b F\<rbrakk> \<Longrightarrow> tendsto (\<lambda>n. X n ** Y n) (a ** b) F"
+by (simp only: tendsto_Zfun_iff prod_diff_prod
+               Zfun_add Zfun Zfun_left Zfun_right)
+
+end
--- a/src/HOL/List.thy	Mon Jun 01 09:26:28 2009 +0200
+++ b/src/HOL/List.thy	Tue Jun 02 12:18:08 2009 +0200
@@ -1365,6 +1365,13 @@
  "(xs @ x # ys)[length xs := y] = (xs @ y # ys)"
 by (induct xs, auto)
 
+lemma map_update: "map f (xs[k:= y]) = (map f xs)[k := f y]"
+by(induct xs arbitrary: k)(auto split:nat.splits)
+
+lemma rev_update:
+  "k < length xs \<Longrightarrow> rev (xs[k:= y]) = (rev xs)[length xs - k - 1 := y]"
+by (induct xs arbitrary: k) (auto simp: list_update_append split:nat.splits)
+
 lemma update_zip:
   "(zip xs ys)[i:=xy] = zip (xs[i:=fst xy]) (ys[i:=snd xy])"
 by (induct ys arbitrary: i xy xs) (auto, case_tac xs, auto split: nat.split)
@@ -2212,6 +2219,36 @@
   shows "- listsum (map f xs) = (listsum (map (uminus o f) xs))"
 by (induct xs) simp_all
 
+lemma listsum_addf:
+  fixes f g :: "'a \<Rightarrow> 'b::comm_monoid_add"
+  shows "(\<Sum>x\<leftarrow>xs. f x + g x) = listsum (map f xs) + listsum (map g xs)"
+by (induct xs) (simp_all add: algebra_simps)
+
+lemma listsum_subtractf:
+  fixes f g :: "'a \<Rightarrow> 'b::ab_group_add"
+  shows "(\<Sum>x\<leftarrow>xs. f x - g x) = listsum (map f xs) - listsum (map g xs)"
+by (induct xs) simp_all
+
+lemma listsum_const_mult:
+  fixes f :: "'a \<Rightarrow> 'b::semiring_0"
+  shows "(\<Sum>x\<leftarrow>xs. c * f x) = c * (\<Sum>x\<leftarrow>xs. f x)"
+by (induct xs, simp_all add: algebra_simps)
+
+lemma listsum_mult_const:
+  fixes f :: "'a \<Rightarrow> 'b::semiring_0"
+  shows "(\<Sum>x\<leftarrow>xs. f x * c) = (\<Sum>x\<leftarrow>xs. f x) * c"
+by (induct xs, simp_all add: algebra_simps)
+
+lemma listsum_abs:
+  fixes xs :: "'a::pordered_ab_group_add_abs list"
+  shows "\<bar>listsum xs\<bar> \<le> listsum (map abs xs)"
+by (induct xs, simp, simp add: order_trans [OF abs_triangle_ineq])
+
+lemma listsum_mono:
+  fixes f g :: "'a \<Rightarrow> 'b::{comm_monoid_add, pordered_ab_semigroup_add}"
+  shows "(\<And>x. x \<in> set xs \<Longrightarrow> f x \<le> g x) \<Longrightarrow> (\<Sum>x\<leftarrow>xs. f x) \<le> (\<Sum>x\<leftarrow>xs. g x)"
+by (induct xs, simp, simp add: add_mono)
+
 
 subsubsection {* @{text upt} *}
 
--- a/src/HOL/Ln.thy	Mon Jun 01 09:26:28 2009 +0200
+++ b/src/HOL/Ln.thy	Tue Jun 02 12:18:08 2009 +0200
@@ -343,7 +343,7 @@
 done
 
 lemma DERIV_ln: "0 < x ==> DERIV ln x :> 1 / x"
-  apply (unfold deriv_def, unfold LIM_def, clarsimp)
+  apply (unfold deriv_def, unfold LIM_eq, clarsimp)
   apply (rule exI)
   apply (rule conjI)
   prefer 2
--- a/src/HOL/Log.thy	Mon Jun 01 09:26:28 2009 +0200
+++ b/src/HOL/Log.thy	Tue Jun 02 12:18:08 2009 +0200
@@ -248,7 +248,7 @@
 qed
 
 lemma LIMSEQ_neg_powr: "0 < s ==> (%x. (real x) powr - s) ----> 0"
-  apply (unfold LIMSEQ_def)
+  apply (unfold LIMSEQ_iff)
   apply clarsimp
   apply (rule_tac x = "natfloor(r powr (1 / - s)) + 1" in exI)
   apply clarify
--- a/src/HOL/NSA/CLim.thy	Mon Jun 01 09:26:28 2009 +0200
+++ b/src/HOL/NSA/CLim.thy	Tue Jun 02 12:18:08 2009 +0200
@@ -45,17 +45,25 @@
               hIm_hcomplex_of_complex)
 
 (** get this result easily now **)
-lemma LIM_Re: "f -- a --> L ==> (%x. Re(f x)) -- a --> Re(L)"
+lemma LIM_Re:
+  fixes f :: "'a::real_normed_vector \<Rightarrow> complex"
+  shows "f -- a --> L ==> (%x. Re(f x)) -- a --> Re(L)"
 by (simp add: LIM_NSLIM_iff NSLIM_Re)
 
-lemma LIM_Im: "f -- a --> L ==> (%x. Im(f x)) -- a --> Im(L)"
+lemma LIM_Im:
+  fixes f :: "'a::real_normed_vector \<Rightarrow> complex"
+  shows "f -- a --> L ==> (%x. Im(f x)) -- a --> Im(L)"
 by (simp add: LIM_NSLIM_iff NSLIM_Im)
 
-lemma LIM_cnj: "f -- a --> L ==> (%x. cnj (f x)) -- a --> cnj L"
-by (simp add: LIM_def complex_cnj_diff [symmetric])
+lemma LIM_cnj:
+  fixes f :: "'a::real_normed_vector \<Rightarrow> complex"
+  shows "f -- a --> L ==> (%x. cnj (f x)) -- a --> cnj L"
+by (simp add: LIM_eq complex_cnj_diff [symmetric])
 
-lemma LIM_cnj_iff: "((%x. cnj (f x)) -- a --> cnj L) = (f -- a --> L)"
-by (simp add: LIM_def complex_cnj_diff [symmetric])
+lemma LIM_cnj_iff:
+  fixes f :: "'a::real_normed_vector \<Rightarrow> complex"
+  shows "((%x. cnj (f x)) -- a --> cnj L) = (f -- a --> L)"
+by (simp add: LIM_eq complex_cnj_diff [symmetric])
 
 lemma starfun_norm: "( *f* (\<lambda>x. norm (f x))) = (\<lambda>x. hnorm (( *f* f) x))"
 by transfer (rule refl)
@@ -74,8 +82,10 @@
     approx_approx_zero_iff [symmetric] approx_minus_iff [symmetric])
 
 (** much, much easier standard proof **)
-lemma CLIM_CRLIM_iff: "(f -- x --> L) = ((%y. cmod(f y - L)) -- x --> 0)"
-by (simp add: LIM_def)
+lemma CLIM_CRLIM_iff:
+  fixes f :: "'a::real_normed_vector \<Rightarrow> complex"
+  shows "(f -- x --> L) = ((%y. cmod(f y - L)) -- x --> 0)"
+by (simp add: LIM_eq)
 
 (* so this is nicer nonstandard proof *)
 lemma NSCLIM_NSCRLIM_iff2:
@@ -92,7 +102,8 @@
 done
 
 lemma LIM_CRLIM_Re_Im_iff:
-     "(f -- a --> L) = ((%x. Re(f x)) -- a --> Re(L) &
+  fixes f :: "'a::real_normed_vector \<Rightarrow> complex"
+  shows "(f -- a --> L) = ((%x. Re(f x)) -- a --> Re(L) &
                          (%x. Im(f x)) -- a --> Im(L))"
 by (simp add: LIM_NSLIM_iff NSLIM_NSCRLIM_Re_Im_iff)
 
@@ -113,10 +124,14 @@
 lemma isContCR_cmod [simp]: "isCont cmod (a)"
 by (simp add: isNSCont_isCont_iff [symmetric])
 
-lemma isCont_Re: "isCont f a ==> isCont (%x. Re (f x)) a"
+lemma isCont_Re:
+  fixes f :: "'a::real_normed_vector \<Rightarrow> complex"
+  shows "isCont f a ==> isCont (%x. Re (f x)) a"
 by (simp add: isCont_def LIM_Re)
 
-lemma isCont_Im: "isCont f a ==> isCont (%x. Im (f x)) a"
+lemma isCont_Im:
+  fixes f :: "'a::real_normed_vector \<Rightarrow> complex"
+  shows "isCont f a ==> isCont (%x. Im (f x)) a"
 by (simp add: isCont_def LIM_Im)
 
 subsection{* Differentiation of Natural Number Powers*}
--- a/src/HOL/NSA/HLim.thy	Mon Jun 01 09:26:28 2009 +0200
+++ b/src/HOL/NSA/HLim.thy	Tue Jun 02 12:18:08 2009 +0200
@@ -287,7 +287,7 @@
     fix r::real assume r: "0 < r"
     with f obtain s where s: "0 < s" and
       less_r: "\<And>x y. norm (x - y) < s \<Longrightarrow> norm (f x - f y) < r"
-      by (auto simp add: isUCont_def)
+      by (auto simp add: isUCont_def dist_norm)
     from less_r have less_r':
        "\<And>x y. hnorm (x - y) < star_of s
         \<Longrightarrow> hnorm (starfun f x - starfun f y) < star_of r"
@@ -306,7 +306,7 @@
 lemma isNSUCont_isUCont:
   fixes f :: "'a::real_normed_vector \<Rightarrow> 'b::real_normed_vector"
   assumes f: "isNSUCont f" shows "isUCont f"
-proof (unfold isUCont_def, safe)
+proof (unfold isUCont_def dist_norm, safe)
   fix r::real assume r: "0 < r"
   have "\<exists>s>0. \<forall>x y. hnorm (x - y) < s
         \<longrightarrow> hnorm (starfun f x - starfun f y) < star_of r"
--- a/src/HOL/NSA/HTranscendental.thy	Mon Jun 01 09:26:28 2009 +0200
+++ b/src/HOL/NSA/HTranscendental.thy	Tue Jun 02 12:18:08 2009 +0200
@@ -18,13 +18,11 @@
 
 definition
   sinhr :: "real => hypreal" where
-  "sinhr x = st(sumhr (0, whn, %n. (if even(n) then 0 else
-             ((-1) ^ ((n - 1) div 2))/(real (fact n))) * (x ^ n)))"
+  "sinhr x = st(sumhr (0, whn, %n. sin_coeff n * x ^ n))"
   
 definition
   coshr :: "real => hypreal" where
-  "coshr x = st(sumhr (0, whn, %n. (if even(n) then
-            ((-1) ^ (n div 2))/(real (fact n)) else 0) * x ^ n))"
+  "coshr x = st(sumhr (0, whn, %n. cos_coeff n * x ^ n))"
 
 
 subsection{*Nonstandard Extension of Square Root Function*}
@@ -242,7 +240,7 @@
 apply (rule subst [where P="\<lambda>x. 1 \<approx> x", OF _ approx_refl])
 apply (rule rev_mp [OF hypnat_one_less_hypnat_omega])
 apply (rule_tac x="whn" in spec)
-apply (unfold sumhr_app, transfer, simp)
+apply (unfold sumhr_app, transfer, simp add: cos_coeff_def)
 done
 
 lemma STAR_exp_zero_approx_one [simp]: "( *f* exp) (0::hypreal) @= 1"
@@ -406,17 +404,14 @@
 Goalw [NSLIM_def] "(%h. ((x powr h) - 1) / h) -- 0 --NS> ln x"
 *)
 
-lemma HFinite_sin [simp]:
-     "sumhr (0, whn, %n. (if even(n) then 0 else  
-              (-1 ^ ((n - 1) div 2))/(real (fact n))) * x ^ n)  
-              \<in> HFinite"
+lemma HFinite_sin [simp]: "sumhr (0, whn, %n. sin_coeff n * x ^ n) \<in> HFinite"
 unfolding sumhr_app
 apply (simp only: star_zero_def starfun2_star_of)
 apply (rule NSBseqD2)
 apply (rule NSconvergent_NSBseq)
 apply (rule convergent_NSconvergent_iff [THEN iffD1])
 apply (rule summable_convergent_sumr_iff [THEN iffD1])
-apply (simp only: One_nat_def summable_sin)
+apply (rule summable_sin)
 done
 
 lemma STAR_sin_zero [simp]: "( *f* sin) 0 = 0"
@@ -432,10 +427,7 @@
            simp add: mult_assoc)
 done
 
-lemma HFinite_cos [simp]:
-     "sumhr (0, whn, %n. (if even(n) then  
-            (-1 ^ (n div 2))/(real (fact n)) else  
-            0) * x ^ n) \<in> HFinite"
+lemma HFinite_cos [simp]: "sumhr (0, whn, %n. cos_coeff n * x ^ n) \<in> HFinite"
 unfolding sumhr_app
 apply (simp only: star_zero_def starfun2_star_of)
 apply (rule NSBseqD2)
--- a/src/HOL/Quickcheck.thy	Mon Jun 01 09:26:28 2009 +0200
+++ b/src/HOL/Quickcheck.thy	Tue Jun 02 12:18:08 2009 +0200
@@ -4,6 +4,7 @@
 
 theory Quickcheck
 imports Random Code_Eval
+uses ("Tools/quickcheck_generators.ML")
 begin
 
 notation fcomp (infixl "o>" 60)
@@ -16,59 +17,7 @@
   fixes random :: "code_numeral \<Rightarrow> Random.seed \<Rightarrow> ('a \<times> (unit \<Rightarrow> term)) \<times> Random.seed"
 
 
-subsection {* Quickcheck generator *}
-
-ML {*
-structure Quickcheck =
-struct
-
-open Quickcheck;
-
-val eval_ref : (unit -> int -> int * int -> term list option * (int * int)) option ref = ref NONE;
-
-val target = "Quickcheck";
-
-fun mk_generator_expr thy prop tys =
-  let
-    val bound_max = length tys - 1;
-    val bounds = map_index (fn (i, ty) =>
-      (2 * (bound_max - i) + 1, 2 * (bound_max - i), 2 * i, ty)) tys;
-    val result = list_comb (prop, map (fn (i, _, _, _) => Bound i) bounds);
-    val terms = HOLogic.mk_list @{typ term} (map (fn (_, i, _, _) => Bound i $ @{term "()"}) bounds);
-    val check = @{term "If \<Colon> bool \<Rightarrow> term list option \<Rightarrow> term list option \<Rightarrow> term list option"}
-      $ result $ @{term "None \<Colon> term list option"} $ (@{term "Some \<Colon> term list \<Rightarrow> term list option "} $ terms);
-    val return = @{term "Pair \<Colon> term list option \<Rightarrow> Random.seed \<Rightarrow> term list option \<times> Random.seed"};
-    fun liftT T sT = sT --> HOLogic.mk_prodT (T, sT);
-    fun mk_termtyp ty = HOLogic.mk_prodT (ty, @{typ "unit \<Rightarrow> term"});
-    fun mk_scomp T1 T2 sT f g = Const (@{const_name scomp},
-      liftT T1 sT --> (T1 --> liftT T2 sT) --> liftT T2 sT) $ f $ g;
-    fun mk_split ty = Sign.mk_const thy
-      (@{const_name split}, [ty, @{typ "unit \<Rightarrow> term"}, liftT @{typ "term list option"} @{typ Random.seed}]);
-    fun mk_scomp_split ty t t' =
-      mk_scomp (mk_termtyp ty) @{typ "term list option"} @{typ Random.seed} t
-        (mk_split ty $ Abs ("", ty, Abs ("", @{typ "unit \<Rightarrow> term"}, t')));
-    fun mk_bindclause (_, _, i, ty) = mk_scomp_split ty
-      (Sign.mk_const thy (@{const_name random}, [ty]) $ Bound i);
-  in Abs ("n", @{typ code_numeral}, fold_rev mk_bindclause bounds (return $ check)) end;
-
-fun compile_generator_expr thy t =
-  let
-    val tys = (map snd o fst o strip_abs) t;
-    val t' = mk_generator_expr thy t tys;
-    val f = Code_ML.eval (SOME target) ("Quickcheck.eval_ref", eval_ref)
-      (fn proc => fn g => fn s => g s #>> (Option.map o map) proc) thy t' [];
-  in f #> Random_Engine.run end;
-
-end
-*}
-
-setup {*
-  Code_Target.extend_target (Quickcheck.target, (Code_ML.target_Eval, K I))
-  #> Quickcheck.add_generator ("code", Quickcheck.compile_generator_expr o ProofContext.theory_of)
-*}
-
-
-subsection {* Fundamental types*}
+subsection {* Fundamental and numeric types*}
 
 instantiation bool :: random
 begin
@@ -91,66 +40,6 @@
 
 end
 
-text {* Type @{typ "'a \<Rightarrow> 'b"} *}
-
-ML {*
-structure Random_Engine =
-struct
-
-open Random_Engine;
-
-fun random_fun (T1 : typ) (T2 : typ) (eq : 'a -> 'a -> bool) (term_of : 'a -> term)
-    (random : Random_Engine.seed -> ('b * (unit -> term)) * Random_Engine.seed)
-    (random_split : Random_Engine.seed -> Random_Engine.seed * Random_Engine.seed)
-    (seed : Random_Engine.seed) =
-  let
-    val (seed', seed'') = random_split seed;
-    val state = ref (seed', [], Const (@{const_name undefined}, T1 --> T2));
-    val fun_upd = Const (@{const_name fun_upd},
-      (T1 --> T2) --> T1 --> T2 --> T1 --> T2);
-    fun random_fun' x =
-      let
-        val (seed, fun_map, f_t) = ! state;
-      in case AList.lookup (uncurry eq) fun_map x
-       of SOME y => y
-        | NONE => let
-              val t1 = term_of x;
-              val ((y, t2), seed') = random seed;
-              val fun_map' = (x, y) :: fun_map;
-              val f_t' = fun_upd $ f_t $ t1 $ t2 ();
-              val _ = state := (seed', fun_map', f_t');
-            in y end
-      end;
-    fun term_fun' () = #3 (! state);
-  in ((random_fun', term_fun'), seed'') end;
-
-end
-*}
-
-axiomatization random_fun_aux :: "typerep \<Rightarrow> typerep \<Rightarrow> ('a \<Rightarrow> 'a \<Rightarrow> bool) \<Rightarrow> ('a \<Rightarrow> term)
-  \<Rightarrow> (Random.seed \<Rightarrow> ('b \<times> (unit \<Rightarrow> term)) \<times> Random.seed) \<Rightarrow> (Random.seed \<Rightarrow> Random.seed \<times> Random.seed)
-  \<Rightarrow> Random.seed \<Rightarrow> (('a \<Rightarrow> 'b) \<times> (unit \<Rightarrow> term)) \<times> Random.seed"
-
-code_const random_fun_aux (Quickcheck "Random'_Engine.random'_fun")
-  -- {* With enough criminal energy this can be abused to derive @{prop False};
-  for this reason we use a distinguished target @{text Quickcheck}
-  not spoiling the regular trusted code generation *}
-
-instantiation "fun" :: ("{eq, term_of}", "{type, random}") random
-begin
-
-definition random_fun :: "code_numeral \<Rightarrow> Random.seed \<Rightarrow> (('a \<Rightarrow> 'b) \<times> (unit \<Rightarrow> term)) \<times> Random.seed" where
-  "random n = random_fun_aux TYPEREP('a) TYPEREP('b) (op =) Code_Eval.term_of (random n) Random.split_seed"
-
-instance ..
-
-end
-
-code_reserved Quickcheck Random_Engine
-
-
-subsection {* Numeric types *}
-
 instantiation nat :: random
 begin
 
@@ -175,120 +64,47 @@
 
 end
 
-subsection {* Type copies *}
+
+subsection {* Complex generators *}
+
+definition collapse :: "('a \<Rightarrow> ('a \<Rightarrow> 'b \<times> 'a) \<times> 'a) \<Rightarrow> 'a \<Rightarrow> 'b \<times> 'a" where
+  "collapse f = (f o\<rightarrow> id)"
+
+definition beyond :: "code_numeral \<Rightarrow> code_numeral \<Rightarrow> code_numeral" where
+  "beyond k l = (if l > k then l else 0)"
 
-setup {*
-let
+lemma beyond_zero:
+  "beyond k 0 = 0"
+  by (simp add: beyond_def)
+
+use "Tools/quickcheck_generators.ML"
+setup {* Quickcheck_Generators.setup *}
+
+code_reserved Quickcheck Quickcheck_Generators
 
-fun mk_random_typecopy tyco vs constr typ thy =
-  let
-    val Ts = map TFree vs;  
-    val T = Type (tyco, Ts);
-    fun mk_termifyT T = HOLogic.mk_prodT (T, @{typ "unit \<Rightarrow> term"})
-    val Ttm = mk_termifyT T;
-    val typtm = mk_termifyT typ;
-    fun mk_const c Ts = Const (c, Sign.const_instance thy (c, Ts));
-    fun mk_random T = mk_const @{const_name random} [T];
-    val size = @{term "k\<Colon>code_numeral"};
-    val v = "x";
-    val t_v = Free (v, typtm);
-    val t_constr = mk_const constr Ts;
-    val lhs = mk_random T $ size;
-    val rhs = HOLogic.mk_ST [(((mk_random typ) $ size, @{typ Random.seed}), SOME (v, typtm))]
-      (HOLogic.mk_return Ttm @{typ Random.seed}
-      (mk_const "Code_Eval.valapp" [typ, T]
-        $ HOLogic.mk_prod (t_constr, Abs ("u", @{typ unit}, HOLogic.reflect_term t_constr)) $ t_v))
-      @{typ Random.seed} (SOME Ttm, @{typ Random.seed});
-    val eq = HOLogic.mk_Trueprop (HOLogic.mk_eq (lhs, rhs));
-  in   
-    thy
-    |> TheoryTarget.instantiation ([tyco], vs, @{sort random})
-    |> `(fn lthy => Syntax.check_term lthy eq)
-    |-> (fn eq => Specification.definition (NONE, (Attrib.empty_binding, eq)))
-    |> snd
-    |> Class.prove_instantiation_exit (K (Class.intro_classes_tac []))
-  end;
+text {* Type @{typ "'a \<Rightarrow> 'b"} *}
+
+axiomatization random_fun_aux :: "typerep \<Rightarrow> typerep \<Rightarrow> ('a \<Rightarrow> 'a \<Rightarrow> bool) \<Rightarrow> ('a \<Rightarrow> term)
+  \<Rightarrow> (Random.seed \<Rightarrow> ('b \<times> (unit \<Rightarrow> term)) \<times> Random.seed) \<Rightarrow> (Random.seed \<Rightarrow> Random.seed \<times> Random.seed)
+  \<Rightarrow> Random.seed \<Rightarrow> (('a \<Rightarrow> 'b) \<times> (unit \<Rightarrow> term)) \<times> Random.seed"
 
-fun ensure_random_typecopy tyco thy =
-  let
-    val SOME { vs = raw_vs, constr, typ = raw_typ, ... } =
-      TypecopyPackage.get_info thy tyco;
-    val constrain = curry (Sorts.inter_sort (Sign.classes_of thy));
-    val typ = map_atyps (fn TFree (v, sort) =>
-      TFree (v, constrain sort @{sort random})) raw_typ;
-    val vs' = Term.add_tfreesT typ [];
-    val vs = map (fn (v, sort) =>
-      (v, the_default (constrain sort @{sort typerep}) (AList.lookup (op =) vs' v))) raw_vs;
-    val do_inst = Sign.of_sort thy (typ, @{sort random});
-  in if do_inst then mk_random_typecopy tyco vs constr typ thy else thy end;
+code_const random_fun_aux (Quickcheck "Quickcheck'_Generators.random'_fun")
+  -- {* With enough criminal energy this can be abused to derive @{prop False};
+  for this reason we use a distinguished target @{text Quickcheck}
+  not spoiling the regular trusted code generation *}
 
-in
+instantiation "fun" :: ("{eq, term_of}", "{type, random}") random
+begin
 
-TypecopyPackage.interpretation ensure_random_typecopy
+definition random_fun :: "code_numeral \<Rightarrow> Random.seed \<Rightarrow> (('a \<Rightarrow> 'b) \<times> (unit \<Rightarrow> term)) \<times> Random.seed" where
+  "random n = random_fun_aux TYPEREP('a) TYPEREP('b) (op =) Code_Eval.term_of (random n) Random.split_seed"
+
+instance ..
 
 end
-*}
 
 
-subsection {* Type copies *}
-
-setup {*
-let
-
-fun mk_random_typecopy tyco vs constr typ thy =
-  let
-    val Ts = map TFree vs;
-    val T = Type (tyco, Ts);
-    fun mk_termifyT T = HOLogic.mk_prodT (T, @{typ "unit \<Rightarrow> term"})
-    val Ttm = mk_termifyT T;
-    val typtm = mk_termifyT typ;
-    fun mk_const c Ts = Const (c, Sign.const_instance thy (c, Ts));
-    fun mk_random T = mk_const @{const_name random} [T];
-    val size = @{term "k\<Colon>code_numeral"};
-    val v = "x";
-    val t_v = Free (v, typtm);
-    val t_constr = mk_const constr Ts;
-    val lhs = mk_random T $ size;
-    val rhs = HOLogic.mk_ST [(((mk_random typ) $ size, @{typ Random.seed}), SOME (v, typtm))]
-      (HOLogic.mk_return Ttm @{typ Random.seed}
-      (mk_const "Code_Eval.valapp" [typ, T]
-        $ HOLogic.mk_prod (t_constr, Abs ("u", @{typ unit}, HOLogic.reflect_term t_constr)) $ t_v))
-      @{typ Random.seed} (SOME Ttm, @{typ Random.seed});
-    val eq = HOLogic.mk_Trueprop (HOLogic.mk_eq (lhs, rhs));
-  in
-    thy
-    |> TheoryTarget.instantiation ([tyco], vs, @{sort random})
-    |> `(fn lthy => Syntax.check_term lthy eq)
-    |-> (fn eq => Specification.definition (NONE, (Attrib.empty_binding, eq)))
-    |> snd
-    |> Class.prove_instantiation_exit (K (Class.intro_classes_tac []))
-  end;
-
-fun ensure_random_typecopy tyco thy =
-  let
-    val SOME { vs = raw_vs, constr, typ = raw_typ, ... } =
-      TypecopyPackage.get_info thy tyco;
-    val constrain = curry (Sorts.inter_sort (Sign.classes_of thy));
-    val typ = map_atyps (fn TFree (v, sort) =>
-      TFree (v, constrain sort @{sort random})) raw_typ;
-    val vs' = Term.add_tfreesT typ [];
-    val vs = map (fn (v, sort) =>
-      (v, the_default (constrain sort @{sort typerep}) (AList.lookup (op =) vs' v))) raw_vs;
-    val do_inst = Sign.of_sort thy (typ, @{sort random});
-  in if do_inst then mk_random_typecopy tyco vs constr typ thy else thy end;
-
-in
-
-TypecopyPackage.interpretation ensure_random_typecopy
-
-end
-*}
-
-
-subsection {* Datatypes *}
-
-text {* under construction *}
-
+hide (open) const collapse beyond
 
 no_notation fcomp (infixl "o>" 60)
 no_notation scomp (infixl "o\<rightarrow>" 60)
--- a/src/HOL/Random.thy	Mon Jun 01 09:26:28 2009 +0200
+++ b/src/HOL/Random.thy	Tue Jun 02 12:18:08 2009 +0200
@@ -118,8 +118,12 @@
   then show ?thesis by (simp add: select_weight_def scomp_def split_def) 
 qed
 
+lemma select_weight_cons_zero:
+  "select_weight ((0, x) # xs) = select_weight xs"
+  by (simp add: select_weight_def)
+
 lemma select_weigth_drop_zero:
-  "Random.select_weight (filter (\<lambda>(k, _). k > 0) xs) = Random.select_weight xs"
+  "select_weight (filter (\<lambda>(k, _). k > 0) xs) = select_weight xs"
 proof -
   have "listsum (map fst [(k, _)\<leftarrow>xs . 0 < k]) = listsum (map fst xs)"
     by (induct xs) auto
@@ -128,9 +132,9 @@
 
 lemma select_weigth_select:
   assumes "xs \<noteq> []"
-  shows "Random.select_weight (map (Pair 1) xs) = Random.select xs"
+  shows "select_weight (map (Pair 1) xs) = select xs"
 proof -
-  have less: "\<And>s. fst (Random.range (Code_Numeral.of_nat (length xs)) s) < Code_Numeral.of_nat (length xs)"
+  have less: "\<And>s. fst (range (Code_Numeral.of_nat (length xs)) s) < Code_Numeral.of_nat (length xs)"
     using assms by (intro range) simp
   moreover have "listsum (map fst (map (Pair 1) xs)) = Code_Numeral.of_nat (length xs)"
     by (induct xs) simp_all
--- a/src/HOL/RealVector.thy	Mon Jun 01 09:26:28 2009 +0200
+++ b/src/HOL/RealVector.thy	Tue Jun 02 12:18:08 2009 +0200
@@ -169,6 +169,11 @@
 lemmas scaleR_cancel_left = real_vector.scale_cancel_left
 lemmas scaleR_cancel_right = real_vector.scale_cancel_right
 
+lemma scaleR_minus1_left [simp]:
+  fixes x :: "'a::real_vector"
+  shows "scaleR (-1) x = - x"
+  using scaleR_minus_left [of 1 x] by simp
+
 class real_algebra = real_vector + ring +
   assumes mult_scaleR_left [simp]: "scaleR a x * y = scaleR a (x * y)"
   and mult_scaleR_right [simp]: "x * scaleR a y = scaleR a (x * y)"
@@ -411,6 +416,45 @@
   by (rule Reals_cases) auto
 
 
+subsection {* Metric spaces *}
+
+class dist =
+  fixes dist :: "'a \<Rightarrow> 'a \<Rightarrow> real"
+
+class metric_space = dist +
+  assumes dist_eq_0_iff [simp]: "dist x y = 0 \<longleftrightarrow> x = y"
+  assumes dist_triangle2: "dist x y \<le> dist x z + dist y z"
+begin
+
+lemma dist_self [simp]: "dist x x = 0"
+by simp
+
+lemma zero_le_dist [simp]: "0 \<le> dist x y"
+using dist_triangle2 [of x x y] by simp
+
+lemma zero_less_dist_iff: "0 < dist x y \<longleftrightarrow> x \<noteq> y"
+by (simp add: less_le)
+
+lemma dist_not_less_zero [simp]: "\<not> dist x y < 0"
+by (simp add: not_less)
+
+lemma dist_le_zero_iff [simp]: "dist x y \<le> 0 \<longleftrightarrow> x = y"
+by (simp add: le_less)
+
+lemma dist_commute: "dist x y = dist y x"
+proof (rule order_antisym)
+  show "dist x y \<le> dist y x"
+    using dist_triangle2 [of x y x] by simp
+  show "dist y x \<le> dist x y"
+    using dist_triangle2 [of y x y] by simp
+qed
+
+lemma dist_triangle: "dist x z \<le> dist x y + dist y z"
+using dist_triangle2 [of x z y] by (simp add: dist_commute)
+
+end
+
+
 subsection {* Real normed vector spaces *}
 
 class norm =
@@ -419,7 +463,10 @@
 class sgn_div_norm = scaleR + norm + sgn +
   assumes sgn_div_norm: "sgn x = x /\<^sub>R norm x"
 
-class real_normed_vector = real_vector + sgn_div_norm +
+class dist_norm = dist + norm + minus +
+  assumes dist_norm: "dist x y = norm (x - y)"
+
+class real_normed_vector = real_vector + sgn_div_norm + dist_norm +
   assumes norm_ge_zero [simp]: "0 \<le> norm x"
   and norm_eq_zero [simp]: "norm x = 0 \<longleftrightarrow> x = 0"
   and norm_triangle_ineq: "norm (x + y) \<le> norm x + norm y"
@@ -453,8 +500,12 @@
 definition
   real_norm_def [simp]: "norm r = \<bar>r\<bar>"
 
+definition
+  dist_real_def: "dist x y = \<bar>x - y\<bar>"
+
 instance
 apply (intro_classes, unfold real_norm_def real_scaleR_def)
+apply (rule dist_real_def)
 apply (simp add: real_sgn_def)
 apply (rule abs_ge_zero)
 apply (rule abs_eq_0)
@@ -632,6 +683,18 @@
   shows "norm (x ^ n) = norm x ^ n"
 by (induct n) (simp_all add: norm_mult)
 
+text {* Every normed vector space is a metric space. *}
+
+instance real_normed_vector < metric_space
+proof
+  fix x y :: 'a show "dist x y = 0 \<longleftrightarrow> x = y"
+    unfolding dist_norm by simp
+next
+  fix x y z :: 'a show "dist x y \<le> dist x z + dist y z"
+    unfolding dist_norm
+    using norm_triangle_ineq4 [of "x - z" "y - z"] by simp
+qed
+
 
 subsection {* Sign function *}
 
--- a/src/HOL/Relation_Power.thy	Mon Jun 01 09:26:28 2009 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,154 +0,0 @@
-(*  Title:      HOL/Relation_Power.thy
-    Author:     Tobias Nipkow
-    Copyright   1996  TU Muenchen
-*)
-
-header{*Powers of Relations and Functions*}
-
-theory Relation_Power
-imports Power Transitive_Closure Plain
-begin
-
-consts funpower :: "('a \<Rightarrow> 'b) \<Rightarrow> nat \<Rightarrow> 'a \<Rightarrow> 'b" (infixr "^^" 80)
-
-overloading
-  relpow \<equiv> "funpower \<Colon> ('a \<times> 'a) set \<Rightarrow> nat \<Rightarrow> ('a \<times> 'a) set"
-begin
-
-text {* @{text "R ^^ n = R O ... O R"}, the n-fold composition of @{text R} *}
-
-primrec relpow where
-    "(R \<Colon> ('a \<times> 'a) set) ^^ 0 = Id"
-  | "(R \<Colon> ('a \<times> 'a) set) ^^ Suc n = R O (R ^^ n)"
-
-end
-
-overloading
-  funpow \<equiv> "funpower \<Colon> ('a \<Rightarrow> 'a) \<Rightarrow> nat \<Rightarrow> 'a \<Rightarrow> 'a"
-begin
-
-text {* @{text "f ^^ n = f o ... o f"}, the n-fold composition of @{text f} *}
-
-primrec funpow where
-    "(f \<Colon> 'a \<Rightarrow> 'a) ^^ 0 = id"
-  | "(f \<Colon> 'a \<Rightarrow> 'a) ^^ Suc n = f o (f ^^ n)"
-
-end
-
-primrec fun_pow :: "nat \<Rightarrow> ('a \<Rightarrow> 'a) \<Rightarrow> 'a \<Rightarrow> 'a" where
-    "fun_pow 0 f = id"
-  | "fun_pow (Suc n) f = f o fun_pow n f"
-
-lemma funpow_fun_pow [code unfold]:
-  "f ^^ n = fun_pow n f"
-  unfolding funpow_def fun_pow_def ..
-
-lemma funpow_add:
-  "f ^^ (m + n) = f ^^ m o f ^^ n"
-  by (induct m) simp_all
-
-lemma funpow_swap1:
-  "f ((f ^^ n) x) = (f ^^ n) (f x)"
-proof -
-  have "f ((f ^^ n) x) = (f ^^ (n+1)) x" unfolding One_nat_def by simp
-  also have "\<dots>  = (f ^^ n o f ^^ 1) x" by (simp only: funpow_add)
-  also have "\<dots> = (f ^^ n) (f x)" unfolding One_nat_def by simp
-  finally show ?thesis .
-qed
-
-lemma rel_pow_1 [simp]:
-  fixes R :: "('a * 'a) set"
-  shows "R ^^ 1 = R"
-  by simp
-
-lemma rel_pow_0_I: 
-  "(x, x) \<in> R ^^ 0"
-  by simp
-
-lemma rel_pow_Suc_I:
-  "(x, y) \<in>  R ^^ n \<Longrightarrow> (y, z) \<in> R \<Longrightarrow> (x, z) \<in> R ^^ Suc n"
-  by auto
-
-lemma rel_pow_Suc_I2:
-  "(x, y) \<in> R \<Longrightarrow> (y, z) \<in> R ^^ n \<Longrightarrow> (x, z) \<in> R ^^ Suc n"
-  by (induct n arbitrary: z) (simp, fastsimp)
-
-lemma rel_pow_0_E:
-  "(x, y) \<in> R ^^ 0 \<Longrightarrow> (x = y \<Longrightarrow> P) \<Longrightarrow> P"
-  by simp
-
-lemma rel_pow_Suc_E:
-  "(x, z) \<in> R ^^ Suc n \<Longrightarrow> (\<And>y. (x, y) \<in> R ^^ n \<Longrightarrow> (y, z) \<in> R \<Longrightarrow> P) \<Longrightarrow> P"
-  by auto
-
-lemma rel_pow_E:
-  "(x, z) \<in>  R ^^ n \<Longrightarrow>  (n = 0 \<Longrightarrow> x = z \<Longrightarrow> P)
-   \<Longrightarrow> (\<And>y m. n = Suc m \<Longrightarrow> (x, y) \<in>  R ^^ m \<Longrightarrow> (y, z) \<in> R \<Longrightarrow> P)
-   \<Longrightarrow> P"
-  by (cases n) auto
-
-lemma rel_pow_Suc_D2:
-  "(x, z) \<in> R ^^ Suc n \<Longrightarrow> (\<exists>y. (x, y) \<in> R \<and> (y, z) \<in> R ^^ n)"
-  apply (induct n arbitrary: x z)
-   apply (blast intro: rel_pow_0_I elim: rel_pow_0_E rel_pow_Suc_E)
-  apply (blast intro: rel_pow_Suc_I elim: rel_pow_0_E rel_pow_Suc_E)
-  done
-
-lemma rel_pow_Suc_D2':
-  "\<forall>x y z. (x, y) \<in> R ^^ n \<and> (y, z) \<in> R \<longrightarrow> (\<exists>w. (x, w) \<in> R \<and> (w, z) \<in> R ^^ n)"
-  by (induct n) (simp_all, blast)
-
-lemma rel_pow_E2:
-  "(x, z) \<in> R ^^ n \<Longrightarrow>  (n = 0 \<Longrightarrow> x = z \<Longrightarrow> P)
-     \<Longrightarrow> (\<And>y m. n = Suc m \<Longrightarrow> (x, y) \<in> R \<Longrightarrow> (y, z) \<in> R ^^ m \<Longrightarrow> P)
-   \<Longrightarrow> P"
-  apply (cases n, simp)
-  apply (cut_tac n=nat and R=R in rel_pow_Suc_D2', simp, blast)
-  done
-
-lemma rtrancl_imp_UN_rel_pow:
-  "p \<in> R^* \<Longrightarrow> p \<in> (\<Union>n. R ^^ n)"
-  apply (cases p) apply (simp only:)
-  apply (erule rtrancl_induct)
-   apply (blast intro: rel_pow_0_I rel_pow_Suc_I)+
-  done
-
-lemma rel_pow_imp_rtrancl:
-  "p \<in> R ^^ n \<Longrightarrow> p \<in> R^*"
-  apply (induct n arbitrary: p)
-  apply (simp_all only: split_tupled_all)
-   apply (blast intro: rtrancl_refl elim: rel_pow_0_E)
-  apply (blast elim: rel_pow_Suc_E intro: rtrancl_into_rtrancl)
-  done
-
-lemma rtrancl_is_UN_rel_pow:
-  "R^* = (UN n. R ^^ n)"
-  by (blast intro: rtrancl_imp_UN_rel_pow rel_pow_imp_rtrancl)
-
-lemma trancl_power:
-  "x \<in> r^+ = (\<exists>n > 0. x \<in> r ^^ n)"
-  apply (cases x)
-  apply simp
-  apply (rule iffI)
-   apply (drule tranclD2)
-   apply (clarsimp simp: rtrancl_is_UN_rel_pow)
-   apply (rule_tac x="Suc x" in exI)
-   apply (clarsimp simp: rel_comp_def)
-   apply fastsimp
-  apply clarsimp
-  apply (case_tac n, simp)
-  apply clarsimp
-  apply (drule rel_pow_imp_rtrancl)
-  apply fastsimp
-  done
-
-lemma single_valued_rel_pow:
-  fixes R :: "('a * 'a) set"
-  shows "single_valued R \<Longrightarrow> single_valued (R ^^ n)"
-  apply (induct n arbitrary: R)
-  apply simp_all
-  apply (rule single_valuedI)
-  apply (fast dest: single_valuedD elim: rel_pow_Suc_E)
-  done
-
-end
--- a/src/HOL/SEQ.thy	Mon Jun 01 09:26:28 2009 +0200
+++ b/src/HOL/SEQ.thy	Tue Jun 02 12:18:08 2009 +0200
@@ -9,27 +9,31 @@
 header {* Sequences and Convergence *}
 
 theory SEQ
-imports RealVector RComplete
+imports Limits
 begin
 
 definition
+  sequentially :: "nat filter" where
+  [code del]: "sequentially = Abs_filter (\<lambda>P. \<exists>N. \<forall>n\<ge>N. P n)"
+
+definition
   Zseq :: "[nat \<Rightarrow> 'a::real_normed_vector] \<Rightarrow> bool" where
     --{*Standard definition of sequence converging to zero*}
   [code del]: "Zseq X = (\<forall>r>0. \<exists>no. \<forall>n\<ge>no. norm (X n) < r)"
 
 definition
-  LIMSEQ :: "[nat => 'a::real_normed_vector, 'a] => bool"
+  LIMSEQ :: "[nat \<Rightarrow> 'a::metric_space, 'a] \<Rightarrow> bool"
     ("((_)/ ----> (_))" [60, 60] 60) where
     --{*Standard definition of convergence of sequence*}
-  [code del]: "X ----> L = (\<forall>r. 0 < r --> (\<exists>no. \<forall>n. no \<le> n --> norm (X n - L) < r))"
+  [code del]: "X ----> L = (\<forall>r>0. \<exists>no. \<forall>n\<ge>no. dist (X n) L < r)"
 
 definition
-  lim :: "(nat => 'a::real_normed_vector) => 'a" where
+  lim :: "(nat \<Rightarrow> 'a::real_normed_vector) \<Rightarrow> 'a" where
     --{*Standard definition of limit using choice operator*}
   "lim X = (THE L. X ----> L)"
 
 definition
-  convergent :: "(nat => 'a::real_normed_vector) => bool" where
+  convergent :: "(nat \<Rightarrow> 'a::metric_space) \<Rightarrow> bool" where
     --{*Standard definition of convergence*}
   "convergent X = (\<exists>L. X ----> L)"
 
@@ -62,10 +66,28 @@
   [code del]:   "subseq f = (\<forall>m. \<forall>n>m. (f m) < (f n))"
 
 definition
-  Cauchy :: "(nat => 'a::real_normed_vector) => bool" where
+  Cauchy :: "(nat \<Rightarrow> 'a::metric_space) \<Rightarrow> bool" where
     --{*Standard definition of the Cauchy condition*}
-  [code del]: "Cauchy X = (\<forall>e>0. \<exists>M. \<forall>m \<ge> M. \<forall>n \<ge> M. norm (X m - X n) < e)"
+  [code del]: "Cauchy X = (\<forall>e>0. \<exists>M. \<forall>m \<ge> M. \<forall>n \<ge> M. dist (X m) (X n) < e)"
+
+
+subsection {* Sequentially *}
 
+lemma eventually_sequentially:
+  "eventually P sequentially \<longleftrightarrow> (\<exists>N. \<forall>n\<ge>N. P n)"
+unfolding sequentially_def
+apply (rule eventually_Abs_filter)
+apply simp
+apply (clarify, rule_tac x=N in exI, simp)
+apply (clarify, rename_tac M N)
+apply (rule_tac x="max M N" in exI, simp)
+done
+
+lemma Zseq_conv_Zfun: "Zseq X \<longleftrightarrow> Zfun X sequentially"
+unfolding Zseq_def Zfun_def eventually_sequentially ..
+
+lemma LIMSEQ_conv_tendsto: "(X ----> L) \<longleftrightarrow> tendsto X L sequentially"
+unfolding LIMSEQ_def tendsto_def eventually_sequentially ..
 
 subsection {* Bounded Sequences *}
 
@@ -134,61 +156,14 @@
   assumes X: "Zseq X"
   assumes Y: "\<And>n. norm (Y n) \<le> norm (X n) * K"
   shows "Zseq (\<lambda>n. Y n)"
-proof (cases)
-  assume K: "0 < K"
-  show ?thesis
-  proof (rule ZseqI)
-    fix r::real assume "0 < r"
-    hence "0 < r / K"
-      using K by (rule divide_pos_pos)
-    then obtain N where "\<forall>n\<ge>N. norm (X n) < r / K"
-      using ZseqD [OF X] by fast
-    hence "\<forall>n\<ge>N. norm (X n) * K < r"
-      by (simp add: pos_less_divide_eq K)
-    hence "\<forall>n\<ge>N. norm (Y n) < r"
-      by (simp add: order_le_less_trans [OF Y])
-    thus "\<exists>N. \<forall>n\<ge>N. norm (Y n) < r" ..
-  qed
-next
-  assume "\<not> 0 < K"
-  hence K: "K \<le> 0" by (simp only: linorder_not_less)
-  {
-    fix n::nat
-    have "norm (Y n) \<le> norm (X n) * K" by (rule Y)
-    also have "\<dots> \<le> norm (X n) * 0"
-      using K norm_ge_zero by (rule mult_left_mono)
-    finally have "norm (Y n) = 0" by simp
-  }
-  thus ?thesis by (simp add: Zseq_zero)
-qed
+using assms unfolding Zseq_conv_Zfun by (rule Zfun_imp_Zfun)
 
 lemma Zseq_le: "\<lbrakk>Zseq Y; \<forall>n. norm (X n) \<le> norm (Y n)\<rbrakk> \<Longrightarrow> Zseq X"
 by (erule_tac K="1" in Zseq_imp_Zseq, simp)
 
 lemma Zseq_add:
-  assumes X: "Zseq X"
-  assumes Y: "Zseq Y"
-  shows "Zseq (\<lambda>n. X n + Y n)"
-proof (rule ZseqI)
-  fix r::real assume "0 < r"
-  hence r: "0 < r / 2" by simp
-  obtain M where M: "\<forall>n\<ge>M. norm (X n) < r/2"
-    using ZseqD [OF X r] by fast
-  obtain N where N: "\<forall>n\<ge>N. norm (Y n) < r/2"
-    using ZseqD [OF Y r] by fast
-  show "\<exists>N. \<forall>n\<ge>N. norm (X n + Y n) < r"
-  proof (intro exI allI impI)
-    fix n assume n: "max M N \<le> n"
-    have "norm (X n + Y n) \<le> norm (X n) + norm (Y n)"
-      by (rule norm_triangle_ineq)
-    also have "\<dots> < r/2 + r/2"
-    proof (rule add_strict_mono)
-      from M n show "norm (X n) < r/2" by simp
-      from N n show "norm (Y n) < r/2" by simp
-    qed
-    finally show "norm (X n + Y n) < r" by simp
-  qed
-qed
+  "Zseq X \<Longrightarrow> Zseq Y \<Longrightarrow> Zseq (\<lambda>n. X n + Y n)"
+unfolding Zseq_conv_Zfun by (rule Zfun_add)
 
 lemma Zseq_minus: "Zseq X \<Longrightarrow> Zseq (\<lambda>n. - X n)"
 unfolding Zseq_def by simp
@@ -197,44 +172,12 @@
 by (simp only: diff_minus Zseq_add Zseq_minus)
 
 lemma (in bounded_linear) Zseq:
-  assumes X: "Zseq X"
-  shows "Zseq (\<lambda>n. f (X n))"
-proof -
-  obtain K where "\<And>x. norm (f x) \<le> norm x * K"
-    using bounded by fast
-  with X show ?thesis
-    by (rule Zseq_imp_Zseq)
-qed
+  "Zseq X \<Longrightarrow> Zseq (\<lambda>n. f (X n))"
+unfolding Zseq_conv_Zfun by (rule Zfun)
 
 lemma (in bounded_bilinear) Zseq:
-  assumes X: "Zseq X"
-  assumes Y: "Zseq Y"
-  shows "Zseq (\<lambda>n. X n ** Y n)"
-proof (rule ZseqI)
-  fix r::real assume r: "0 < r"
-  obtain K where K: "0 < K"
-    and norm_le: "\<And>x y. norm (x ** y) \<le> norm x * norm y * K"
-    using pos_bounded by fast
-  from K have K': "0 < inverse K"
-    by (rule positive_imp_inverse_positive)
-  obtain M where M: "\<forall>n\<ge>M. norm (X n) < r"
-    using ZseqD [OF X r] by fast
-  obtain N where N: "\<forall>n\<ge>N. norm (Y n) < inverse K"
-    using ZseqD [OF Y K'] by fast
-  show "\<exists>N. \<forall>n\<ge>N. norm (X n ** Y n) < r"
-  proof (intro exI allI impI)
-    fix n assume n: "max M N \<le> n"
-    have "norm (X n ** Y n) \<le> norm (X n) * norm (Y n) * K"
-      by (rule norm_le)
-    also have "norm (X n) * norm (Y n) * K < r * inverse K * K"
-    proof (intro mult_strict_right_mono mult_strict_mono' norm_ge_zero K)
-      from M n show Xn: "norm (X n) < r" by simp
-      from N n show Yn: "norm (Y n) < inverse K" by simp
-    qed
-    also from K have "r * inverse K * K = r" by simp
-    finally show "norm (X n ** Y n) < r" .
-  qed
-qed
+  "Zseq X \<Longrightarrow> Zseq Y \<Longrightarrow> Zseq (\<lambda>n. X n ** Y n)"
+unfolding Zseq_conv_Zfun by (rule Zfun)
 
 lemma (in bounded_bilinear) Zseq_prod_Bseq:
   assumes X: "Zseq X"
@@ -302,38 +245,51 @@
 subsection {* Limits of Sequences *}
 
 lemma LIMSEQ_iff:
-      "(X ----> L) = (\<forall>r>0. \<exists>no. \<forall>n \<ge> no. norm (X n - L) < r)"
-by (rule LIMSEQ_def)
+  fixes L :: "'a::real_normed_vector"
+  shows "(X ----> L) = (\<forall>r>0. \<exists>no. \<forall>n \<ge> no. norm (X n - L) < r)"
+unfolding LIMSEQ_def dist_norm ..
 
 lemma LIMSEQ_Zseq_iff: "((\<lambda>n. X n) ----> L) = Zseq (\<lambda>n. X n - L)"
-by (simp only: LIMSEQ_def Zseq_def)
+by (simp only: LIMSEQ_iff Zseq_def)
+
+lemma metric_LIMSEQ_I:
+  "(\<And>r. 0 < r \<Longrightarrow> \<exists>no. \<forall>n\<ge>no. dist (X n) L < r) \<Longrightarrow> X ----> L"
+by (simp add: LIMSEQ_def)
+
+lemma metric_LIMSEQ_D:
+  "\<lbrakk>X ----> L; 0 < r\<rbrakk> \<Longrightarrow> \<exists>no. \<forall>n\<ge>no. dist (X n) L < r"
+by (simp add: LIMSEQ_def)
 
 lemma LIMSEQ_I:
-  "(\<And>r. 0 < r \<Longrightarrow> \<exists>no. \<forall>n\<ge>no. norm (X n - L) < r) \<Longrightarrow> X ----> L"
-by (simp add: LIMSEQ_def)
+  fixes L :: "'a::real_normed_vector"
+  shows "(\<And>r. 0 < r \<Longrightarrow> \<exists>no. \<forall>n\<ge>no. norm (X n - L) < r) \<Longrightarrow> X ----> L"
+by (simp add: LIMSEQ_iff)
 
 lemma LIMSEQ_D:
-  "\<lbrakk>X ----> L; 0 < r\<rbrakk> \<Longrightarrow> \<exists>no. \<forall>n\<ge>no. norm (X n - L) < r"
-by (simp add: LIMSEQ_def)
+  fixes L :: "'a::real_normed_vector"
+  shows "\<lbrakk>X ----> L; 0 < r\<rbrakk> \<Longrightarrow> \<exists>no. \<forall>n\<ge>no. norm (X n - L) < r"
+by (simp add: LIMSEQ_iff)
 
 lemma LIMSEQ_const: "(\<lambda>n. k) ----> k"
 by (simp add: LIMSEQ_def)
 
-lemma LIMSEQ_const_iff: "(\<lambda>n. k) ----> l = (k = l)"
-by (simp add: LIMSEQ_Zseq_iff Zseq_const_iff)
+lemma LIMSEQ_const_iff: "(\<lambda>n. k) ----> l \<longleftrightarrow> k = l"
+apply (safe intro!: LIMSEQ_const)
+apply (rule ccontr)
+apply (drule_tac r="dist k l" in metric_LIMSEQ_D)
+apply (simp add: zero_less_dist_iff)
+apply auto
+done
 
-lemma LIMSEQ_norm: "X ----> a \<Longrightarrow> (\<lambda>n. norm (X n)) ----> norm a"
-apply (simp add: LIMSEQ_def, safe)
-apply (drule_tac x="r" in spec, safe)
-apply (rule_tac x="no" in exI, safe)
-apply (drule_tac x="n" in spec, safe)
-apply (erule order_le_less_trans [OF norm_triangle_ineq3])
-done
+lemma LIMSEQ_norm:
+  fixes a :: "'a::real_normed_vector"
+  shows "X ----> a \<Longrightarrow> (\<lambda>n. norm (X n)) ----> norm a"
+unfolding LIMSEQ_conv_tendsto by (rule tendsto_norm)
 
 lemma LIMSEQ_ignore_initial_segment:
   "f ----> a \<Longrightarrow> (\<lambda>n. f (n + k)) ----> a"
-apply (rule LIMSEQ_I)
-apply (drule (1) LIMSEQ_D)
+apply (rule metric_LIMSEQ_I)
+apply (drule (1) metric_LIMSEQ_D)
 apply (erule exE, rename_tac N)
 apply (rule_tac x=N in exI)
 apply simp
@@ -341,8 +297,8 @@
 
 lemma LIMSEQ_offset:
   "(\<lambda>n. f (n + k)) ----> a \<Longrightarrow> f ----> a"
-apply (rule LIMSEQ_I)
-apply (drule (1) LIMSEQ_D)
+apply (rule metric_LIMSEQ_I)
+apply (drule (1) metric_LIMSEQ_D)
 apply (erule exE, rename_tac N)
 apply (rule_tac x="N + k" in exI)
 apply clarify
@@ -363,40 +319,44 @@
   unfolding LIMSEQ_def
   by (metis div_le_dividend div_mult_self1_is_m le_trans nat_mult_commute)
 
-
-lemma add_diff_add:
-  fixes a b c d :: "'a::ab_group_add"
-  shows "(a + c) - (b + d) = (a - b) + (c - d)"
-by simp
+lemma LIMSEQ_add:
+  fixes a b :: "'a::real_normed_vector"
+  shows "\<lbrakk>X ----> a; Y ----> b\<rbrakk> \<Longrightarrow> (\<lambda>n. X n + Y n) ----> a + b"
+unfolding LIMSEQ_conv_tendsto by (rule tendsto_add)
 
-lemma minus_diff_minus:
-  fixes a b :: "'a::ab_group_add"
-  shows "(- a) - (- b) = - (a - b)"
-by simp
+lemma LIMSEQ_minus:
+  fixes a :: "'a::real_normed_vector"
+  shows "X ----> a \<Longrightarrow> (\<lambda>n. - X n) ----> - a"
+unfolding LIMSEQ_conv_tendsto by (rule tendsto_minus)
 
-lemma LIMSEQ_add: "\<lbrakk>X ----> a; Y ----> b\<rbrakk> \<Longrightarrow> (\<lambda>n. X n + Y n) ----> a + b"
-by (simp only: LIMSEQ_Zseq_iff add_diff_add Zseq_add)
-
-lemma LIMSEQ_minus: "X ----> a \<Longrightarrow> (\<lambda>n. - X n) ----> - a"
-by (simp only: LIMSEQ_Zseq_iff minus_diff_minus Zseq_minus)
-
-lemma LIMSEQ_minus_cancel: "(\<lambda>n. - X n) ----> - a \<Longrightarrow> X ----> a"
+lemma LIMSEQ_minus_cancel:
+  fixes a :: "'a::real_normed_vector"
+  shows "(\<lambda>n. - X n) ----> - a \<Longrightarrow> X ----> a"
 by (drule LIMSEQ_minus, simp)
 
-lemma LIMSEQ_diff: "\<lbrakk>X ----> a; Y ----> b\<rbrakk> \<Longrightarrow> (\<lambda>n. X n - Y n) ----> a - b"
-by (simp add: diff_minus LIMSEQ_add LIMSEQ_minus)
+lemma LIMSEQ_diff:
+  fixes a b :: "'a::real_normed_vector"
+  shows "\<lbrakk>X ----> a; Y ----> b\<rbrakk> \<Longrightarrow> (\<lambda>n. X n - Y n) ----> a - b"
+unfolding LIMSEQ_conv_tendsto by (rule tendsto_diff)
 
 lemma LIMSEQ_unique: "\<lbrakk>X ----> a; X ----> b\<rbrakk> \<Longrightarrow> a = b"
-by (drule (1) LIMSEQ_diff, simp add: LIMSEQ_const_iff)
+apply (rule ccontr)
+apply (drule_tac r="dist a b / 2" in metric_LIMSEQ_D, simp add: zero_less_dist_iff)
+apply (drule_tac r="dist a b / 2" in metric_LIMSEQ_D, simp add: zero_less_dist_iff)
+apply (clarify, rename_tac M N)
+apply (subgoal_tac "dist a b < dist a b / 2 + dist a b / 2", simp)
+apply (subgoal_tac "dist a b \<le> dist (X (max M N)) a + dist (X (max M N)) b")
+apply (erule le_less_trans, rule add_strict_mono, simp, simp)
+apply (subst dist_commute, rule dist_triangle)
+done
 
 lemma (in bounded_linear) LIMSEQ:
   "X ----> a \<Longrightarrow> (\<lambda>n. f (X n)) ----> f a"
-by (simp only: LIMSEQ_Zseq_iff diff [symmetric] Zseq)
+unfolding LIMSEQ_conv_tendsto by (rule tendsto)
 
 lemma (in bounded_bilinear) LIMSEQ:
   "\<lbrakk>X ----> a; Y ----> b\<rbrakk> \<Longrightarrow> (\<lambda>n. X n ** Y n) ----> a ** b"
-by (simp only: LIMSEQ_Zseq_iff prod_diff_prod
-               Zseq_add Zseq Zseq_left Zseq_right)
+unfolding LIMSEQ_conv_tendsto by (rule tendsto)
 
 lemma LIMSEQ_mult:
   fixes a b :: "'a::real_normed_algebra"
@@ -492,6 +452,7 @@
 by (induct m) (simp_all add: LIMSEQ_const LIMSEQ_mult)
 
 lemma LIMSEQ_setsum:
+  fixes L :: "'a \<Rightarrow> 'b::real_normed_vector"
   assumes n: "\<And>n. n \<in> S \<Longrightarrow> X n ----> L n"
   shows "(\<lambda>m. \<Sum>n\<in>S. X n m) ----> (\<Sum>n\<in>S. L n)"
 proof (cases "finite S")
@@ -534,39 +495,40 @@
     by (simp add: setprod_def LIMSEQ_const)
 qed
 
-lemma LIMSEQ_add_const: "f ----> a ==> (%n.(f n + b)) ----> a + b"
+lemma LIMSEQ_add_const:
+  fixes a :: "'a::real_normed_vector"
+  shows "f ----> a ==> (%n.(f n + b)) ----> a + b"
 by (simp add: LIMSEQ_add LIMSEQ_const)
 
 (* FIXME: delete *)
 lemma LIMSEQ_add_minus:
-     "[| X ----> a; Y ----> b |] ==> (%n. X n + -Y n) ----> a + -b"
+  fixes a b :: "'a::real_normed_vector"
+  shows "[| X ----> a; Y ----> b |] ==> (%n. X n + -Y n) ----> a + -b"
 by (simp only: LIMSEQ_add LIMSEQ_minus)
 
-lemma LIMSEQ_diff_const: "f ----> a ==> (%n.(f n  - b)) ----> a - b"
+lemma LIMSEQ_diff_const:
+  fixes a b :: "'a::real_normed_vector"
+  shows "f ----> a ==> (%n.(f n  - b)) ----> a - b"
 by (simp add: LIMSEQ_diff LIMSEQ_const)
 
-lemma LIMSEQ_diff_approach_zero: 
-  "g ----> L ==> (%x. f x - g x) ----> 0  ==>
-     f ----> L"
-  apply (drule LIMSEQ_add)
-  apply assumption
-  apply simp
-done
+lemma LIMSEQ_diff_approach_zero:
+  fixes L :: "'a::real_normed_vector"
+  shows "g ----> L ==> (%x. f x - g x) ----> 0 ==> f ----> L"
+by (drule (1) LIMSEQ_add, simp)
 
-lemma LIMSEQ_diff_approach_zero2: 
-  "f ----> L ==> (%x. f x - g x) ----> 0  ==>
-     g ----> L";
-  apply (drule LIMSEQ_diff)
-  apply assumption
-  apply simp
-done
+lemma LIMSEQ_diff_approach_zero2:
+  fixes L :: "'a::real_normed_vector"
+  shows "f ----> L ==> (%x. f x - g x) ----> 0 ==> g ----> L";
+by (drule (1) LIMSEQ_diff, simp)
 
 text{*A sequence tends to zero iff its abs does*}
-lemma LIMSEQ_norm_zero: "((\<lambda>n. norm (X n)) ----> 0) = (X ----> 0)"
-by (simp add: LIMSEQ_def)
+lemma LIMSEQ_norm_zero:
+  fixes X :: "nat \<Rightarrow> 'a::real_normed_vector"
+  shows "((\<lambda>n. norm (X n)) ----> 0) \<longleftrightarrow> (X ----> 0)"
+by (simp add: LIMSEQ_iff)
 
 lemma LIMSEQ_rabs_zero: "((%n. \<bar>f n\<bar>) ----> 0) = (f ----> (0::real))"
-by (simp add: LIMSEQ_def)
+by (simp add: LIMSEQ_iff)
 
 lemma LIMSEQ_imp_rabs: "f ----> (l::real) ==> (%n. \<bar>f n\<bar>) ----> \<bar>l\<bar>"
 by (drule LIMSEQ_norm, simp)
@@ -653,7 +615,9 @@
 lemma convergent_LIMSEQ_iff: "convergent X = (X ----> lim X)"
 by (auto intro: theI LIMSEQ_unique simp add: convergent_def lim_def)
 
-lemma convergent_minus_iff: "(convergent X) = (convergent (%n. -(X n)))"
+lemma convergent_minus_iff:
+  fixes X :: "nat \<Rightarrow> 'a::real_normed_vector"
+  shows "convergent X \<longleftrightarrow> convergent (\<lambda>n. - X n)"
 apply (simp add: convergent_def)
 apply (auto dest: LIMSEQ_minus)
 apply (drule LIMSEQ_minus, auto)
@@ -1119,20 +1083,35 @@
 
 subsection {* Cauchy Sequences *}
 
-lemma CauchyI:
-  "(\<And>e. 0 < e \<Longrightarrow> \<exists>M. \<forall>m\<ge>M. \<forall>n\<ge>M. norm (X m - X n) < e) \<Longrightarrow> Cauchy X"
+lemma metric_CauchyI:
+  "(\<And>e. 0 < e \<Longrightarrow> \<exists>M. \<forall>m\<ge>M. \<forall>n\<ge>M. dist (X m) (X n) < e) \<Longrightarrow> Cauchy X"
+by (simp add: Cauchy_def)
+
+lemma metric_CauchyD:
+  "\<lbrakk>Cauchy X; 0 < e\<rbrakk> \<Longrightarrow> \<exists>M. \<forall>m\<ge>M. \<forall>n\<ge>M. dist (X m) (X n) < e"
 by (simp add: Cauchy_def)
 
+lemma Cauchy_iff:
+  fixes X :: "nat \<Rightarrow> 'a::real_normed_vector"
+  shows "Cauchy X \<longleftrightarrow> (\<forall>e>0. \<exists>M. \<forall>m\<ge>M. \<forall>n\<ge>M. norm (X m - X n) < e)"
+unfolding Cauchy_def dist_norm ..
+
+lemma CauchyI:
+  fixes X :: "nat \<Rightarrow> 'a::real_normed_vector"
+  shows "(\<And>e. 0 < e \<Longrightarrow> \<exists>M. \<forall>m\<ge>M. \<forall>n\<ge>M. norm (X m - X n) < e) \<Longrightarrow> Cauchy X"
+by (simp add: Cauchy_iff)
+
 lemma CauchyD:
-  "\<lbrakk>Cauchy X; 0 < e\<rbrakk> \<Longrightarrow> \<exists>M. \<forall>m\<ge>M. \<forall>n\<ge>M. norm (X m - X n) < e"
-by (simp add: Cauchy_def)
+  fixes X :: "nat \<Rightarrow> 'a::real_normed_vector"
+  shows "\<lbrakk>Cauchy X; 0 < e\<rbrakk> \<Longrightarrow> \<exists>M. \<forall>m\<ge>M. \<forall>n\<ge>M. norm (X m - X n) < e"
+by (simp add: Cauchy_iff)
 
 lemma Cauchy_subseq_Cauchy:
   "\<lbrakk> Cauchy X; subseq f \<rbrakk> \<Longrightarrow> Cauchy (X o f)"
-apply (auto simp add: Cauchy_def) 
-apply (drule_tac x=e in spec, clarify)  
-apply (rule_tac x=M in exI, clarify) 
-apply (blast intro: seq_suble le_trans dest!: spec) 
+apply (auto simp add: Cauchy_def)
+apply (drule_tac x=e in spec, clarify)
+apply (rule_tac x=M in exI, clarify)
+apply (blast intro: le_trans [OF _ seq_suble] dest!: spec)
 done
 
 subsubsection {* Cauchy Sequences are Bounded *}
@@ -1149,7 +1128,7 @@
 done
 
 lemma Cauchy_Bseq: "Cauchy X ==> Bseq X"
-apply (simp add: Cauchy_def)
+apply (simp add: Cauchy_iff)
 apply (drule spec, drule mp, rule zero_less_one, safe)
 apply (drule_tac x="M" in spec, simp)
 apply (drule lemmaCauchy)
@@ -1167,22 +1146,21 @@
 
 theorem LIMSEQ_imp_Cauchy:
   assumes X: "X ----> a" shows "Cauchy X"
-proof (rule CauchyI)
+proof (rule metric_CauchyI)
   fix e::real assume "0 < e"
   hence "0 < e/2" by simp
-  with X have "\<exists>N. \<forall>n\<ge>N. norm (X n - a) < e/2" by (rule LIMSEQ_D)
-  then obtain N where N: "\<forall>n\<ge>N. norm (X n - a) < e/2" ..
-  show "\<exists>N. \<forall>m\<ge>N. \<forall>n\<ge>N. norm (X m - X n) < e"
+  with X have "\<exists>N. \<forall>n\<ge>N. dist (X n) a < e/2" by (rule metric_LIMSEQ_D)
+  then obtain N where N: "\<forall>n\<ge>N. dist (X n) a < e/2" ..
+  show "\<exists>N. \<forall>m\<ge>N. \<forall>n\<ge>N. dist (X m) (X n) < e"
   proof (intro exI allI impI)
     fix m assume "N \<le> m"
-    hence m: "norm (X m - a) < e/2" using N by fast
+    hence m: "dist (X m) a < e/2" using N by fast
     fix n assume "N \<le> n"
-    hence n: "norm (X n - a) < e/2" using N by fast
-    have "norm (X m - X n) = norm ((X m - a) - (X n - a))" by simp
-    also have "\<dots> \<le> norm (X m - a) + norm (X n - a)"
-      by (rule norm_triangle_ineq4)
-    also from m n have "\<dots> < e" by(simp add:field_simps)
-    finally show "norm (X m - X n) < e" .
+    hence n: "dist (X n) a < e/2" using N by fast
+    have "dist (X m) (X n) \<le> dist (X m) a + dist (X n) a"
+      by (rule dist_triangle2)
+    also from m n have "\<dots> < e" by simp
+    finally show "dist (X m) (X n) < e" .
   qed
 qed
 
@@ -1311,7 +1289,7 @@
 lemma convergent_subseq_convergent:
   fixes X :: "nat \<Rightarrow> 'a::banach"
   shows "\<lbrakk> convergent X; subseq f \<rbrakk> \<Longrightarrow> convergent (X o f)"
-  by (simp add: Cauchy_subseq_Cauchy Cauchy_convergent_iff [symmetric]) 
+  by (simp add: Cauchy_subseq_Cauchy Cauchy_convergent_iff [symmetric])
 
 
 subsection {* Power Sequences *}
--- a/src/HOL/Series.thy	Mon Jun 01 09:26:28 2009 +0200
+++ b/src/HOL/Series.thy	Tue Jun 02 12:18:08 2009 +0200
@@ -160,7 +160,7 @@
 
 lemma series_zero: 
      "(\<forall>m. n \<le> m --> f(m) = 0) ==> f sums (setsum f {0..<n})"
-apply (simp add: sums_def LIMSEQ_def diff_minus[symmetric], safe)
+apply (simp add: sums_def LIMSEQ_iff diff_minus[symmetric], safe)
 apply (rule_tac x = n in exI)
 apply (clarsimp simp add:setsum_diff[symmetric] cong:setsum_ivl_cong)
 done
@@ -264,7 +264,7 @@
      "[|summable f; 0 < k |] ==> (%n. setsum f {n*k..<n*k+k}) sums (suminf f)"
 apply (drule summable_sums)
 apply (simp only: sums_def sumr_group)
-apply (unfold LIMSEQ_def, safe)
+apply (unfold LIMSEQ_iff, safe)
 apply (drule_tac x="r" in spec, safe)
 apply (rule_tac x="no" in exI, safe)
 apply (drule_tac x="n*k" in spec)
@@ -361,7 +361,7 @@
 lemma summable_LIMSEQ_zero: "summable f \<Longrightarrow> f ----> 0"
 apply (drule summable_convergent_sumr_iff [THEN iffD1])
 apply (drule convergent_Cauchy)
-apply (simp only: Cauchy_def LIMSEQ_def, safe)
+apply (simp only: Cauchy_iff LIMSEQ_iff, safe)
 apply (drule_tac x="r" in spec, safe)
 apply (rule_tac x="M" in exI, safe)
 apply (drule_tac x="Suc n" in spec, simp)
@@ -371,7 +371,7 @@
 lemma summable_Cauchy:
      "summable (f::nat \<Rightarrow> 'a::banach) =  
       (\<forall>e > 0. \<exists>N. \<forall>m \<ge> N. \<forall>n. norm (setsum f {m..<n}) < e)"
-apply (simp only: summable_convergent_sumr_iff Cauchy_convergent_iff [symmetric] Cauchy_def, safe)
+apply (simp only: summable_convergent_sumr_iff Cauchy_convergent_iff [symmetric] Cauchy_iff, safe)
 apply (drule spec, drule (1) mp)
 apply (erule exE, rule_tac x="M" in exI, clarify)
 apply (rule_tac x="m" and y="n" in linorder_le_cases)
--- a/src/HOL/Tools/function_package/scnp_reconstruct.ML	Mon Jun 01 09:26:28 2009 +0200
+++ b/src/HOL/Tools/function_package/scnp_reconstruct.ML	Tue Jun 02 12:18:08 2009 +0200
@@ -416,14 +416,14 @@
 (* Method setup *)
 
 val orders =
-  (Scan.repeat1
+  Scan.repeat1
     ((Args.$$$ "max" >> K MAX) ||
      (Args.$$$ "min" >> K MIN) ||
      (Args.$$$ "ms" >> K MS))
-  || Scan.succeed [MAX, MS, MIN])
+  || Scan.succeed [MAX, MS, MIN]
 
-val setup = Method.add_method
-  ("sizechange", Method.sectioned_args (Scan.lift orders) clasimp_modifiers decomp_scnp,
-   "termination prover with graph decomposition and the NP subset of size change termination")
+val setup = Method.setup @{binding sizechange}
+  (Scan.lift orders --| Method.sections clasimp_modifiers >> decomp_scnp)
+  "termination prover with graph decomposition and the NP subset of size change termination"
 
 end
--- a/src/HOL/Tools/primrec_package.ML	Mon Jun 01 09:26:28 2009 +0200
+++ b/src/HOL/Tools/primrec_package.ML	Tue Jun 02 12:18:08 2009 +0200
@@ -16,6 +16,8 @@
   val add_primrec_overloaded: (string * (string * typ) * bool) list ->
     (binding * typ option * mixfix) list ->
     (Attrib.binding * term) list -> theory -> thm list * theory
+  val add_primrec_simple: ((binding * typ) * mixfix) list -> term list ->
+    local_theory -> (string * thm list list) * local_theory
 end;
 
 structure PrimrecPackage : PRIMREC_PACKAGE =
@@ -211,22 +213,12 @@
             else find_dts dt_info tnames' tnames);
 
 
-(* primrec definition *)
+(* distill primitive definition(s) from primrec specification *)
 
-local
-
-fun prove_spec ctxt names rec_rewrites defs eqs =
+fun distill lthy fixes eqs = 
   let
-    val rewrites = map mk_meta_eq rec_rewrites @ map (snd o snd) defs;
-    fun tac _ = EVERY [rewrite_goals_tac rewrites, rtac refl 1];
-    val _ = message ("Proving equations for primrec function(s) " ^ commas_quote names);
-  in map (fn (a, t) => (a, [Goal.prove ctxt [] [] t tac])) eqs end;
-
-fun gen_primrec set_group prep_spec raw_fixes raw_spec lthy =
-  let
-    val (fixes, spec) = fst (prep_spec raw_fixes raw_spec lthy);
     val eqns = fold_rev (process_eqn (fn v => Variable.is_fixed lthy v
-      orelse exists (fn ((w, _), _) => v = Binding.name_of w) fixes) o snd) spec [];
+      orelse exists (fn ((w, _), _) => v = Binding.name_of w) fixes)) eqs [];
     val tnames = distinct (op =) (map (#1 o snd) eqns);
     val dts = find_dts (DatatypePackage.get_datatypes (ProofContext.theory_of lthy)) tnames tnames;
     val main_fns = map (fn (tname, {index, ...}) =>
@@ -236,31 +228,59 @@
         ("datatypes " ^ commas_quote tnames ^ "\nare not mutually recursive")
       else snd (hd dts);
     val (fnames, fnss) = fold_rev (process_fun descr eqns) main_fns ([], []);
-    val (fs, defs) = fold_rev (get_fns fnss) (descr ~~ rec_names) ([], []);
-    val names1 = map snd fnames;
-    val names2 = map fst eqns;
-    val _ = if gen_eq_set (op =) (names1, names2) then ()
-      else primrec_error ("functions " ^ commas_quote names2 ^
+    val (fs, raw_defs) = fold_rev (get_fns fnss) (descr ~~ rec_names) ([], []);
+    val defs = map (make_def lthy fixes fs) raw_defs;
+    val names = map snd fnames;
+    val names_eqns = map fst eqns;
+    val _ = if gen_eq_set (op =) (names, names_eqns) then ()
+      else primrec_error ("functions " ^ commas_quote names_eqns ^
         "\nare not mutually recursive");
-    val prefix = space_implode "_" (map (Long_Name.base_name o #1) defs);
-    val qualify = Binding.qualify false prefix;
-    val spec' = (map o apfst)
-      (fn (b, attrs) => (qualify b, Code.add_default_eqn_attrib :: attrs)) spec;
-    val simp_atts = map (Attrib.internal o K)
-      [Simplifier.simp_add, Nitpick_Const_Simp_Thms.add, Quickcheck_RecFun_Simp_Thms.add];
+    val rec_rewrites' = map mk_meta_eq rec_rewrites;
+    val prefix = space_implode "_" (map (Long_Name.base_name o #1) raw_defs);
+    fun prove lthy defs =
+      let
+        val rewrites = rec_rewrites' @ map (snd o snd) defs;
+        fun tac _ = EVERY [rewrite_goals_tac rewrites, rtac refl 1];
+        val _ = message ("Proving equations for primrec function(s) " ^ commas_quote names);
+      in map (fn eq => [Goal.prove lthy [] [] eq tac]) eqs end;
+  in ((prefix, (fs, defs)), prove) end
+  handle PrimrecError (msg, some_eqn) =>
+    error ("Primrec definition error:\n" ^ msg ^ (case some_eqn
+     of SOME eqn => "\nin\n" ^ quote (Syntax.string_of_term lthy eqn)
+      | NONE => ""));
+
+
+(* primrec definition *)
+
+fun add_primrec_simple fixes ts lthy =
+  let
+    val ((prefix, (fs, defs)), prove) = distill lthy fixes ts;
+  in
+    lthy
+    |> fold_map (LocalTheory.define Thm.definitionK) defs
+    |-> (fn defs => `(fn lthy => (prefix, prove lthy defs)))
+  end;
+
+local
+
+fun gen_primrec set_group prep_spec raw_fixes raw_spec lthy =
+  let
+    val (fixes, spec) = fst (prep_spec raw_fixes raw_spec lthy);
+    fun attr_bindings prefix = map (fn ((b, attrs), _) =>
+      (Binding.qualify false prefix b, Code.add_default_eqn_attrib :: attrs)) spec;
+    fun simp_attr_binding prefix = (Binding.qualify true prefix (Binding.name "simps"),
+      map (Attrib.internal o K)
+        [Simplifier.simp_add, Nitpick_Const_Simp_Thms.add, Quickcheck_RecFun_Simp_Thms.add]);
   in
     lthy
     |> set_group ? LocalTheory.set_group (serial_string ())
-    |> fold_map (LocalTheory.define Thm.definitionK o make_def lthy fixes fs) defs
-    |-> (fn defs => `(fn ctxt => prove_spec ctxt names1 rec_rewrites defs spec'))
-    |-> (fn simps => fold_map (LocalTheory.note Thm.generatedK) simps)
-    |-> (fn simps' => LocalTheory.note Thm.generatedK
-          ((qualify (Binding.qualified_name "simps"), simp_atts), maps snd simps'))
+    |> add_primrec_simple fixes (map snd spec)
+    |-> (fn (prefix, simps) => fold_map (LocalTheory.note Thm.generatedK)
+          (attr_bindings prefix ~~ simps)
+    #-> (fn simps' => LocalTheory.note Thm.generatedK
+          (simp_attr_binding prefix, maps snd simps')))
     |>> snd
-  end handle PrimrecError (msg, some_eqn) =>
-    error ("Primrec definition error:\n" ^ msg ^ (case some_eqn
-     of SOME eqn => "\nin\n" ^ quote (Syntax.string_of_term lthy eqn)
-      | NONE => ""));
+  end;
 
 in
 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/HOL/Tools/quickcheck_generators.ML	Tue Jun 02 12:18:08 2009 +0200
@@ -0,0 +1,145 @@
+(* Author: Florian Haftmann, TU Muenchen
+
+Quickcheck generators for various types.
+*)
+
+signature QUICKCHECK_GENERATORS =
+sig
+  val compile_generator_expr: theory -> term -> int -> term list option
+  type seed = Random_Engine.seed
+  val random_fun: typ -> typ -> ('a -> 'a -> bool) -> ('a -> term)
+    -> (seed -> ('b * (unit -> term)) * seed) -> (seed -> seed * seed)
+    -> seed -> (('a -> 'b) * (unit -> Term.term)) * seed
+  val ensure_random_typecopy: string -> theory -> theory
+  val eval_ref: (unit -> int -> int * int -> term list option * (int * int)) option ref
+  val setup: theory -> theory
+end;
+
+structure Quickcheck_Generators : QUICKCHECK_GENERATORS =
+struct
+
+(** building and compiling generator expressions **)
+
+val eval_ref : (unit -> int -> int * int -> term list option * (int * int)) option ref = ref NONE;
+
+val target = "Quickcheck";
+
+fun mk_generator_expr thy prop tys =
+  let
+    val bound_max = length tys - 1;
+    val bounds = map_index (fn (i, ty) =>
+      (2 * (bound_max - i) + 1, 2 * (bound_max - i), 2 * i, ty)) tys;
+    val result = list_comb (prop, map (fn (i, _, _, _) => Bound i) bounds);
+    val terms = HOLogic.mk_list @{typ term} (map (fn (_, i, _, _) => Bound i $ @{term "()"}) bounds);
+    val check = @{term "If :: bool => term list option => term list option => term list option"}
+      $ result $ @{term "None :: term list option"} $ (@{term "Some :: term list => term list option "} $ terms);
+    val return = @{term "Pair :: term list option => Random.seed => term list option * Random.seed"};
+    fun liftT T sT = sT --> HOLogic.mk_prodT (T, sT);
+    fun mk_termtyp ty = HOLogic.mk_prodT (ty, @{typ "unit => term"});
+    fun mk_scomp T1 T2 sT f g = Const (@{const_name scomp},
+      liftT T1 sT --> (T1 --> liftT T2 sT) --> liftT T2 sT) $ f $ g;
+    fun mk_split ty = Sign.mk_const thy
+      (@{const_name split}, [ty, @{typ "unit => term"}, liftT @{typ "term list option"} @{typ Random.seed}]);
+    fun mk_scomp_split ty t t' =
+      mk_scomp (mk_termtyp ty) @{typ "term list option"} @{typ Random.seed} t
+        (mk_split ty $ Abs ("", ty, Abs ("", @{typ "unit => term"}, t')));
+    fun mk_bindclause (_, _, i, ty) = mk_scomp_split ty
+      (Sign.mk_const thy (@{const_name random}, [ty]) $ Bound i);
+  in Abs ("n", @{typ code_numeral}, fold_rev mk_bindclause bounds (return $ check)) end;
+
+fun compile_generator_expr thy t =
+  let
+    val tys = (map snd o fst o strip_abs) t;
+    val t' = mk_generator_expr thy t tys;
+    val f = Code_ML.eval (SOME target) ("Quickcheck_Generators.eval_ref", eval_ref)
+      (fn proc => fn g => fn s => g s #>> (Option.map o map) proc) thy t' [];
+  in f #> Random_Engine.run end;
+
+
+(** typ "'a => 'b" **)
+
+type seed = Random_Engine.seed;
+
+fun random_fun (T1 : typ) (T2 : typ) (eq : 'a -> 'a -> bool) (term_of : 'a -> term)
+    (random : seed -> ('b * (unit -> term)) * seed)
+    (random_split : seed -> seed * seed)
+    (seed : seed) =
+  let
+    val (seed', seed'') = random_split seed;
+    val state = ref (seed', [], Const (@{const_name undefined}, T1 --> T2));
+    val fun_upd = Const (@{const_name fun_upd},
+      (T1 --> T2) --> T1 --> T2 --> T1 --> T2);
+    fun random_fun' x =
+      let
+        val (seed, fun_map, f_t) = ! state;
+      in case AList.lookup (uncurry eq) fun_map x
+       of SOME y => y
+        | NONE => let
+              val t1 = term_of x;
+              val ((y, t2), seed') = random seed;
+              val fun_map' = (x, y) :: fun_map;
+              val f_t' = fun_upd $ f_t $ t1 $ t2 ();
+              val _ = state := (seed', fun_map', f_t');
+            in y end
+      end;
+    fun term_fun' () = #3 (! state);
+  in ((random_fun', term_fun'), seed'') end;
+
+
+(** type copies **)
+
+fun mk_random_typecopy tyco vs constr typ thy =
+  let
+    val Ts = map TFree vs;  
+    val T = Type (tyco, Ts);
+    fun mk_termifyT T = HOLogic.mk_prodT (T, @{typ "unit => term"})
+    val Ttm = mk_termifyT T;
+    val typtm = mk_termifyT typ;
+    fun mk_const c Ts = Const (c, Sign.const_instance thy (c, Ts));
+    fun mk_random T = mk_const @{const_name random} [T];
+    val size = @{term "j::code_numeral"};
+    val v = "x";
+    val t_v = Free (v, typtm);
+    val t_constr = mk_const constr Ts;
+    val lhs = mk_random T $ size;
+    val rhs = HOLogic.mk_ST [(((mk_random typ) $ size, @{typ Random.seed}), SOME (v, typtm))]
+      (HOLogic.mk_return Ttm @{typ Random.seed}
+      (mk_const "Code_Eval.valapp" [typ, T]
+        $ HOLogic.mk_prod (t_constr, Abs ("u", @{typ unit}, HOLogic.reflect_term t_constr)) $ t_v))
+      @{typ Random.seed} (SOME Ttm, @{typ Random.seed});
+    val eq = HOLogic.mk_Trueprop (HOLogic.mk_eq (lhs, rhs));
+  in   
+    thy
+    |> TheoryTarget.instantiation ([tyco], vs, @{sort random})
+    |> `(fn lthy => Syntax.check_term lthy eq)
+    |-> (fn eq => Specification.definition (NONE, (Attrib.empty_binding, eq)))
+    |> snd
+    |> Class.prove_instantiation_exit (K (Class.intro_classes_tac []))
+  end;
+
+fun ensure_random_typecopy tyco thy =
+  let
+    val SOME { vs = raw_vs, constr, typ = raw_typ, ... } =
+      TypecopyPackage.get_info thy tyco;
+    val constrain = curry (Sorts.inter_sort (Sign.classes_of thy));
+    val typ = map_atyps (fn TFree (v, sort) =>
+      TFree (v, constrain sort @{sort random})) raw_typ;
+    val vs' = Term.add_tfreesT typ [];
+    val vs = map (fn (v, sort) =>
+      (v, the_default (constrain sort @{sort typerep}) (AList.lookup (op =) vs' v))) raw_vs;
+    val do_inst = Sign.of_sort thy (typ, @{sort random});
+  in if do_inst then mk_random_typecopy tyco vs constr typ thy else thy end;
+
+
+(** datatypes **)
+
+(* still under construction *)
+
+
+(** setup **)
+
+val setup = Code_Target.extend_target (target, (Code_ML.target_Eval, K I))
+  #> Quickcheck.add_generator ("code", compile_generator_expr o ProofContext.theory_of)
+  #> TypecopyPackage.interpretation ensure_random_typecopy;
+
+end;
--- a/src/HOL/Tools/recdef_package.ML	Mon Jun 01 09:26:28 2009 +0200
+++ b/src/HOL/Tools/recdef_package.ML	Tue Jun 02 12:18:08 2009 +0200
@@ -170,7 +170,7 @@
     val ctxt =
       (case opt_src of
         NONE => ctxt0
-      | SOME src => Method.only_sectioned_args recdef_modifiers I src ctxt0);
+      | SOME src => #2 (Method.syntax (Method.sections recdef_modifiers) src ctxt0));
     val {simps, congs, wfs} = get_hints ctxt;
     val cs = local_claset_of ctxt;
     val ss = local_simpset_of ctxt addsimps simps;
--- a/src/HOL/Transcendental.thy	Mon Jun 01 09:26:28 2009 +0200
+++ b/src/HOL/Transcendental.thy	Tue Jun 02 12:18:08 2009 +0200
@@ -438,7 +438,7 @@
   assumes k: "0 < (k::real)"
   assumes le: "\<And>h. \<lbrakk>h \<noteq> 0; norm h < k\<rbrakk> \<Longrightarrow> norm (f h) \<le> K * norm h"
   shows "f -- 0 --> 0"
-unfolding LIM_def diff_0_right
+unfolding LIM_eq diff_0_right
 proof (safe)
   let ?h = "of_real (k / 2)::'a"
   have "?h \<noteq> 0" and "norm ?h < k" using k by simp_all
@@ -1252,30 +1252,31 @@
 subsection {* Sine and Cosine *}
 
 definition
+  sin_coeff :: "nat \<Rightarrow> real" where
+  "sin_coeff = (\<lambda>n. if even n then 0 else -1 ^ ((n - Suc 0) div 2) / real (fact n))"
+
+definition
+  cos_coeff :: "nat \<Rightarrow> real" where
+  "cos_coeff = (\<lambda>n. if even n then (-1 ^ (n div 2)) / real (fact n) else 0)"
+
+definition
   sin :: "real => real" where
-  "sin x = (\<Sum>n. (if even(n) then 0 else
-             (-1 ^ ((n - Suc 0) div 2))/(real (fact n))) * x ^ n)"
- 
+  "sin x = (\<Sum>n. sin_coeff n * x ^ n)"
+
 definition
   cos :: "real => real" where
-  "cos x = (\<Sum>n. (if even(n) then (-1 ^ (n div 2))/(real (fact n)) 
-                            else 0) * x ^ n)"
-
-lemma summable_sin: 
-     "summable (%n.  
-           (if even n then 0  
-           else -1 ^ ((n - Suc 0) div 2)/(real (fact n))) *  
-                x ^ n)"
+  "cos x = (\<Sum>n. cos_coeff n * x ^ n)"
+
+lemma summable_sin: "summable (\<lambda>n. sin_coeff n * x ^ n)"
+unfolding sin_coeff_def
 apply (rule_tac g = "(%n. inverse (real (fact n)) * \<bar>x\<bar> ^ n)" in summable_comparison_test)
 apply (rule_tac [2] summable_exp)
 apply (rule_tac x = 0 in exI)
 apply (auto simp add: divide_inverse abs_mult power_abs [symmetric] zero_le_mult_iff)
 done
 
-lemma summable_cos: 
-      "summable (%n.  
-           (if even n then  
-           -1 ^ (n div 2)/(real (fact n)) else 0) * x ^ n)"
+lemma summable_cos: "summable (\<lambda>n. cos_coeff n * x ^ n)"
+unfolding cos_coeff_def
 apply (rule_tac g = "(%n. inverse (real (fact n)) * \<bar>x\<bar> ^ n)" in summable_comparison_test)
 apply (rule_tac [2] summable_exp)
 apply (rule_tac x = 0 in exI)
@@ -1304,71 +1305,39 @@
 apply (case_tac [2] "n", auto)
 done
 
-lemma sin_converges: 
-      "(%n. (if even n then 0  
-            else -1 ^ ((n - Suc 0) div 2)/(real (fact n))) *  
-                 x ^ n) sums sin(x)"
+lemma sin_converges: "(\<lambda>n. sin_coeff n * x ^ n) sums sin(x)"
 unfolding sin_def by (rule summable_sin [THEN summable_sums])
 
-lemma cos_converges: 
-      "(%n. (if even n then  
-           -1 ^ (n div 2)/(real (fact n))  
-           else 0) * x ^ n) sums cos(x)"
+lemma cos_converges: "(\<lambda>n. cos_coeff n * x ^ n) sums cos(x)"
 unfolding cos_def by (rule summable_cos [THEN summable_sums])
 
-lemma sin_fdiffs: 
-      "diffs(%n. if even n then 0  
-           else -1 ^ ((n - Suc 0) div 2)/(real (fact n)))  
-       = (%n. if even n then  
-                 -1 ^ (n div 2)/(real (fact n))  
-              else 0)"
+lemma sin_fdiffs: "diffs sin_coeff = cos_coeff"
+unfolding sin_coeff_def cos_coeff_def
 by (auto intro!: ext 
          simp add: diffs_def divide_inverse real_of_nat_def of_nat_mult
          simp del: mult_Suc of_nat_Suc)
 
-lemma sin_fdiffs2: 
-       "diffs(%n. if even n then 0  
-           else -1 ^ ((n - Suc 0) div 2)/(real (fact n))) n  
-       = (if even n then  
-                 -1 ^ (n div 2)/(real (fact n))  
-              else 0)"
+lemma sin_fdiffs2: "diffs sin_coeff n = cos_coeff n"
 by (simp only: sin_fdiffs)
 
-lemma cos_fdiffs: 
-      "diffs(%n. if even n then  
-                 -1 ^ (n div 2)/(real (fact n)) else 0)  
-       = (%n. - (if even n then 0  
-           else -1 ^ ((n - Suc 0)div 2)/(real (fact n))))"
+lemma cos_fdiffs: "diffs cos_coeff = (\<lambda>n. - sin_coeff n)"
+unfolding sin_coeff_def cos_coeff_def
 by (auto intro!: ext 
          simp add: diffs_def divide_inverse odd_Suc_mult_two_ex real_of_nat_def of_nat_mult
          simp del: mult_Suc of_nat_Suc)
 
-
-lemma cos_fdiffs2: 
-      "diffs(%n. if even n then  
-                 -1 ^ (n div 2)/(real (fact n)) else 0) n 
-       = - (if even n then 0  
-           else -1 ^ ((n - Suc 0)div 2)/(real (fact n)))"
+lemma cos_fdiffs2: "diffs cos_coeff n = - sin_coeff n"
 by (simp only: cos_fdiffs)
 
 text{*Now at last we can get the derivatives of exp, sin and cos*}
 
-lemma lemma_sin_minus:
-     "- sin x = (\<Sum>n. - ((if even n then 0 
-                  else -1 ^ ((n - Suc 0) div 2)/(real (fact n))) * x ^ n))"
+lemma lemma_sin_minus: "- sin x = (\<Sum>n. - (sin_coeff n * x ^ n))"
 by (auto intro!: sums_unique sums_minus sin_converges)
 
-lemma lemma_sin_ext:
-     "sin = (%x. \<Sum>n. 
-                   (if even n then 0  
-                       else -1 ^ ((n - Suc 0) div 2)/(real (fact n))) *  
-                   x ^ n)"
+lemma lemma_sin_ext: "sin = (\<lambda>x. \<Sum>n. sin_coeff n * x ^ n)"
 by (auto intro!: ext simp add: sin_def)
 
-lemma lemma_cos_ext:
-     "cos = (%x. \<Sum>n. 
-                   (if even n then -1 ^ (n div 2)/(real (fact n)) else 0) *
-                   x ^ n)"
+lemma lemma_cos_ext: "cos = (\<lambda>x. \<Sum>n. cos_coeff n * x ^ n)"
 by (auto intro!: ext simp add: cos_def)
 
 lemma DERIV_sin [simp]: "DERIV sin x :> cos(x)"
@@ -1396,10 +1365,10 @@
 subsection {* Properties of Sine and Cosine *}
 
 lemma sin_zero [simp]: "sin 0 = 0"
-unfolding sin_def by (simp add: powser_zero)
+unfolding sin_def sin_coeff_def by (simp add: powser_zero)
 
 lemma cos_zero [simp]: "cos 0 = 1"
-unfolding cos_def by (simp add: powser_zero)
+unfolding cos_def cos_coeff_def by (simp add: powser_zero)
 
 lemma DERIV_sin_sin_mult [simp]:
      "DERIV (%x. sin(x)*sin(x)) x :> cos(x) * sin(x) + cos(x) * sin(x)"
@@ -1632,14 +1601,10 @@
      "(%n. -1 ^ n /(real (fact (2 * n + 1))) * x ^ (2 * n + 1)) 
       sums  sin x"
 proof -
-  have "(\<lambda>n. \<Sum>k = n * 2..<n * 2 + 2.
-            (if even k then 0
-             else -1 ^ ((k - Suc 0) div 2) / real (fact k)) *
-            x ^ k) 
-	sums sin x"
+  have "(\<lambda>n. \<Sum>k = n * 2..<n * 2 + 2. sin_coeff k * x ^ k) sums sin x"
     unfolding sin_def
     by (rule sin_converges [THEN sums_summable, THEN sums_group], simp) 
-  thus ?thesis unfolding One_nat_def by (simp add: mult_ac)
+  thus ?thesis unfolding One_nat_def sin_coeff_def by (simp add: mult_ac)
 qed
 
 text {* FIXME: This is a long, ugly proof! *}
@@ -1702,13 +1667,10 @@
 lemma cos_paired:
      "(%n. -1 ^ n /(real (fact (2 * n))) * x ^ (2 * n)) sums cos x"
 proof -
-  have "(\<lambda>n. \<Sum>k = n * 2..<n * 2 + 2.
-            (if even k then -1 ^ (k div 2) / real (fact k) else 0) *
-            x ^ k) 
-        sums cos x"
+  have "(\<lambda>n. \<Sum>k = n * 2..<n * 2 + 2. cos_coeff k * x ^ k) sums cos x"
     unfolding cos_def
     by (rule cos_converges [THEN sums_summable, THEN sums_group], simp) 
-  thus ?thesis by (simp add: mult_ac)
+  thus ?thesis unfolding cos_coeff_def by (simp add: mult_ac)
 qed
 
 lemma fact_lemma: "real (n::nat) * 4 = real (4 * n)"
@@ -2183,7 +2145,7 @@
 
 lemma lemma_tan_total: "0 < y ==> \<exists>x. 0 < x & x < pi/2 & y < tan x"
 apply (cut_tac LIM_cos_div_sin)
-apply (simp only: LIM_def)
+apply (simp only: LIM_eq)
 apply (drule_tac x = "inverse y" in spec, safe, force)
 apply (drule_tac ?d1.0 = s in pi_half_gt_zero [THEN [2] real_lbound_gt_zero], safe)
 apply (rule_tac x = "(pi/2) - e" in exI)
--- a/src/HOL/Transitive_Closure.thy	Mon Jun 01 09:26:28 2009 +0200
+++ b/src/HOL/Transitive_Closure.thy	Tue Jun 02 12:18:08 2009 +0200
@@ -698,6 +698,9 @@
   apply (cut_tac n=nat and R=R in rel_pow_Suc_D2', simp, blast)
   done
 
+lemma rel_pow_add: "R ^^ (m+n) = R^^n O R^^m"
+by(induct n) auto
+
 lemma rtrancl_imp_UN_rel_pow:
   assumes "p \<in> R^*"
   shows "p \<in> (\<Union>n. R ^^ n)"
--- a/src/HOL/ex/Formal_Power_Series_Examples.thy	Mon Jun 01 09:26:28 2009 +0200
+++ b/src/HOL/ex/Formal_Power_Series_Examples.thy	Tue Jun 02 12:18:08 2009 +0200
@@ -11,7 +11,7 @@
 
 section{* The generalized binomial theorem *}
 lemma gbinomial_theorem: 
-  "((a::'a::{ring_char_0, field, division_by_zero})+b) ^ n = (\<Sum>k=0..n. of_nat (n choose k) * a^k * b^(n-k))"
+  "((a::'a::{field_char_0, division_by_zero})+b) ^ n = (\<Sum>k=0..n. of_nat (n choose k) * a^k * b^(n-k))"
 proof-
   from E_add_mult[of a b] 
   have "(E (a + b)) $ n = (E a * E b)$n" by simp
@@ -38,7 +38,7 @@
   by (simp add: fps_binomial_def)
 
 lemma fps_binomial_ODE_unique:
-  fixes c :: "'a::{field, ring_char_0}"
+  fixes c :: "'a::field_char_0"
   shows "fps_deriv a = (fps_const c * a) / (1 + X) \<longleftrightarrow> a = fps_const (a$0) * fps_binomial c"
   (is "?lhs \<longleftrightarrow> ?rhs")
 proof-
@@ -302,4 +302,4 @@
   finally show ?thesis .
 qed
 
-end
\ No newline at end of file
+end
--- a/src/HOL/ex/predicate_compile.ML	Mon Jun 01 09:26:28 2009 +0200
+++ b/src/HOL/ex/predicate_compile.ML	Tue Jun 02 12:18:08 2009 +0200
@@ -31,6 +31,8 @@
 
 (* debug stuff *)
 
+fun makestring _ = "?";   (* FIXME dummy *)
+
 fun tracing s = (if ! Toplevel.debug then Output.tracing s else ());
 
 fun print_tac s = (if ! Toplevel.debug then Tactical.print_tac s else Seq.single);
@@ -965,6 +967,7 @@
   | select_sup _ 1 = [rtac @{thm supI1}]
   | select_sup n i = (rtac @{thm supI2})::(select_sup (n - 1) (i - 1));
 
+(* FIXME: This function relies on the derivation of an induction rule *)
 fun get_nparams thy s = let
     val _ = tracing ("get_nparams: " ^ s)
   in
--- a/src/HOLCF/Tools/domain/domain_axioms.ML	Mon Jun 01 09:26:28 2009 +0200
+++ b/src/HOLCF/Tools/domain/domain_axioms.ML	Tue Jun 02 12:18:08 2009 +0200
@@ -6,14 +6,14 @@
 
 signature DOMAIN_AXIOMS =
 sig
-    val copy_of_dtyp : (int -> term) -> DatatypeAux.dtyp -> term
+  val copy_of_dtyp : (int -> term) -> DatatypeAux.dtyp -> term
 
-    val calc_axioms :
-        string -> Domain_Library.eq list -> int -> Domain_Library.eq ->
-        string * (string * term) list * (string * term) list
+  val calc_axioms :
+      string -> Domain_Library.eq list -> int -> Domain_Library.eq ->
+      string * (string * term) list * (string * term) list
 
-    val add_axioms :
-        bstring -> Domain_Library.eq list -> theory -> theory
+  val add_axioms :
+      bstring -> Domain_Library.eq list -> theory -> theory
 end;
 
 
@@ -39,101 +39,107 @@
   | copy r (DatatypeAux.DtTFree a) = ID
   | copy r (DatatypeAux.DtType (c, ds)) =
     case Symtab.lookup copy_tab c of
-        SOME f => list_ccomb (%%:f, map (copy_of_dtyp r) ds)
-      | NONE => (warning ("copy_of_dtyp: unknown type constructor " ^ c); ID);
+      SOME f => list_ccomb (%%:f, map (copy_of_dtyp r) ds)
+    | NONE => (warning ("copy_of_dtyp: unknown type constructor " ^ c); ID);
 
 fun calc_axioms
-        (comp_dname : string)
-        (eqs : eq list)
-        (n : int)
-        (eqn as ((dname,_),cons) : eq)
+      (comp_dname : string)
+      (eqs : eq list)
+      (n : int)
+      (eqn as ((dname,_),cons) : eq)
     : string * (string * term) list * (string * term) list =
     let
 
-        (* ----- axioms and definitions concerning the isomorphism ------------------ *)
+      (* ----- axioms and definitions concerning the isomorphism ------------------ *)
 
-        val dc_abs = %%:(dname^"_abs");
-        val dc_rep = %%:(dname^"_rep");
-        val x_name'= "x";
-        val x_name = idx_name eqs x_name' (n+1);
-        val dnam = Long_Name.base_name dname;
+      val dc_abs = %%:(dname^"_abs");
+      val dc_rep = %%:(dname^"_rep");
+      val x_name'= "x";
+      val x_name = idx_name eqs x_name' (n+1);
+      val dnam = Long_Name.base_name dname;
 
-        val abs_iso_ax = ("abs_iso", mk_trp(dc_rep`(dc_abs`%x_name') === %:x_name'));
-        val rep_iso_ax = ("rep_iso", mk_trp(dc_abs`(dc_rep`%x_name') === %:x_name'));
+      val abs_iso_ax = ("abs_iso", mk_trp(dc_rep`(dc_abs`%x_name') === %:x_name'));
+      val rep_iso_ax = ("rep_iso", mk_trp(dc_abs`(dc_rep`%x_name') === %:x_name'));
 
-        val when_def = ("when_def",%%:(dname^"_when") == 
-                                  List.foldr (uncurry /\ ) (/\x_name'((when_body cons (fn (x,y) =>
-				                                                          Bound(1+length cons+x-y)))`(dc_rep`Bound 0))) (when_funs cons));
-            
-        val copy_def =
+      val when_def = ("when_def",%%:(dname^"_when") == 
+                                List.foldr (uncurry /\ ) (/\x_name'((when_body cons (fn (x,y) =>
+                                                                                        Bound(1+length cons+x-y)))`(dc_rep`Bound 0))) (when_funs cons));
+          
+      val copy_def =
           let fun r i = cproj (Bound 0) eqs i;
           in ("copy_def", %%:(dname^"_copy") ==
                           /\ "f" (dc_abs oo (copy_of_dtyp r (dtyp_of_eq eqn)) oo dc_rep)) end;
 
-        (* -- definitions concerning the constructors, discriminators and selectors - *)
+      (* -- definitions concerning the constructors, discriminators and selectors - *)
 
-        fun con_def m n (_,args) = let
-            fun idxs z x arg = (if is_lazy arg then mk_up else I) (Bound(z-x));
-            fun parms vs = mk_stuple (mapn (idxs(length vs)) 1 vs);
-            fun inj y 1 _ = y
-              | inj y _ 0 = mk_sinl y
-              | inj y i j = mk_sinr (inj y (i-1) (j-1));
-        in List.foldr /\# (dc_abs`(inj (parms args) m n)) args end;
-            
-        val con_defs = mapn (fn n => fn (con,args) =>
-                                        (extern_name con ^"_def", %%:con == con_def (length cons) n (con,args))) 0 cons;
-            
-        val dis_defs = let
-	    fun ddef (con,_) = (dis_name con ^"_def",%%:(dis_name con) == 
-		                                    list_ccomb(%%:(dname^"_when"),map 
-			                                                              (fn (con',args) => (List.foldr /\#
-			   (if con'=con then TT else FF) args)) cons))
-	in map ddef cons end;
+      fun con_def m n (_,args) = let
+        fun idxs z x arg = (if is_lazy arg then mk_up else I) (Bound(z-x));
+        fun parms vs = mk_stuple (mapn (idxs(length vs)) 1 vs);
+        fun inj y 1 _ = y
+          | inj y _ 0 = mk_sinl y
+          | inj y i j = mk_sinr (inj y (i-1) (j-1));
+      in List.foldr /\# (dc_abs`(inj (parms args) m n)) args end;
+          
+      val con_defs = mapn (fn n => fn (con,args) =>
+                                      (extern_name con ^"_def", %%:con == con_def (length cons) n (con,args))) 0 cons;
+          
+      val dis_defs = let
+        fun ddef (con,_) = (dis_name con ^"_def",%%:(dis_name con) == 
+                                                list_ccomb(%%:(dname^"_when"),map 
+                                                                                (fn (con',args) => (List.foldr /\#
+      (if con'=con then TT else FF) args)) cons))
+      in map ddef cons end;
 
-        val mat_defs =
-            let
-                fun mdef (con,_) =
-                    let
-                        val k = Bound 0
-                        val x = Bound 1
-                        fun one_con (con', args') =
-	                    if con'=con then k else List.foldr /\# mk_fail args'
-                        val w = list_ccomb(%%:(dname^"_when"), map one_con cons)
-                        val rhs = /\ "x" (/\ "k" (w ` x))
-                    in (mat_name con ^"_def", %%:(mat_name con) == rhs) end
-            in map mdef cons end;
+      val mat_defs =
+          let
+            fun mdef (con,_) =
+                let
+                  val k = Bound 0
+                  val x = Bound 1
+                  fun one_con (con', args') =
+                      if con'=con then k else List.foldr /\# mk_fail args'
+                  val w = list_ccomb(%%:(dname^"_when"), map one_con cons)
+                  val rhs = /\ "x" (/\ "k" (w ` x))
+                in (mat_name con ^"_def", %%:(mat_name con) == rhs) end
+          in map mdef cons end;
 
-        val pat_defs =
-            let
-                fun pdef (con,args) =
-                    let
-                        val ps = mapn (fn n => fn _ => %:("pat" ^ string_of_int n)) 1 args;
-                        val xs = map (bound_arg args) args;
-                        val r = Bound (length args);
-                        val rhs = case args of [] => mk_return HOLogic.unit
-                                             | _ => mk_ctuple_pat ps ` mk_ctuple xs;
-                        fun one_con (con',args') = List.foldr /\# (if con'=con then rhs else mk_fail) args';
-                    in (pat_name con ^"_def", list_comb (%%:(pat_name con), ps) == 
-                                                        list_ccomb(%%:(dname^"_when"), map one_con cons))
-                    end
-            in map pdef cons end;
+      val pat_defs =
+          let
+            fun pdef (con,args) =
+                let
+                  val ps = mapn (fn n => fn _ => %:("pat" ^ string_of_int n)) 1 args;
+                  val xs = map (bound_arg args) args;
+                  val r = Bound (length args);
+                  val rhs = case args of [] => mk_return HOLogic.unit
+                                       | _ => mk_ctuple_pat ps ` mk_ctuple xs;
+                  fun one_con (con',args') = List.foldr /\# (if con'=con then rhs else mk_fail) args';
+                in (pat_name con ^"_def", list_comb (%%:(pat_name con), ps) == 
+                                                    list_ccomb(%%:(dname^"_when"), map one_con cons))
+                end
+          in map pdef cons end;
 
-        val sel_defs = let
-	    fun sdef con n arg = Option.map (fn sel => (sel^"_def",%%:sel == 
-		                                                  list_ccomb(%%:(dname^"_when"),map 
-			                                                                            (fn (con',args) => if con'<>con then UU else
-			                                                                                               List.foldr /\# (Bound (length args - n)) args) cons))) (sel_of arg);
-	in List.mapPartial I (List.concat(map (fn (con,args) => mapn (sdef con) 1 args) cons)) end;
+      val sel_defs = let
+        fun sdef con n arg = Option.map (fn sel => (sel^"_def",%%:sel == 
+                                                              list_ccomb(%%:(dname^"_when"),map 
+                                                                                              (fn (con',args) => if con'<>con then UU else
+                                                                                                                 List.foldr /\# (Bound (length args - n)) args) cons))) (sel_of arg);
+      in List.mapPartial I (List.concat(map (fn (con,args) => mapn (sdef con) 1 args) cons)) end;
 
 
-        (* ----- axiom and definitions concerning induction ------------------------- *)
+      (* ----- axiom and definitions concerning induction ------------------------- *)
 
-        val reach_ax = ("reach", mk_trp(cproj (mk_fix (%%:(comp_dname^"_copy"))) eqs n
-					      `%x_name === %:x_name));
-        val take_def = ("take_def",%%:(dname^"_take") == mk_lam("n",cproj
-	                                                                (mk_iterate (Bound 0, %%:(comp_dname^"_copy"), UU)) eqs n));
-        val finite_def = ("finite_def",%%:(dname^"_finite") == mk_lam(x_name,
-	                                                              mk_ex("n",(%%:(dname^"_take") $ Bound 0)`Bound 1 === Bound 1)));
+      val reach_ax = ("reach", mk_trp(cproj (mk_fix (%%:(comp_dname^"_copy"))) eqs n
+                                            `%x_name === %:x_name));
+      val take_def =
+          ("take_def",
+           %%:(dname^"_take") ==
+              mk_lam("n",cproj
+                           (mk_iterate (Bound 0, %%:(comp_dname^"_copy"), UU)) eqs n));
+      val finite_def =
+          ("finite_def",
+           %%:(dname^"_finite") ==
+              mk_lam(x_name,
+                     mk_ex("n",(%%:(dname^"_take") $ Bound 0)`Bound 1 === Bound 1)));
 
     in (dnam,
         [abs_iso_ax, rep_iso_ax, reach_ax],
@@ -161,64 +167,64 @@
 
 fun add_matchers (((dname,_),cons) : eq) thy =
     let
-        val con_names = map fst cons;
-        val mat_names = map mat_name con_names;
-        fun qualify n = Sign.full_name thy (Binding.name n);
-        val ms = map qualify con_names ~~ map qualify mat_names;
+      val con_names = map fst cons;
+      val mat_names = map mat_name con_names;
+      fun qualify n = Sign.full_name thy (Binding.name n);
+      val ms = map qualify con_names ~~ map qualify mat_names;
     in FixrecPackage.add_matchers ms thy end;
 
 fun add_axioms comp_dnam (eqs : eq list) thy' =
     let
-        val comp_dname = Sign.full_bname thy' comp_dnam;
-        val dnames = map (fst o fst) eqs;
-        val x_name = idx_name dnames "x"; 
-        fun copy_app dname = %%:(dname^"_copy")`Bound 0;
-        val copy_def = ("copy_def" , %%:(comp_dname^"_copy") ==
-                                     /\ "f"(mk_ctuple (map copy_app dnames)));
+      val comp_dname = Sign.full_bname thy' comp_dnam;
+      val dnames = map (fst o fst) eqs;
+      val x_name = idx_name dnames "x"; 
+      fun copy_app dname = %%:(dname^"_copy")`Bound 0;
+      val copy_def = ("copy_def" , %%:(comp_dname^"_copy") ==
+                                   /\ "f"(mk_ctuple (map copy_app dnames)));
 
-        fun one_con (con,args) = let
-            val nonrec_args = filter_out 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;
-            val allvns      = map vname allargs;
-            fun vname_arg s arg = if is_rec arg then vname arg^s else vname arg;
-            val vns1        = map (vname_arg "" ) args;
-            val vns2        = map (vname_arg "'") args;
-            val allargs_cnt = length nonrec_args + 2*recs_cnt;
-            val rec_idxs    = (recs_cnt-1) downto 0;
-            val nonlazy_idxs = map snd (filter_out (fn (arg,_) => is_lazy arg)
-				                   (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 =
-                List.foldr mk_conj
-                           (mk_conj(
-                            Bound(allargs_cnt+1)===list_ccomb(%%:con,map (bound_arg allvns) vns1),
-                            Bound(allargs_cnt+0)===list_ccomb(%%:con,map (bound_arg allvns) vns2)))
-                           (mapn rel_app 1 rec_args);
-        in List.foldr mk_ex
-                      (Library.foldr mk_conj
-                                     (map (defined o Bound) nonlazy_idxs,capps)) allvns
-        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,
-         		         foldr1 mk_disj (mk_conj(Bound 1 === UU,Bound 0 === UU)
-                                                 ::map one_con cons))));
-        val bisim_def =
-            ("bisim_def",
-             %%:(comp_dname^"_bisim")==mk_lam("R", foldr1 mk_conj (mapn one_comp 0 eqs)));
-            
-        fun add_one (thy,(dnam,axs,dfs)) =
-            thy |> Sign.add_path dnam
-                |> add_defs_infer dfs
-                |> add_axioms_infer axs
-                |> Sign.parent_path;
+      fun one_con (con,args) = let
+        val nonrec_args = filter_out 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;
+        val allvns      = map vname allargs;
+        fun vname_arg s arg = if is_rec arg then vname arg^s else vname arg;
+        val vns1        = map (vname_arg "" ) args;
+        val vns2        = map (vname_arg "'") args;
+        val allargs_cnt = length nonrec_args + 2*recs_cnt;
+        val rec_idxs    = (recs_cnt-1) downto 0;
+        val nonlazy_idxs = map snd (filter_out (fn (arg,_) => is_lazy arg)
+                                               (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 =
+            List.foldr mk_conj
+                       (mk_conj(
+                        Bound(allargs_cnt+1)===list_ccomb(%%:con,map (bound_arg allvns) vns1),
+                        Bound(allargs_cnt+0)===list_ccomb(%%:con,map (bound_arg allvns) vns2)))
+                       (mapn rel_app 1 rec_args);
+      in List.foldr mk_ex
+                    (Library.foldr mk_conj
+                                   (map (defined o Bound) nonlazy_idxs,capps)) allvns
+      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,
+                               foldr1 mk_disj (mk_conj(Bound 1 === UU,Bound 0 === UU)
+                                               ::map one_con cons))));
+      val bisim_def =
+          ("bisim_def",
+           %%:(comp_dname^"_bisim")==mk_lam("R", foldr1 mk_conj (mapn one_comp 0 eqs)));
+          
+      fun add_one (thy,(dnam,axs,dfs)) =
+          thy |> Sign.add_path dnam
+              |> add_defs_infer dfs
+              |> add_axioms_infer axs
+              |> Sign.parent_path;
 
-        val thy = Library.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 |> Sign.add_path comp_dnam  
            |> add_defs_infer (bisim_def::(if length eqs>1 then [copy_def] else []))
--- a/src/HOLCF/Tools/domain/domain_extender.ML	Mon Jun 01 09:26:28 2009 +0200
+++ b/src/HOLCF/Tools/domain/domain_extender.ML	Tue Jun 02 12:18:08 2009 +0200
@@ -7,13 +7,13 @@
 signature DOMAIN_EXTENDER =
 sig
   val add_domain_cmd: string ->
-    ((string * string option) list * binding * mixfix *
-      (binding * (bool * binding option * string) list * mixfix) list) list
-    -> theory -> theory
+                      ((string * string option) list * binding * mixfix *
+                       (binding * (bool * binding option * string) list * mixfix) list) list
+                      -> theory -> theory
   val add_domain: string ->
-    ((string * string option) list * binding * mixfix *
-      (binding * (bool * binding option * typ) list * mixfix) list) list
-    -> theory -> theory
+                  ((string * string option) list * binding * mixfix *
+                   (binding * (bool * binding option * typ) list * mixfix) list) list
+                  -> theory -> theory
 end;
 
 structure Domain_Extender :> DOMAIN_EXTENDER =
@@ -23,121 +23,128 @@
 
 (* ----- general testing and preprocessing of constructor list -------------- *)
 fun check_and_sort_domain
-  (dtnvs : (string * typ list) list)
-  (cons'' : (binding * (bool * binding option * typ) list * mixfix) list list)
-  (sg : theory)
-  : ((string * typ list) *
-      (binding * (bool * binding option * typ) list * mixfix) list) list =
-  let
-    val defaultS = Sign.defaultS sg;
-    val test_dupl_typs = (case duplicates (op =) (map fst dtnvs) of 
-	[] => false | dups => error ("Duplicate types: " ^ commas_quote dups));
-    val test_dupl_cons = (case duplicates (op =) (map (Binding.name_of o first) (List.concat cons'')) of 
-	[] => false | dups => error ("Duplicate constructors: " 
-							 ^ commas_quote dups));
-    val test_dupl_sels = (case duplicates (op =) (map Binding.name_of (List.mapPartial second
-			       (List.concat (map second (List.concat cons''))))) of
-        [] => false | dups => error("Duplicate selectors: "^commas_quote dups));
-    val test_dupl_tvars = exists(fn s=>case duplicates (op =) (map(fst o dest_TFree)s)of
-	[] => false | dups => error("Duplicate type arguments: " 
-		   ^commas_quote dups)) (map snd dtnvs);
-    (* test for free type variables, illegal sort constraints on rhs,
-	       non-pcpo-types and invalid use of recursive type;
-       replace sorts in type variables on rhs *)
-    fun analyse_equation ((dname,typevars),cons') = 
-      let
-	val tvars = map dest_TFree typevars;
-	val distinct_typevars = map TFree tvars;
-	fun rm_sorts (TFree(s,_)) = TFree(s,[])
-	|   rm_sorts (Type(s,ts)) = Type(s,remove_sorts ts)
-	|   rm_sorts (TVar(s,_))  = TVar(s,[])
-	and remove_sorts l = map rm_sorts l;
-	val indirect_ok = ["*","Cfun.->","Ssum.++","Sprod.**","Up.u"]
-	fun analyse indirect (TFree(v,s))  = (case AList.lookup (op =) tvars v of 
-		    NONE => error ("Free type variable " ^ quote v ^ " on rhs.")
-	          | SOME sort => if eq_set_string (s,defaultS) orelse
-				    eq_set_string (s,sort    )
-				 then TFree(v,sort)
-				 else error ("Inconsistent sort constraint" ^
-				             " for type variable " ^ quote v))
-        |   analyse indirect (t as Type(s,typl)) = (case AList.lookup (op =) dtnvs s of
-		NONE          => if s mem indirect_ok
-				 then Type(s,map (analyse false) typl)
-				 else Type(s,map (analyse true) typl)
-	      | SOME typevars => if indirect 
-                           then error ("Indirect recursion of type " ^ 
-				        quote (string_of_typ sg t))
-                           else if dname <> s orelse (** BUG OR FEATURE?: 
-                                mutual recursion may use different arguments **)
-				   remove_sorts typevars = remove_sorts typl 
-				then Type(s,map (analyse true) typl)
-				else error ("Direct recursion of type " ^ 
-					     quote (string_of_typ sg t) ^ 
-					    " with different arguments"))
-        |   analyse indirect (TVar _) = Imposs "extender:analyse";
-        fun check_pcpo lazy T =
-          let val ok = if lazy then cpo_type else pcpo_type
-          in if ok sg T then T else error
-            ("Constructor argument type is not of sort pcpo: " ^
-              string_of_typ sg T)
-          end;
-        fun analyse_arg (lazy, sel, T) =
-          (lazy, sel, check_pcpo lazy (analyse false T));
-        fun analyse_con (b, args, mx) = (b, map analyse_arg args, mx);
-      in ((dname,distinct_typevars), map analyse_con cons') end; 
-  in ListPair.map analyse_equation (dtnvs,cons'')
-  end; (* let *)
+      (dtnvs : (string * typ list) list)
+      (cons'' : (binding * (bool * binding option * typ) list * mixfix) list list)
+      (sg : theory)
+    : ((string * typ list) *
+       (binding * (bool * binding option * typ) list * mixfix) list) list =
+    let
+      val defaultS = Sign.defaultS sg;
+      val test_dupl_typs = (case duplicates (op =) (map fst dtnvs) of 
+                              [] => false | dups => error ("Duplicate types: " ^ commas_quote dups));
+      val test_dupl_cons =
+          (case duplicates (op =) (map (Binding.name_of o first) (List.concat cons'')) of 
+             [] => false | dups => error ("Duplicate constructors: " 
+                                          ^ commas_quote dups));
+      val test_dupl_sels =
+          (case duplicates (op =) (map Binding.name_of (List.mapPartial second
+                                                                        (List.concat (map second (List.concat cons''))))) of
+             [] => false | dups => error("Duplicate selectors: "^commas_quote dups));
+      val test_dupl_tvars =
+          exists(fn s=>case duplicates (op =) (map(fst o dest_TFree)s)of
+                         [] => false | dups => error("Duplicate type arguments: " 
+                                                     ^commas_quote dups)) (map snd dtnvs);
+      (* test for free type variables, illegal sort constraints on rhs,
+         non-pcpo-types and invalid use of recursive type;
+         replace sorts in type variables on rhs *)
+      fun analyse_equation ((dname,typevars),cons') = 
+          let
+            val tvars = map dest_TFree typevars;
+            val distinct_typevars = map TFree tvars;
+            fun rm_sorts (TFree(s,_)) = TFree(s,[])
+              | rm_sorts (Type(s,ts)) = Type(s,remove_sorts ts)
+              | rm_sorts (TVar(s,_))  = TVar(s,[])
+            and remove_sorts l = map rm_sorts l;
+            val indirect_ok = ["*","Cfun.->","Ssum.++","Sprod.**","Up.u"]
+            fun analyse indirect (TFree(v,s))  =
+                (case AList.lookup (op =) tvars v of 
+                   NONE => error ("Free type variable " ^ quote v ^ " on rhs.")
+                 | SOME sort => if eq_set_string (s,defaultS) orelse
+                                   eq_set_string (s,sort    )
+                                then TFree(v,sort)
+                                else error ("Inconsistent sort constraint" ^
+                                            " for type variable " ^ quote v))
+              | analyse indirect (t as Type(s,typl)) =
+                (case AList.lookup (op =) dtnvs s of
+                   NONE          => if s mem indirect_ok
+                                    then Type(s,map (analyse false) typl)
+                                    else Type(s,map (analyse true) typl)
+                 | SOME typevars => if indirect 
+                                    then error ("Indirect recursion of type " ^ 
+                                                quote (string_of_typ sg t))
+                                    else if dname <> s orelse
+                                            (** BUG OR FEATURE?:
+                                                mutual recursion may use different arguments **)
+                                            remove_sorts typevars = remove_sorts typl 
+                                    then Type(s,map (analyse true) typl)
+                                    else error ("Direct recursion of type " ^ 
+                                                quote (string_of_typ sg t) ^ 
+                                                " with different arguments"))
+              | analyse indirect (TVar _) = Imposs "extender:analyse";
+            fun check_pcpo lazy T =
+                let val ok = if lazy then cpo_type else pcpo_type
+                in if ok sg T then T else error
+                                            ("Constructor argument type is not of sort pcpo: " ^
+                                             string_of_typ sg T)
+                end;
+            fun analyse_arg (lazy, sel, T) =
+                (lazy, sel, check_pcpo lazy (analyse false T));
+            fun analyse_con (b, args, mx) = (b, map analyse_arg args, mx);
+          in ((dname,distinct_typevars), map analyse_con cons') end; 
+    in ListPair.map analyse_equation (dtnvs,cons'')
+    end; (* let *)
 
 (* ----- calls for building new thy and thms -------------------------------- *)
 
 fun gen_add_domain
-  (prep_typ : theory -> 'a -> typ)
-  (comp_dnam : string)
-  (eqs''' : ((string * string option) list * binding * mixfix *
-              (binding * (bool * binding option * 'a) list * mixfix) list) list)
-  (thy''' : theory) =
-  let
-    fun readS (SOME s) = Syntax.read_sort_global thy''' s
-      | readS NONE = Sign.defaultS thy''';
-    fun readTFree (a, s) = TFree (a, readS s);
+      (prep_typ : theory -> 'a -> typ)
+      (comp_dnam : string)
+      (eqs''' : ((string * string option) list * binding * mixfix *
+                 (binding * (bool * binding option * 'a) list * mixfix) list) list)
+      (thy''' : theory) =
+    let
+      fun readS (SOME s) = Syntax.read_sort_global thy''' s
+        | readS NONE = Sign.defaultS thy''';
+      fun readTFree (a, s) = TFree (a, readS s);
 
-    val dtnvs = map (fn (vs,dname:binding,mx,_) => 
-                  (dname, map readTFree vs, mx)) eqs''';
-    val cons''' = map (fn (_,_,_,cons) => cons) eqs''';
-    fun thy_type  (dname,tvars,mx) = (dname, length tvars, mx);
-    fun thy_arity (dname,tvars,mx) = (Sign.full_name thy''' dname, map (snd o dest_TFree) tvars, pcpoS);
-    val thy'' = thy''' |> Sign.add_types (map thy_type dtnvs)
-		       |> fold (AxClass.axiomatize_arity o thy_arity) dtnvs;
-    val cons'' = map (map (upd_second (map (upd_third (prep_typ thy''))))) cons''';
-    val dtnvs' = map (fn (dname,vs,mx) => (Sign.full_name thy''' dname,vs)) dtnvs;
-    val eqs' : ((string * typ list) * (binding * (bool * binding option * typ) list * mixfix) list) list = check_and_sort_domain dtnvs' cons'' thy'';
-    val thy' = thy'' |> Domain_Syntax.add_syntax comp_dnam eqs';
-    val dts  = map (Type o fst) eqs';
-    val new_dts = map (fn ((s,Ts),_) => (s, map (fst o dest_TFree) Ts)) eqs';
-    fun strip ss = Library.drop (find_index_eq "'" ss +1, ss);
-    fun typid (Type  (id,_)) =
+      val dtnvs = map (fn (vs,dname:binding,mx,_) => 
+                          (dname, map readTFree vs, mx)) eqs''';
+      val cons''' = map (fn (_,_,_,cons) => cons) eqs''';
+      fun thy_type  (dname,tvars,mx) = (dname, length tvars, mx);
+      fun thy_arity (dname,tvars,mx) = (Sign.full_name thy''' dname, map (snd o dest_TFree) tvars, pcpoS);
+      val thy'' = thy''' |> Sign.add_types (map thy_type dtnvs)
+                         |> fold (AxClass.axiomatize_arity o thy_arity) dtnvs;
+      val cons'' = map (map (upd_second (map (upd_third (prep_typ thy''))))) cons''';
+      val dtnvs' = map (fn (dname,vs,mx) => (Sign.full_name thy''' dname,vs)) dtnvs;
+      val eqs' : ((string * typ list) * (binding * (bool * binding option * typ) list * mixfix) list) list =
+          check_and_sort_domain dtnvs' cons'' thy'';
+      val thy' = thy'' |> Domain_Syntax.add_syntax comp_dnam eqs';
+      val dts  = map (Type o fst) eqs';
+      val new_dts = map (fn ((s,Ts),_) => (s, map (fst o dest_TFree) Ts)) eqs';
+      fun strip ss = Library.drop (find_index_eq "'" ss +1, ss);
+      fun typid (Type  (id,_)) =
           let val c = hd (Symbol.explode (Long_Name.base_name id))
           in if Symbol.is_letter c then c else "t" end
-      | typid (TFree (id,_)   ) = hd (strip (tl (Symbol.explode id)))
-      | typid (TVar ((id,_),_)) = hd (tl (Symbol.explode id));
-    fun one_con (con,args,mx) =
-	((Syntax.const_name mx (Binding.name_of con)),
-	 ListPair.map (fn ((lazy,sel,tp),vn) => mk_arg ((lazy,
-					DatatypeAux.dtyp_of_typ new_dts tp),
-					Option.map Binding.name_of sel,vn))
-	     (args,(mk_var_names(map (typid o third) args)))
-	 ) : cons;
-    val eqs = map (fn (dtnvs,cons') => (dtnvs, map one_con cons')) eqs' : eq list;
-    val thy = thy' |> Domain_Axioms.add_axioms comp_dnam eqs;
-    val ((rewss, take_rews), theorems_thy) = thy |> fold_map (fn eq =>
-      Domain_Theorems.theorems (eq, eqs)) eqs
-      ||>> Domain_Theorems.comp_theorems (comp_dnam, eqs);
-  in
-    theorems_thy
-    |> Sign.add_path (Long_Name.base_name comp_dnam)
-    |> (snd o (PureThy.add_thmss [((Binding.name "rews", List.concat rewss @ take_rews), [])]))
-    |> Sign.parent_path
-  end;
+        | typid (TFree (id,_)   ) = hd (strip (tl (Symbol.explode id)))
+        | typid (TVar ((id,_),_)) = hd (tl (Symbol.explode id));
+      fun one_con (con,args,mx) =
+          ((Syntax.const_name mx (Binding.name_of con)),
+           ListPair.map (fn ((lazy,sel,tp),vn) => mk_arg ((lazy,
+                                                           DatatypeAux.dtyp_of_typ new_dts tp),
+                                                          Option.map Binding.name_of sel,vn))
+                        (args,(mk_var_names(map (typid o third) args)))
+          ) : cons;
+      val eqs = map (fn (dtnvs,cons') => (dtnvs, map one_con cons')) eqs' : eq list;
+      val thy = thy' |> Domain_Axioms.add_axioms comp_dnam eqs;
+      val ((rewss, take_rews), theorems_thy) =
+          thy |> fold_map (fn eq => Domain_Theorems.theorems (eq, eqs)) eqs
+              ||>> Domain_Theorems.comp_theorems (comp_dnam, eqs);
+    in
+      theorems_thy
+        |> Sign.add_path (Long_Name.base_name comp_dnam)
+        |> (snd o (PureThy.add_thmss [((Binding.name "rews", List.concat rewss @ take_rews), [])]))
+        |> Sign.parent_path
+    end;
 
 val add_domain = gen_add_domain Sign.certify_typ;
 val add_domain_cmd = gen_add_domain Syntax.read_typ_global;
@@ -150,47 +157,47 @@
 val _ = OuterKeyword.keyword "lazy";
 
 val dest_decl : (bool * binding option * string) parser =
-  P.$$$ "(" |-- Scan.optional (P.$$$ "lazy" >> K true) false --
-    (P.binding >> SOME) -- (P.$$$ "::" |-- P.typ)  --| P.$$$ ")" >> P.triple1
-  || P.$$$ "(" |-- P.$$$ "lazy" |-- P.typ --| P.$$$ ")"
-       >> (fn t => (true,NONE,t))
-  || P.typ >> (fn t => (false,NONE,t));
+    P.$$$ "(" |-- Scan.optional (P.$$$ "lazy" >> K true) false --
+      (P.binding >> SOME) -- (P.$$$ "::" |-- P.typ)  --| P.$$$ ")" >> P.triple1
+      || P.$$$ "(" |-- P.$$$ "lazy" |-- P.typ --| P.$$$ ")"
+      >> (fn t => (true,NONE,t))
+      || P.typ >> (fn t => (false,NONE,t));
 
 val cons_decl =
-  P.binding -- Scan.repeat dest_decl -- P.opt_mixfix;
+    P.binding -- Scan.repeat dest_decl -- P.opt_mixfix;
 
 val type_var' : (string * string option) parser =
-  (P.type_ident -- Scan.option (P.$$$ "::" |-- P.!!! P.sort));
+    (P.type_ident -- Scan.option (P.$$$ "::" |-- P.!!! P.sort));
 
 val type_args' : (string * string option) list parser =
-  type_var' >> single ||
-  P.$$$ "(" |-- P.!!! (P.list1 type_var' --| P.$$$ ")") ||
-  Scan.succeed [];
+    type_var' >> single ||
+              P.$$$ "(" |-- P.!!! (P.list1 type_var' --| P.$$$ ")") ||
+              Scan.succeed [];
 
 val domain_decl =
-  (type_args' -- P.binding -- P.opt_infix) --
-  (P.$$$ "=" |-- P.enum1 "|" cons_decl);
+    (type_args' -- P.binding -- P.opt_infix) --
+                                             (P.$$$ "=" |-- P.enum1 "|" cons_decl);
 
 val domains_decl =
-  Scan.option (P.$$$ "(" |-- P.name --| P.$$$ ")") --
-  P.and_list1 domain_decl;
+    Scan.option (P.$$$ "(" |-- P.name --| P.$$$ ")") --
+                P.and_list1 domain_decl;
 
 fun mk_domain (opt_name : string option,
-  doms : ((((string * string option) list * binding) * mixfix) *
-    ((binding * (bool * binding option * string) list) * mixfix) list) list ) =
-  let
-    val names = map (fn (((_, t), _), _) => Binding.name_of t) doms;
-    val specs : ((string * string option) list * binding * mixfix *
-      (binding * (bool * binding option * string) list * mixfix) list) list =
-        map (fn (((vs, t), mx), cons) =>
-          (vs, t, mx, map (fn ((c, ds), mx) => (c, ds, mx)) cons)) doms;
-    val comp_dnam =
-      case opt_name of NONE => space_implode "_" names | SOME s => s;
-  in add_domain_cmd comp_dnam specs end;
+               doms : ((((string * string option) list * binding) * mixfix) *
+                       ((binding * (bool * binding option * string) list) * mixfix) list) list ) =
+    let
+      val names = map (fn (((_, t), _), _) => Binding.name_of t) doms;
+      val specs : ((string * string option) list * binding * mixfix *
+                   (binding * (bool * binding option * string) list * mixfix) list) list =
+          map (fn (((vs, t), mx), cons) =>
+                  (vs, t, mx, map (fn ((c, ds), mx) => (c, ds, mx)) cons)) doms;
+      val comp_dnam =
+          case opt_name of NONE => space_implode "_" names | SOME s => s;
+    in add_domain_cmd comp_dnam specs end;
 
 val _ =
-  OuterSyntax.command "domain" "define recursive domains (HOLCF)" K.thy_decl
-    (domains_decl >> (Toplevel.theory o mk_domain));
+    OuterSyntax.command "domain" "define recursive domains (HOLCF)" K.thy_decl
+                        (domains_decl >> (Toplevel.theory o mk_domain));
 
 end;
 
--- a/src/HOLCF/Tools/domain/domain_library.ML	Mon Jun 01 09:26:28 2009 +0200
+++ b/src/HOLCF/Tools/domain/domain_library.ML	Tue Jun 02 12:18:08 2009 +0200
@@ -8,27 +8,32 @@
 (* ----- general support ---------------------------------------------------- *)
 
 fun mapn f n []      = []
-|   mapn f n (x::xs) = (f n x) :: mapn f (n+1) xs;
+  | mapn f n (x::xs) = (f n x) :: mapn f (n+1) xs;
 
-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 map_cumulr f start xs = List.foldr (fn (x,(ys,res))=>case f(x,res) of (y,res2) =>
-						  (y::ys,res2)) ([],start) xs;
+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 map_cumulr f start xs =
+    List.foldr (fn (x,(ys,res))=>case f(x,res) of (y,res2) =>
+                                                  (y::ys,res2)) ([],start) xs;
 
 fun first  (x,_,_) = x; fun second (_,x,_) = x; fun third  (_,_,x) = x;
 fun upd_first  f (x,y,z) = (f x,   y,   z);
 fun upd_second f (x,y,z) = (  x, f y,   z);
 fun upd_third  f (x,y,z) = (  x,   y, f z);
 
-fun atomize ctxt thm = let val r_inst = read_instantiate ctxt;
-    fun at  thm = case concl_of thm of
-      _$(Const("op &",_)$_$_)       => at(thm RS conjunct1)@at(thm RS conjunct2)
-    | _$(Const("All" ,_)$Abs(s,_,_))=> at(thm RS (r_inst [(("x", 0), "?" ^ s)] spec))
-    | _				    => [thm];
-in map zero_var_indexes (at thm) end;
+fun atomize ctxt thm =
+    let
+      val r_inst = read_instantiate ctxt;
+      fun at thm =
+          case concl_of thm of
+            _$(Const("op &",_)$_$_)       => at(thm RS conjunct1)@at(thm RS conjunct2)
+          | _$(Const("All" ,_)$Abs(s,_,_))=> at(thm RS (r_inst [(("x", 0), "?" ^ s)] spec))
+          | _                             => [thm];
+    in map zero_var_indexes (at thm) end;
 
 (* infix syntax *)
 
@@ -91,9 +96,9 @@
   val mk_return : term -> term;
   val cproj : term -> 'a list -> int -> term;
   val list_ccomb : term * term list -> term;
-(*
-  val con_app : string -> ('a * 'b * string) list -> term;
-*)
+  (*
+   val con_app : string -> ('a * 'b * string) list -> term;
+   *)
   val con_app2 : string -> ('a -> term) -> 'a list -> term;
   val proj : term -> 'a list -> int -> term;
   val prj : ('a -> 'b -> 'a) -> ('a -> 'b -> 'a) -> 'a -> 'b list -> int -> 'a;
@@ -126,8 +131,8 @@
   val ==> : term * term -> term;
   val mk_All : string * term -> term;
 
-  (* Domain specifications *)
-  eqtype arg;
+      (* Domain specifications *)
+      eqtype arg;
   type cons = string * arg list;
   type eq = (string * typ list) * cons list;
   val mk_arg : (bool * DatatypeAux.dtyp) * string option * string -> arg;
@@ -169,15 +174,17 @@
 
 (* ----- name handling ----- *)
 
-val strip_esc = let fun strip ("'" :: c :: cs) = c :: strip cs
-		    |   strip ["'"] = []
-		    |   strip (c :: cs) = c :: strip cs
-		    |   strip [] = [];
-in implode o strip o Symbol.explode end;
+val strip_esc =
+    let fun strip ("'" :: c :: cs) = c :: strip cs
+          | strip ["'"] = []
+          | strip (c :: cs) = c :: strip cs
+          | strip [] = [];
+    in implode o strip o Symbol.explode end;
 
-fun extern_name con = case Symbol.explode con of 
-		   ("o"::"p"::" "::rest) => implode rest
-		   | _ => con;
+fun extern_name con =
+    case Symbol.explode con of 
+      ("o"::"p"::" "::rest) => implode rest
+    | _ => con;
 fun dis_name  con = "is_"^ (extern_name con);
 fun dis_name_ con = "is_"^ (strip_esc   con);
 fun mat_name  con = "match_"^ (extern_name con);
@@ -186,19 +193,20 @@
 fun pat_name_ con = (strip_esc   con) ^ "_pat";
 
 (* make distinct names out of the type list, 
-   forbidding "o","n..","x..","f..","P.." as names *)
+                                       forbidding "o","n..","x..","f..","P.." as names *)
 (* a number string is added if necessary *)
-fun mk_var_names ids : string list = let
-    fun nonreserved s = if s mem ["n","x","f","P"] then s^"'" else s;
-    fun index_vnames(vn::vns,occupied) =
+fun mk_var_names ids : string list =
+    let
+      fun nonreserved s = if s mem ["n","x","f","P"] then s^"'" else s;
+      fun index_vnames(vn::vns,occupied) =
           (case AList.lookup (op =) occupied vn of
              NONE => if vn mem vns
                      then (vn^"1") :: index_vnames(vns,(vn,1)  ::occupied)
                      else  vn      :: index_vnames(vns,          occupied)
            | SOME(i) => (vn^(string_of_int (i+1)))
-				   :: index_vnames(vns,(vn,i+1)::occupied))
-      | index_vnames([],occupied) = [];
-in index_vnames(map nonreserved ids, [("O",0),("o",0)]) end;
+                        :: index_vnames(vns,(vn,i+1)::occupied))
+        | index_vnames([],occupied) = [];
+    in index_vnames(map nonreserved ids, [("O",0),("o",0)]) end;
 
 fun cpo_type sg t = Sign.of_sort sg (Sign.certify_typ sg t, @{sort cpo});
 fun pcpo_type sg t = Sign.of_sort sg (Sign.certify_typ sg t, @{sort pcpo});
@@ -207,23 +215,23 @@
 (* ----- constructor list handling ----- *)
 
 type arg =
-  (bool * DatatypeAux.dtyp) *           (*  (lazy, recursive element) *)
-  string option *			(*   selector name    *)
-  string;				(*   argument name    *)
+     (bool * DatatypeAux.dtyp) *   (*  (lazy, recursive element) *)
+     string option *               (*   selector name    *)
+     string;                       (*   argument name    *)
 
 type cons =
-  string *				(* operator name of constr *)
-  arg list;				(* argument list      *)
+     string *         (* operator name of constr *)
+     arg list;        (* argument list      *)
 
 type eq =
-  (string *		(* name      of abstracted type *)
-   typ list) *		(* arguments of abstracted type *)
-  cons list;		(* represented type, as a constructor list *)
+     (string *        (* name      of abstracted type *)
+      typ list) *     (* arguments of abstracted type *)
+     cons list;       (* represented type, as a constructor list *)
 
 val mk_arg = I;
 
 fun rec_of ((_,dtyp),_,_) =
-  case dtyp of DatatypeAux.DtRec i => i | _ => ~1;
+    case dtyp of DatatypeAux.DtRec i => i | _ => ~1;
 (* FIXME: what about indirect recursion? *)
 
 fun is_lazy arg = fst (first arg);
@@ -333,8 +341,8 @@
 fun if_rec  arg f y   = if is_rec arg then f (rec_of arg) else y;
 fun app_rec_arg p arg = if_rec arg (fn n => fn x => (p n)`x) I (%# arg);
 fun prj _  _  x (   _::[]) _ = x
-|   prj f1 _  x (_::y::ys) 0 = f1 x y
-|   prj f1 f2 x (y::   ys) j = prj f1 f2 (f2 x y) ys (j-1);
+  | prj f1 _  x (_::y::ys) 0 = f1 x y
+  | prj f1 f2 x (y::   ys) j = prj f1 f2 (f2 x y) ys (j-1);
 fun  proj x      = prj (fn S => K(%%:"fst" $S)) (fn S => K(%%:"snd" $S)) x;
 fun cproj x      = prj (fn S => K(mk_cfst S)) (fn S => K(mk_csnd S)) x;
 fun lift tfn = Library.foldr (fn (x,t)=> (mk_trp(tfn x) ===> t));
@@ -348,11 +356,11 @@
 fun cpair (t,u) = %%: @{const_name cpair}`t`u;
 fun spair (t,u) = %%: @{const_name spair}`t`u;
 fun mk_ctuple [] = HOLogic.unit (* used in match_defs *)
-|   mk_ctuple ts = foldr1 cpair ts;
+  | mk_ctuple ts = foldr1 cpair ts;
 fun mk_stuple [] = ONE
-|   mk_stuple ts = foldr1 spair ts;
+  | mk_stuple ts = foldr1 spair ts;
 fun mk_ctupleT [] = HOLogic.unitT   (* used in match_defs *)
-|   mk_ctupleT Ts = foldr1 HOLogic.mk_prodT Ts;
+  | mk_ctupleT Ts = foldr1 HOLogic.mk_prodT Ts;
 fun mk_maybeT T = Type ("Fixrec.maybe",[T]);
 fun cpair_pat (p1,p2) = %%: @{const_name cpair_pat} $ p1 $ p2;
 val mk_ctuple_pat = foldr1 cpair_pat;
@@ -360,29 +368,32 @@
 fun bound_arg vns v = Bound(length vns -find_index_eq v vns -1);
 
 fun cont_eta_contract (Const("Cfun.Abs_CFun",TT) $ Abs(a,T,body)) = 
-      (case cont_eta_contract body  of
-        body' as (Const("Cfun.Rep_CFun",Ta) $ f $ Bound 0) => 
-	  if not (0 mem loose_bnos f) then incr_boundvars ~1 f 
-	  else   Const("Cfun.Abs_CFun",TT) $ Abs(a,T,body')
-      | body' => Const("Cfun.Abs_CFun",TT) $ Abs(a,T,body'))
-|   cont_eta_contract(f$t) = cont_eta_contract f $ cont_eta_contract t
-|   cont_eta_contract t    = t;
+    (case cont_eta_contract body  of
+       body' as (Const("Cfun.Rep_CFun",Ta) $ f $ Bound 0) => 
+       if not (0 mem loose_bnos f) then incr_boundvars ~1 f 
+       else   Const("Cfun.Abs_CFun",TT) $ Abs(a,T,body')
+     | body' => Const("Cfun.Abs_CFun",TT) $ Abs(a,T,body'))
+  | cont_eta_contract(f$t) = cont_eta_contract f $ cont_eta_contract t
+  | cont_eta_contract t    = t;
 
 fun idx_name dnames s n = s^(if length dnames = 1 then "" else string_of_int n);
 fun when_funs cons = if length cons = 1 then ["f"] 
                      else mapn (fn n => K("f"^(string_of_int n))) 1 cons;
-fun when_body cons funarg = let
-	fun one_fun n (_,[]  ) = /\ "dummy" (funarg(1,n))
-	|   one_fun n (_,args) = let
-		val l2 = length args;
-		fun idxs m arg = (if is_lazy arg then (fn t => mk_fup (ID, t))
-					         else I) (Bound(l2-m));
-		in cont_eta_contract (foldr'' 
-			(fn (a,t) => mk_ssplit (/\# (a,t)))
-			(args,
-			fn a=> /\#(a,(list_ccomb(funarg(l2,n),mapn idxs 1 args))))
-			) end;
-in (if length cons = 1 andalso length(snd(hd cons)) <= 1
-    then mk_strictify else I)
-     (foldr1 mk_sscase (mapn one_fun 1 cons)) end;
+fun when_body cons funarg =
+    let
+      fun one_fun n (_,[]  ) = /\ "dummy" (funarg(1,n))
+        | one_fun n (_,args) = let
+            val l2 = length args;
+            fun idxs m arg = (if is_lazy arg then (fn t => mk_fup (ID, t))
+                              else I) (Bound(l2-m));
+          in cont_eta_contract
+               (foldr'' 
+                  (fn (a,t) => mk_ssplit (/\# (a,t)))
+                  (args,
+                fn a=> /\#(a,(list_ccomb(funarg(l2,n),mapn idxs 1 args))))
+               ) end;
+    in (if length cons = 1 andalso length(snd(hd cons)) <= 1
+        then mk_strictify else I)
+         (foldr1 mk_sscase (mapn one_fun 1 cons)) end;
+
 end; (* struct *)
--- a/src/HOLCF/Tools/domain/domain_syntax.ML	Mon Jun 01 09:26:28 2009 +0200
+++ b/src/HOLCF/Tools/domain/domain_syntax.ML	Tue Jun 02 12:18:08 2009 +0200
@@ -6,17 +6,17 @@
 
 signature DOMAIN_SYNTAX =
 sig
-    val calc_syntax:
-        typ ->
-        (string * typ list) *
-        (binding * (bool * binding option * typ) list * mixfix) list ->
-        (binding * typ * mixfix) list * ast Syntax.trrule list
+  val calc_syntax:
+      typ ->
+      (string * typ list) *
+      (binding * (bool * binding option * typ) list * mixfix) list ->
+      (binding * typ * mixfix) list * ast Syntax.trrule list
 
-    val add_syntax:
-        string ->
-        ((string * typ list) *
-         (binding * (bool * binding option * typ) list * mixfix) list) list ->
-        theory -> theory
+  val add_syntax:
+      string ->
+      ((string * typ list) *
+       (binding * (bool * binding option * typ) list * mixfix) list) list ->
+      theory -> theory
 end;
 
 
@@ -27,127 +27,129 @@
 infixr 5 -->; infixr 6 ->>;
 
 fun calc_syntax
-        (dtypeprod : typ)
-        ((dname : string, typevars : typ list), 
-	 (cons': (binding * (bool * binding option * typ) list * mixfix) list))
+      (dtypeprod : typ)
+      ((dname : string, typevars : typ list), 
+       (cons': (binding * (bool * binding option * typ) list * mixfix) list))
     : (binding * typ * mixfix) list * ast Syntax.trrule list =
     let
-        (* ----- constants concerning the isomorphism ------------------------------- *)
+      (* ----- constants concerning the isomorphism ------------------------------- *)
 
-        local
-            fun opt_lazy (lazy,_,t) = if lazy then mk_uT t else t
-            fun prod     (_,args,_) = case args of [] => oneT
-                                                 | _ => foldr1 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,_) = List.foldr (op ->>) (freetvar "t") (map third args);
-        in
-        val dtype  = Type(dname,typevars);
-        val dtype2 = foldr1 mk_ssumT (map prod cons');
-        val dnam = Long_Name.base_name dname;
-        fun dbind s = Binding.name (dnam ^ s);
-        val const_rep  = (dbind "_rep" ,              dtype  ->> dtype2, NoSyn);
-        val const_abs  = (dbind "_abs" ,              dtype2 ->> dtype , NoSyn);
-        val const_when = (dbind "_when", List.foldr (op ->>) (dtype ->> freetvar "t") (map when_type cons'), NoSyn);
-        val const_copy = (dbind "_copy", dtypeprod ->> dtype  ->> dtype , NoSyn);
-        end;
+      local
+        fun opt_lazy (lazy,_,t) = if lazy then mk_uT t else t
+        fun prod     (_,args,_) = case args of [] => oneT
+                                             | _ => foldr1 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,_) = List.foldr (op ->>) (freetvar "t") (map third args);
+      in
+      val dtype  = Type(dname,typevars);
+      val dtype2 = foldr1 mk_ssumT (map prod cons');
+      val dnam = Long_Name.base_name dname;
+      fun dbind s = Binding.name (dnam ^ s);
+      val const_rep  = (dbind "_rep" ,              dtype  ->> dtype2, NoSyn);
+      val const_abs  = (dbind "_abs" ,              dtype2 ->> dtype , NoSyn);
+      val const_when = (dbind "_when", List.foldr (op ->>) (dtype ->> freetvar "t") (map when_type cons'), NoSyn);
+      val const_copy = (dbind "_copy", dtypeprod ->> dtype  ->> dtype , NoSyn);
+      end;
 
-        (* ----- constants concerning constructors, discriminators, and selectors --- *)
+      (* ----- constants concerning constructors, discriminators, and selectors --- *)
 
-        local
-            val escape = let
-	        fun esc (c::cs) = if c mem ["'","_","(",")","/"] then "'"::c::esc cs
-			          else      c::esc cs
-	          |   esc []      = []
-	    in implode o esc o Symbol.explode end;
-            fun dis_name_ con     = Binding.name ("is_" ^ strip_esc (Binding.name_of con));
-            fun mat_name_ con     = Binding.name ("match_" ^ strip_esc (Binding.name_of con));
-            fun pat_name_ con     = Binding.name (strip_esc (Binding.name_of con) ^ "_pat");
-            fun con (name,args,mx) = (name, List.foldr (op ->>) dtype (map third args), mx);
-            fun dis (con,args,mx) = (dis_name_ con, dtype->>trT,
-			             Mixfix(escape ("is_" ^ Binding.name_of con), [], Syntax.max_pri));
-	    (* strictly speaking, these constants have one argument,
-	     but the mixfix (without arguments) is introduced only
-	         to generate parse rules for non-alphanumeric names*)
-            fun freetvar s n      = let val tvar = mk_TFree (s ^ string_of_int n) in
-			                if tvar mem typevars then freetvar ("t"^s) n else tvar end;
-            fun mk_matT (a,bs,c)  = a ->> foldr (op ->>) (mk_maybeT c) bs ->> mk_maybeT c;
-            fun mat (con,args,mx) = (mat_name_ con,
-                                     mk_matT(dtype, map third args, freetvar "t" 1),
-			             Mixfix(escape ("match_" ^ Binding.name_of con), [], Syntax.max_pri));
-            fun sel1 (_,sel,typ)  = Option.map (fn s => (s,dtype ->> typ,NoSyn)) sel;
-            fun sel (con,args,mx) = List.mapPartial sel1 args;
-            fun mk_patT (a,b)     = a ->> mk_maybeT b;
-            fun pat_arg_typ n arg = mk_patT (third arg, freetvar "t" n);
-            fun pat (con,args,mx) = (pat_name_ con, (mapn pat_arg_typ 1 args) --->
-			                                                      mk_patT (dtype, mk_ctupleT (map (freetvar "t") (1 upto length args))),
-			             Mixfix(escape (Binding.name_of con ^ "_pat"), [], Syntax.max_pri));
+      local
+        val escape = let
+          fun esc (c::cs) = if c mem ["'","_","(",")","/"] then "'"::c::esc cs
+                            else      c::esc cs
+            |   esc []      = []
+        in implode o esc o Symbol.explode end;
+        fun dis_name_ con     = Binding.name ("is_" ^ strip_esc (Binding.name_of con));
+        fun mat_name_ con     = Binding.name ("match_" ^ strip_esc (Binding.name_of con));
+        fun pat_name_ con     = Binding.name (strip_esc (Binding.name_of con) ^ "_pat");
+        fun con (name,args,mx) = (name, List.foldr (op ->>) dtype (map third args), mx);
+        fun dis (con,args,mx) = (dis_name_ con, dtype->>trT,
+                                 Mixfix(escape ("is_" ^ Binding.name_of con), [], Syntax.max_pri));
+        (* strictly speaking, these constants have one argument,
+         but the mixfix (without arguments) is introduced only
+             to generate parse rules for non-alphanumeric names*)
+        fun freetvar s n      = let val tvar = mk_TFree (s ^ string_of_int n) in
+                                  if tvar mem typevars then freetvar ("t"^s) n else tvar end;
+        fun mk_matT (a,bs,c)  = a ->> foldr (op ->>) (mk_maybeT c) bs ->> mk_maybeT c;
+        fun mat (con,args,mx) = (mat_name_ con,
+                                 mk_matT(dtype, map third args, freetvar "t" 1),
+                                 Mixfix(escape ("match_" ^ Binding.name_of con), [], Syntax.max_pri));
+        fun sel1 (_,sel,typ)  = Option.map (fn s => (s,dtype ->> typ,NoSyn)) sel;
+        fun sel (con,args,mx) = List.mapPartial sel1 args;
+        fun mk_patT (a,b)     = a ->> mk_maybeT b;
+        fun pat_arg_typ n arg = mk_patT (third arg, freetvar "t" n);
+        fun pat (con,args,mx) = (pat_name_ con,
+                                 (mapn pat_arg_typ 1 args)
+                                   --->
+                                   mk_patT (dtype, mk_ctupleT (map (freetvar "t") (1 upto length args))),
+                                 Mixfix(escape (Binding.name_of con ^ "_pat"), [], Syntax.max_pri));
 
-        in
-        val consts_con = map con cons';
-        val consts_dis = map dis cons';
-        val consts_mat = map mat cons';
-        val consts_pat = map pat cons';
-        val consts_sel = List.concat(map sel cons');
-        end;
+      in
+      val consts_con = map con cons';
+      val consts_dis = map dis cons';
+      val consts_mat = map mat cons';
+      val consts_pat = map pat cons';
+      val consts_sel = List.concat(map sel cons');
+      end;
 
-        (* ----- constants concerning induction ------------------------------------- *)
+      (* ----- constants concerning induction ------------------------------------- *)
 
-        val const_take   = (dbind "_take"  , HOLogic.natT-->dtype->>dtype, NoSyn);
-        val const_finite = (dbind "_finite", dtype-->HOLogic.boolT       , NoSyn);
+      val const_take   = (dbind "_take"  , HOLogic.natT-->dtype->>dtype, NoSyn);
+      val const_finite = (dbind "_finite", dtype-->HOLogic.boolT       , NoSyn);
 
-        (* ----- case translation --------------------------------------------------- *)
+      (* ----- case translation --------------------------------------------------- *)
 
-        local open Syntax in
-        local
-            fun c_ast con mx = Constant (Syntax.const_name mx (Binding.name_of con));
-            fun expvar n     = Variable ("e"^(string_of_int n));
-            fun argvar n m _ = Variable ("a"^(string_of_int n)^"_"^
-				         (string_of_int m));
-            fun argvars n args = mapn (argvar n) 1 args;
-            fun app s (l,r)  = mk_appl (Constant s) [l,r];
-            val cabs = app "_cabs";
-            val capp = app "Rep_CFun";
-            fun con1 n (con,args,mx) = Library.foldl capp (c_ast con mx, argvars n args);
-            fun case1 n (con,args,mx) = app "_case1" (con1 n (con,args,mx), expvar n);
-            fun arg1 n (con,args,_) = List.foldr cabs (expvar n) (argvars n args);
-            fun when1 n m = if n = m then arg1 n else K (Constant "UU");
+      local open Syntax in
+      local
+        fun c_ast con mx = Constant (Syntax.const_name mx (Binding.name_of con));
+        fun expvar n     = Variable ("e"^(string_of_int n));
+        fun argvar n m _ = Variable ("a"^(string_of_int n)^"_"^
+                                     (string_of_int m));
+        fun argvars n args = mapn (argvar n) 1 args;
+        fun app s (l,r)  = mk_appl (Constant s) [l,r];
+        val cabs = app "_cabs";
+        val capp = app "Rep_CFun";
+        fun con1 n (con,args,mx) = Library.foldl capp (c_ast con mx, argvars n args);
+        fun case1 n (con,args,mx) = app "_case1" (con1 n (con,args,mx), expvar n);
+        fun arg1 n (con,args,_) = List.foldr cabs (expvar n) (argvars n args);
+        fun when1 n m = if n = m then arg1 n else K (Constant "UU");
 
-            fun app_var x = mk_appl (Constant "_variable") [x, Variable "rhs"];
-            fun app_pat x = mk_appl (Constant "_pat") [x];
-            fun args_list [] = Constant "_noargs"
-              |   args_list xs = foldr1 (app "_args") xs;
-        in
-        val case_trans =
-            ParsePrintRule
-                (app "_case_syntax" (Variable "x", foldr1 (app "_case2") (mapn case1 1 cons')),
-                 capp (Library.foldl capp (Constant (dnam^"_when"), mapn arg1 1 cons'), Variable "x"));
+        fun app_var x = mk_appl (Constant "_variable") [x, Variable "rhs"];
+        fun app_pat x = mk_appl (Constant "_pat") [x];
+        fun args_list [] = Constant "_noargs"
+          |   args_list xs = foldr1 (app "_args") xs;
+      in
+      val case_trans =
+          ParsePrintRule
+            (app "_case_syntax" (Variable "x", foldr1 (app "_case2") (mapn case1 1 cons')),
+             capp (Library.foldl capp (Constant (dnam^"_when"), mapn arg1 1 cons'), Variable "x"));
 
-        fun one_abscon_trans n (con,mx,args) =
-            ParsePrintRule
-                (cabs (con1 n (con,mx,args), expvar n),
-                 Library.foldl capp (Constant (dnam^"_when"), mapn (when1 n) 1 cons'));
-        val abscon_trans = mapn one_abscon_trans 1 cons';
-            
-        fun one_case_trans (con,args,mx) =
-            let
-                val cname = c_ast con mx;
-                val pname = Constant (strip_esc (Binding.name_of con) ^ "_pat");
-                val ns = 1 upto length args;
-                val xs = map (fn n => Variable ("x"^(string_of_int n))) ns;
-                val ps = map (fn n => Variable ("p"^(string_of_int n))) ns;
-                val vs = map (fn n => Variable ("v"^(string_of_int n))) ns;
-            in
-                [ParseRule (app_pat (Library.foldl capp (cname, xs)),
-                            mk_appl pname (map app_pat xs)),
-                 ParseRule (app_var (Library.foldl capp (cname, xs)),
-                            app_var (args_list xs)),
-                 PrintRule (Library.foldl capp (cname, ListPair.map (app "_match") (ps,vs)),
-                            app "_match" (mk_appl pname ps, args_list vs))]
-            end;
-        val Case_trans = List.concat (map one_case_trans cons');
-        end;
-        end;
+      fun one_abscon_trans n (con,mx,args) =
+          ParsePrintRule
+            (cabs (con1 n (con,mx,args), expvar n),
+             Library.foldl capp (Constant (dnam^"_when"), mapn (when1 n) 1 cons'));
+      val abscon_trans = mapn one_abscon_trans 1 cons';
+          
+      fun one_case_trans (con,args,mx) =
+          let
+            val cname = c_ast con mx;
+            val pname = Constant (strip_esc (Binding.name_of con) ^ "_pat");
+            val ns = 1 upto length args;
+            val xs = map (fn n => Variable ("x"^(string_of_int n))) ns;
+            val ps = map (fn n => Variable ("p"^(string_of_int n))) ns;
+            val vs = map (fn n => Variable ("v"^(string_of_int n))) ns;
+          in
+            [ParseRule (app_pat (Library.foldl capp (cname, xs)),
+                        mk_appl pname (map app_pat xs)),
+             ParseRule (app_var (Library.foldl capp (cname, xs)),
+                        app_var (args_list xs)),
+             PrintRule (Library.foldl capp (cname, ListPair.map (app "_match") (ps,vs)),
+                        app "_match" (mk_appl pname ps, args_list vs))]
+          end;
+      val Case_trans = List.concat (map one_case_trans cons');
+      end;
+      end;
 
     in ([const_rep, const_abs, const_when, const_copy] @ 
         consts_con @ consts_dis @ consts_mat @ consts_pat @ consts_sel @
@@ -158,22 +160,22 @@
 (* ----- putting all the syntax stuff together ------------------------------ *)
 
 fun add_syntax
-        (comp_dnam : string)
-        (eqs' : ((string * typ list) *
-	         (binding * (bool * binding option * typ) list * mixfix) list) list)
-        (thy'' : theory) =
+      (comp_dnam : string)
+      (eqs' : ((string * typ list) *
+               (binding * (bool * binding option * typ) list * mixfix) list) list)
+      (thy'' : theory) =
     let
-        val dtypes  = map (Type o fst) eqs';
-        val boolT   = HOLogic.boolT;
-        val funprod = foldr1 HOLogic.mk_prodT (map (fn tp => tp ->> tp          ) dtypes);
-        val relprod = foldr1 HOLogic.mk_prodT (map (fn tp => tp --> tp --> boolT) dtypes);
-        val const_copy = (Binding.name (comp_dnam^"_copy"), funprod ->> funprod, NoSyn);
-        val const_bisim = (Binding.name (comp_dnam^"_bisim"), relprod --> boolT, NoSyn);
-        val ctt : ((binding * typ * mixfix) list * ast Syntax.trrule list) list = map (calc_syntax funprod) eqs';
+      val dtypes  = map (Type o fst) eqs';
+      val boolT   = HOLogic.boolT;
+      val funprod = foldr1 HOLogic.mk_prodT (map (fn tp => tp ->> tp          ) dtypes);
+      val relprod = foldr1 HOLogic.mk_prodT (map (fn tp => tp --> tp --> boolT) dtypes);
+      val const_copy = (Binding.name (comp_dnam^"_copy"), funprod ->> funprod, NoSyn);
+      val const_bisim = (Binding.name (comp_dnam^"_bisim"), relprod --> boolT, NoSyn);
+      val ctt : ((binding * typ * mixfix) list * ast Syntax.trrule list) list = map (calc_syntax funprod) eqs';
     in thy'' |> ContConsts.add_consts_i (List.concat (map fst ctt) @ 
-				         (if length eqs'>1 then [const_copy] else[])@
-				         [const_bisim])
-	     |> Sign.add_trrules_i (List.concat(map snd ctt))
+                                         (if length eqs'>1 then [const_copy] else[])@
+                                         [const_bisim])
+             |> Sign.add_trrules_i (List.concat(map snd ctt))
     end; (* let *)
 
 end; (* struct *)
--- a/src/HOLCF/Tools/domain/domain_theorems.ML	Mon Jun 01 09:26:28 2009 +0200
+++ b/src/HOLCF/Tools/domain/domain_theorems.ML	Tue Jun 02 12:18:08 2009 +0200
@@ -539,9 +539,10 @@
           [eq1, eq2]
       end;
     fun distincts []      = []
-      | distincts ((c,leqs)::cs) = flat
-	            (ListPair.map (distinct c) ((map #1 cs),leqs)) @
-		    distincts cs;
+      | distincts ((c,leqs)::cs) =
+        flat
+          (ListPair.map (distinct c) ((map #1 cs),leqs)) @
+        distincts cs;
   in map standard (distincts (cons ~~ distincts_le)) end;
 
 local 
--- a/src/Pure/IsaMakefile	Mon Jun 01 09:26:28 2009 +0200
+++ b/src/Pure/IsaMakefile	Tue Jun 02 12:18:08 2009 +0200
@@ -19,16 +19,15 @@
 
 ## Pure
 
-BOOTSTRAP_FILES = ML-Systems/exn.ML ML-Systems/ml_name_space.ML		\
+BOOTSTRAP_FILES = ML-Systems/compiler_polyml-5.0.ML			\
+  ML-Systems/compiler_polyml-5.2.ML ML-Systems/compiler_polyml-5.3.ML	\
+  ML-Systems/exn.ML ML-Systems/ml_name_space.ML				\
   ML-Systems/ml_pretty.ML ML-Systems/mosml.ML				\
   ML-Systems/multithreading.ML ML-Systems/multithreading_polyml.ML	\
-  ML-Systems/overloading_smlnj.ML ML-Systems/polyml-4.1.3.ML		\
-  ML-Systems/polyml-4.1.4.ML ML-Systems/polyml-4.2.0.ML			\
-  ML-Systems/polyml-5.0.ML ML-Systems/polyml-5.1.ML			\
-  ML-Systems/polyml-experimental.ML ML-Systems/polyml.ML		\
-  ML-Systems/polyml_common.ML ML-Systems/polyml_old_compiler4.ML	\
-  ML-Systems/polyml_old_compiler5.ML ML-Systems/polyml_pp.ML		\
-  ML-Systems/proper_int.ML ML-Systems/smlnj.ML				\
+  ML-Systems/overloading_smlnj.ML ML-Systems/polyml-5.0.ML		\
+  ML-Systems/polyml-5.1.ML ML-Systems/polyml-experimental.ML		\
+  ML-Systems/polyml.ML ML-Systems/polyml_common.ML			\
+  ML-Systems/pp_polyml.ML ML-Systems/proper_int.ML ML-Systems/smlnj.ML	\
   ML-Systems/system_shell.ML ML-Systems/thread_dummy.ML			\
   ML-Systems/time_limit.ML ML-Systems/universal.ML
 
--- a/src/Pure/Isar/attrib.ML	Mon Jun 01 09:26:28 2009 +0200
+++ b/src/Pure/Isar/attrib.ML	Tue Jun 02 12:18:08 2009 +0200
@@ -26,14 +26,10 @@
     (('c * 'a list) * ('b * 'a list) list) list ->
     (('c * 'att list) * ('fact * 'att list) list) list
   val crude_closure: Proof.context -> src -> src
-  val add_attributes: (bstring * (src -> attribute) * string) list -> theory -> theory
-  val syntax: attribute context_parser -> src -> attribute
   val setup: Binding.binding -> attribute context_parser -> string -> theory -> theory
   val attribute_setup: bstring * Position.T -> Symbol_Pos.text * Position.T -> string ->
     theory -> theory
-  val no_args: attribute -> src -> attribute
   val add_del: attribute -> attribute -> attribute context_parser
-  val add_del_args: attribute -> attribute -> src -> attribute
   val thm_sel: Facts.interval list parser
   val thm: thm context_parser
   val thms: thm list context_parser
@@ -89,6 +85,10 @@
     |> Pretty.chunks |> Pretty.writeln
   end;
 
+fun add_attribute name att comment thy = thy |> Attributes.map (fn atts =>
+  #2 (NameSpace.define (Sign.naming_of thy) (name, ((att, comment), stamp ())) atts)
+    handle Symtab.DUP dup => error ("Duplicate declaration of attribute " ^ quote dup));
+
 
 (* name space *)
 
@@ -149,24 +149,13 @@
   Args.closure src);
 
 
-(* add_attributes *)
-
-fun add_attributes raw_attrs thy =
-  let
-    val new_attrs =
-      raw_attrs |> map (fn (name, att, comment) => (Binding.name name, ((att, comment), stamp ())));
-    fun add attrs = fold (snd oo NameSpace.define (Sign.naming_of thy)) new_attrs attrs
-      handle Symtab.DUP dup => error ("Duplicate declaration of attributes " ^ quote dup);
-  in Attributes.map add thy end;
-
-
 (* attribute setup *)
 
-fun syntax scan src (context, th) =
-  let val (f: attribute, context') = Args.syntax "attribute" scan src context
-  in f (context', th) end;
+fun syntax scan = Args.syntax "attribute" scan;
 
-fun setup name scan comment = add_attributes [(Binding.name_of name, syntax scan, comment)];
+fun setup name scan =
+  add_attribute name
+    (fn src => fn (ctxt, th) => let val (a, ctxt') = syntax scan src ctxt in a (ctxt', th) end);
 
 fun attribute_setup name (txt, pos) cmt =
   Context.theory_map (ML_Context.expression pos
@@ -175,12 +164,9 @@
     ("(" ^ ML_Syntax.make_binding name ^ ", " ^ txt ^ ", " ^ ML_Syntax.print_string cmt ^ ")"));
 
 
-(* basic syntax *)
+(* add/del syntax *)
 
-fun no_args x = syntax (Scan.succeed x);
-
-fun add_del add del = (Scan.lift (Args.add >> K add || Args.del >> K del || Scan.succeed add));
-fun add_del_args add del = syntax (add_del add del);
+fun add_del add del = Scan.lift (Args.add >> K add || Args.del >> K del || Scan.succeed add);
 
 
 
@@ -237,113 +223,99 @@
 
 fun internal att = Args.src (("Pure.attribute", [T.mk_attribute att]), Position.none);
 
-val internal_att =
-  syntax (Scan.lift Args.internal_attribute >> Morphism.form);
-
-
-(* tags *)
-
-val tagged = syntax (Scan.lift (Args.name -- Args.name) >> Thm.tag);
-val untagged = syntax (Scan.lift Args.name >> Thm.untag);
-
-val kind = syntax (Scan.lift Args.name >> Thm.kind);
-
 
 (* rule composition *)
 
 val COMP_att =
-  syntax (Scan.lift (Scan.optional (Args.bracks P.nat) 1) -- thm
-    >> (fn (i, B) => Thm.rule_attribute (fn _ => fn A => Drule.compose_single (A, i, B))));
+  Scan.lift (Scan.optional (Args.bracks P.nat) 1) -- thm
+    >> (fn (i, B) => Thm.rule_attribute (fn _ => fn A => Drule.compose_single (A, i, B)));
 
 val THEN_att =
-  syntax (Scan.lift (Scan.optional (Args.bracks P.nat) 1) -- thm
-    >> (fn (i, B) => Thm.rule_attribute (fn _ => fn A => A RSN (i, B))));
+  Scan.lift (Scan.optional (Args.bracks P.nat) 1) -- thm
+    >> (fn (i, B) => Thm.rule_attribute (fn _ => fn A => A RSN (i, B)));
 
 val OF_att =
-  syntax (thms >> (fn Bs => Thm.rule_attribute (fn _ => fn A => Bs MRS A)));
+  thms >> (fn Bs => Thm.rule_attribute (fn _ => fn A => Bs MRS A));
 
 
 (* rename_abs *)
 
-val rename_abs = syntax
-  (Scan.lift (Scan.repeat (Args.maybe Args.name) >> (apsnd o Drule.rename_bvars')));
+val rename_abs = Scan.repeat (Args.maybe Args.name) >> (apsnd o Drule.rename_bvars');
 
 
 (* unfold / fold definitions *)
 
 fun unfolded_syntax rule =
-  syntax (thms >>
-    (fn ths => Thm.rule_attribute (fn context => rule (Context.proof_of context) ths)));
+  thms >> (fn ths => Thm.rule_attribute (fn context => rule (Context.proof_of context) ths));
 
 val unfolded = unfolded_syntax LocalDefs.unfold;
 val folded = unfolded_syntax LocalDefs.fold;
 
 
-(* rule cases *)
-
-val consumes = syntax (Scan.lift (Scan.optional P.nat 1) >> RuleCases.consumes);
-val case_names = syntax (Scan.lift (Scan.repeat1 Args.name) >> RuleCases.case_names);
-val case_conclusion =
-  syntax (Scan.lift (Args.name -- Scan.repeat Args.name) >> RuleCases.case_conclusion);
-val params = syntax (Scan.lift (P.and_list1 (Scan.repeat Args.name)) >> RuleCases.params);
-
-
 (* rule format *)
 
-val rule_format = syntax (Args.mode "no_asm"
-  >> (fn true => ObjectLogic.rule_format_no_asm | false => ObjectLogic.rule_format));
+val rule_format = Args.mode "no_asm"
+  >> (fn true => ObjectLogic.rule_format_no_asm | false => ObjectLogic.rule_format);
 
-val elim_format = no_args (Thm.rule_attribute (K Tactic.make_elim));
+val elim_format = Thm.rule_attribute (K Tactic.make_elim);
 
 
 (* misc rules *)
 
-val standard = no_args (Thm.rule_attribute (K Drule.standard));
-
-val no_vars = no_args (Thm.rule_attribute (fn context => fn th =>
+val no_vars = Thm.rule_attribute (fn context => fn th =>
   let
     val ctxt = Variable.set_body false (Context.proof_of context);
     val ((_, [th']), _) = Variable.import_thms true [th] ctxt;
-  in th' end));
+  in th' end);
 
 val eta_long =
-  no_args (Thm.rule_attribute (K (Conv.fconv_rule Drule.eta_long_conversion)));
+  Thm.rule_attribute (K (Conv.fconv_rule Drule.eta_long_conversion));
 
-val rotated = syntax
-  (Scan.lift (Scan.optional P.int 1) >> (fn n => Thm.rule_attribute (K (rotate_prems n))));
-
-val abs_def = no_args (Thm.rule_attribute (K Drule.abs_def));
+val rotated = Scan.optional P.int 1 >> (fn n => Thm.rule_attribute (K (rotate_prems n)));
 
 
 (* theory setup *)
 
 val _ = Context.>> (Context.map_theory
- (add_attributes
-   [("attribute", internal_att, "internal attribute"),
-    ("tagged", tagged, "tagged theorem"),
-    ("untagged", untagged, "untagged theorem"),
-    ("kind", kind, "theorem kind"),
-    ("COMP", COMP_att, "direct composition with rules (no lifting)"),
-    ("THEN", THEN_att, "resolution with rule"),
-    ("OF", OF_att, "rule applied to facts"),
-    ("rename_abs", rename_abs, "rename bound variables in abstractions"),
-    ("unfolded", unfolded, "unfolded definitions"),
-    ("folded", folded, "folded definitions"),
-    ("standard", standard, "result put into standard form"),
-    ("elim_format", elim_format, "destruct rule turned into elimination rule format"),
-    ("no_vars", no_vars, "frozen schematic vars"),
-    ("eta_long", eta_long, "put theorem into eta long beta normal form"),
-    ("consumes", consumes, "number of consumed facts"),
-    ("case_names", case_names, "named rule cases"),
-    ("case_conclusion", case_conclusion, "named conclusion of rule cases"),
-    ("params", params, "named rule parameters"),
-    ("atomize", no_args ObjectLogic.declare_atomize, "declaration of atomize rule"),
-    ("rulify", no_args ObjectLogic.declare_rulify, "declaration of rulify rule"),
-    ("rule_format", rule_format, "result put into standard rule format"),
-    ("rotated", rotated, "rotated theorem premises"),
-    ("defn", add_del_args LocalDefs.defn_add LocalDefs.defn_del,
-      "declaration of definitional transformations"),
-    ("abs_def", abs_def, "abstract over free variables of a definition")]));
+ (setup (Binding.name "attribute") (Scan.lift Args.internal_attribute >> Morphism.form)
+    "internal attribute" #>
+  setup (Binding.name "tagged") (Scan.lift (Args.name -- Args.name) >> Thm.tag) "tagged theorem" #>
+  setup (Binding.name "untagged") (Scan.lift Args.name >> Thm.untag) "untagged theorem" #>
+  setup (Binding.name "kind") (Scan.lift Args.name >> Thm.kind) "theorem kind" #>
+  setup (Binding.name "COMP") COMP_att "direct composition with rules (no lifting)" #>
+  setup (Binding.name "THEN") THEN_att "resolution with rule" #>
+  setup (Binding.name "OF") OF_att "rule applied to facts" #>
+  setup (Binding.name "rename_abs") (Scan.lift rename_abs)
+    "rename bound variables in abstractions" #>
+  setup (Binding.name "unfolded") unfolded "unfolded definitions" #>
+  setup (Binding.name "folded") folded "folded definitions" #>
+  setup (Binding.name "consumes") (Scan.lift (Scan.optional P.nat 1) >> RuleCases.consumes)
+    "number of consumed facts" #>
+  setup (Binding.name "case_names") (Scan.lift (Scan.repeat1 Args.name) >> RuleCases.case_names)
+    "named rule cases" #>
+  setup (Binding.name "case_conclusion")
+    (Scan.lift (Args.name -- Scan.repeat Args.name) >> RuleCases.case_conclusion)
+    "named conclusion of rule cases" #>
+  setup (Binding.name "params")
+    (Scan.lift (P.and_list1 (Scan.repeat Args.name)) >> RuleCases.params)
+    "named rule parameters" #>
+  setup (Binding.name "standard") (Scan.succeed (Thm.rule_attribute (K Drule.standard)))
+    "result put into standard form (legacy)" #>
+  setup (Binding.name "rule_format") rule_format "result put into canonical rule format" #>
+  setup (Binding.name "elim_format") (Scan.succeed elim_format)
+    "destruct rule turned into elimination rule format" #>
+  setup (Binding.name "no_vars") (Scan.succeed no_vars) "frozen schematic vars" #>
+  setup (Binding.name "eta_long") (Scan.succeed eta_long)
+    "put theorem into eta long beta normal form" #>
+  setup (Binding.name "atomize") (Scan.succeed ObjectLogic.declare_atomize)
+    "declaration of atomize rule" #>
+  setup (Binding.name "rulify") (Scan.succeed ObjectLogic.declare_rulify)
+    "declaration of rulify rule" #>
+  setup (Binding.name "rotated") (Scan.lift rotated) "rotated theorem premises" #>
+  setup (Binding.name "defn") (add_del LocalDefs.defn_add LocalDefs.defn_del)
+    "declaration of definitional transformations" #>
+  setup (Binding.name "abs_def") (Scan.succeed (Thm.rule_attribute (K Drule.abs_def)))
+    "abstract over free variables of a definition"));
 
 
 
@@ -397,8 +369,8 @@
     val name = Sign.full_bname thy bname;
   in
     thy
-    |> add_attributes [(bname, syntax (Scan.lift (scan_config thy config) >> Morphism.form),
-      "configuration option")]
+    |> setup (Binding.name bname) (Scan.lift (scan_config thy config) >> Morphism.form)
+      "configuration option"
     |> Configs.map (Symtab.update (name, config))
   end;
 
--- a/src/Pure/Isar/method.ML	Mon Jun 01 09:26:28 2009 +0200
+++ b/src/Pure/Isar/method.ML	Tue Jun 02 12:18:08 2009 +0200
@@ -75,30 +75,13 @@
   val defined: theory -> string -> bool
   val method: theory -> src -> Proof.context -> method
   val method_i: theory -> src -> Proof.context -> method
-  val add_methods: (bstring * (src -> Proof.context -> method) * string) list
-    -> theory -> theory
-  val add_method: bstring * (src -> Proof.context -> method) * string
-    -> theory -> theory
   val syntax: 'a context_parser -> src -> Proof.context -> 'a * Proof.context
   val setup: binding -> (Proof.context -> method) context_parser -> string -> theory -> theory
   val method_setup: bstring * Position.T -> Symbol_Pos.text * Position.T -> string ->
     theory -> theory
-  val simple_args: 'a parser -> ('a -> Proof.context -> method) -> src -> Proof.context -> method
-  val ctxt_args: (Proof.context -> method) -> src -> Proof.context -> method
   type modifier = (Proof.context -> Proof.context) * attribute
   val section: modifier parser list -> thm list context_parser
   val sections: modifier parser list -> thm list list context_parser
-  val sectioned_args: 'a context_parser -> modifier parser list ->
-    ('a -> Proof.context -> 'b) -> src -> Proof.context -> 'b
-  val bang_sectioned_args: modifier parser list ->
-    (thm list -> Proof.context -> 'a) -> src -> Proof.context -> 'a
-  val bang_sectioned_args': modifier parser list -> 'a context_parser ->
-    ('a -> thm list -> Proof.context -> 'b) -> src -> Proof.context -> 'b
-  val only_sectioned_args: modifier parser list -> (Proof.context -> 'a) -> src ->
-    Proof.context -> 'a
-  val thms_ctxt_args: (thm list -> Proof.context -> 'a) -> src -> Proof.context -> 'a
-  val thms_args: (thm list -> 'a) -> src -> Proof.context -> 'a
-  val thm_args: (thm -> 'a) -> src -> Proof.context -> 'a
   val parse: text parser
 end;
 
@@ -356,6 +339,10 @@
     |> Pretty.chunks |> Pretty.writeln
   end;
 
+fun add_method name meth comment thy = thy |> Methods.map (fn meths =>
+  #2 (NameSpace.define (Sign.naming_of thy) (name, ((meth, comment), stamp ())) meths)
+    handle Symtab.DUP dup => error ("Duplicate declaration of method " ^ quote dup));
+
 
 (* get methods *)
 
@@ -376,27 +363,13 @@
 fun method thy = method_i thy o Args.map_name (NameSpace.intern (#1 (Methods.get thy)));
 
 
-(* add method *)
-
-fun add_methods raw_meths thy =
-  let
-    val new_meths = raw_meths |> map (fn (name, f, comment) =>
-      (Binding.name name, ((f, comment), stamp ())));
-
-    fun add meths = fold (snd oo NameSpace.define (Sign.naming_of thy)) new_meths meths
-      handle Symtab.DUP dup => error ("Duplicate declaration of method " ^ quote dup);
-  in Methods.map add thy end;
-
-val add_method = add_methods o Library.single;
-
-
 (* method setup *)
 
 fun syntax scan = Args.context_syntax "method" scan;
 
-fun setup name scan comment =
-  add_methods [(Binding.name_of name,
-    fn src => fn ctxt => let val (m, ctxt') = syntax scan src ctxt in m ctxt' end, comment)];
+fun setup name scan =
+  add_method name
+    (fn src => fn ctxt => let val (m, ctxt') = syntax scan src ctxt in m ctxt' end);
 
 fun method_setup name (txt, pos) cmt =
   Context.theory_map (ML_Context.expression pos
@@ -411,15 +384,6 @@
 structure P = OuterParse;
 
 
-(* basic *)
-
-fun simple_args scan f src ctxt : method =
-  fst (syntax (Scan.lift (scan >> (fn x => f x ctxt))) src ctxt);
-
-fun ctxt_args (f: Proof.context -> method) src ctxt =
-  fst (syntax (Scan.succeed (f ctxt)) src ctxt);
-
-
 (* sections *)
 
 type modifier = (Proof.context -> Proof.context) * attribute;
@@ -436,19 +400,6 @@
 
 fun sections ss = Scan.repeat (section ss);
 
-fun sectioned_args args ss f src ctxt =
-  let val ((x, _), ctxt') = syntax (args -- sections ss) src ctxt
-  in f x ctxt' end;
-
-fun bang_sectioned_args ss f = sectioned_args Args.bang_facts ss f;
-fun bang_sectioned_args' ss scan f =
-  sectioned_args (Args.bang_facts -- scan >> swap) ss (uncurry f);
-fun only_sectioned_args ss f = sectioned_args (Scan.succeed ()) ss (fn () => f);
-
-fun thms_ctxt_args f = sectioned_args (thms []) [] f;
-fun thms_args f = thms_ctxt_args (K o f);
-fun thm_args f = thms_args (fn [thm] => f thm | _ => error "Single theorem expected");
-
 end;
 
 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/Pure/ML-Systems/compiler_polyml-5.0.ML	Tue Jun 02 12:18:08 2009 +0200
@@ -0,0 +1,32 @@
+(*  Title:      Pure/ML-Systems/compiler_polyml-5.0.ML
+
+Runtime compilation -- for PolyML.compilerEx in version 5.0 and 5.1.
+*)
+
+fun use_text ({tune_source, print, error, ...}: use_context) (line, name) verbose txt =
+  let
+    val in_buffer = ref (explode (tune_source txt));
+    val out_buffer = ref ([]: string list);
+    fun output () = implode (rev (case ! out_buffer of "\n" :: cs => cs | cs => cs));
+
+    val current_line = ref line;
+    fun get () =
+      (case ! in_buffer of
+        [] => ""
+      | c :: cs => (in_buffer := cs; if c = "\n" then current_line := ! current_line + 1 else (); c));
+    fun put s = out_buffer := s :: ! out_buffer;
+
+    fun exec () =
+      (case ! in_buffer of
+        [] => ()
+      | _ => (PolyML.compilerEx (get, put, fn () => ! current_line, name) (); exec ()));
+  in
+    exec () handle exn => (error (output ()); raise exn);
+    if verbose then print (output ()) else ()
+  end;
+
+fun use_file context verbose name =
+  let
+    val instream = TextIO.openIn name;
+    val txt = Exn.release (Exn.capture TextIO.inputAll instream before TextIO.closeIn instream);
+  in use_text context (1, name) verbose txt end;
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/Pure/ML-Systems/compiler_polyml-5.2.ML	Tue Jun 02 12:18:08 2009 +0200
@@ -0,0 +1,51 @@
+(*  Title:      Pure/ML-Systems/compiler_polyml-5.2.ML
+
+Runtime compilation for Poly/ML 5.2 and 5.2.1.
+*)
+
+local
+
+fun drop_newline s =
+  if String.isSuffix "\n" s then String.substring (s, 0, size s - 1)
+  else s;
+
+in
+
+fun use_text ({tune_source, name_space, str_of_pos, print, error, ...}: use_context)
+    (start_line, name) verbose txt =
+  let
+    val current_line = ref start_line;
+    val in_buffer = ref (String.explode (tune_source txt));
+    val out_buffer = ref ([]: string list);
+    fun output () = drop_newline (implode (rev (! out_buffer)));
+
+    fun get () =
+      (case ! in_buffer of
+        [] => NONE
+      | c :: cs =>
+          (in_buffer := cs; if c = #"\n" then current_line := ! current_line + 1 else (); SOME c));
+    fun put s = out_buffer := s :: ! out_buffer;
+    fun message (msg, is_err, line) =
+      (if is_err then "Error: " else "Warning: ") ^ drop_newline msg ^ str_of_pos line name ^ "\n";
+
+    val parameters =
+     [PolyML.Compiler.CPOutStream put,
+      PolyML.Compiler.CPLineNo (fn () => ! current_line),
+      PolyML.Compiler.CPErrorMessageProc (put o message),
+      PolyML.Compiler.CPNameSpace name_space];
+    val _ =
+      (while not (List.null (! in_buffer)) do
+        PolyML.compiler (get, parameters) ())
+      handle exn =>
+       (put ("Exception- " ^ General.exnMessage exn ^ " raised");
+        error (output ()); raise exn);
+  in if verbose then print (output ()) else () end;
+
+fun use_file context verbose name =
+  let
+    val instream = TextIO.openIn name;
+    val txt = Exn.release (Exn.capture TextIO.inputAll instream before TextIO.closeIn instream);
+  in use_text context (1, name) verbose txt end;
+
+end;
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/Pure/ML-Systems/compiler_polyml-5.3.ML	Tue Jun 02 12:18:08 2009 +0200
@@ -0,0 +1,55 @@
+(*  Title:      Pure/ML-Systems/compiler_polyml-5.3.ML
+
+Runtime compilation for Poly/ML 5.3 (SVN experimental).
+*)
+
+local
+
+fun drop_newline s =
+  if String.isSuffix "\n" s then String.substring (s, 0, size s - 1)
+  else s;
+
+in
+
+fun use_text ({tune_source, name_space, str_of_pos, print, error, ...}: use_context)
+    (start_line, name) verbose txt =
+  let
+    val current_line = ref start_line;
+    val in_buffer = ref (String.explode (tune_source txt));
+    val out_buffer = ref ([]: string list);
+    fun output () = drop_newline (implode (rev (! out_buffer)));
+
+    fun get () =
+      (case ! in_buffer of
+        [] => NONE
+      | c :: cs =>
+          (in_buffer := cs; if c = #"\n" then current_line := ! current_line + 1 else (); SOME c));
+    fun put s = out_buffer := s :: ! out_buffer;
+    fun put_message {message = msg1, hard, location = {startLine = line, ...}, context} =
+     (put (if hard then "Error: " else "Warning: ");
+      PolyML.prettyPrint (put, 76) msg1;
+      (case context of NONE => () | SOME msg2 => PolyML.prettyPrint (put, 76) msg2);
+      put ("At" ^ str_of_pos line name ^ "\n"));
+
+    val parameters =
+     [PolyML.Compiler.CPOutStream put,
+      PolyML.Compiler.CPLineNo (fn () => ! current_line),
+      PolyML.Compiler.CPErrorMessageProc put_message,
+      PolyML.Compiler.CPNameSpace name_space,
+      PolyML.Compiler.CPPrintInAlphabeticalOrder false];
+    val _ =
+      (while not (List.null (! in_buffer)) do
+        PolyML.compiler (get, parameters) ())
+      handle exn =>
+       (put ("Exception- " ^ General.exnMessage exn ^ " raised");
+        error (output ()); raise exn);
+  in if verbose then print (output ()) else () end;
+
+fun use_file context verbose name =
+  let
+    val instream = TextIO.openIn name;
+    val txt = Exn.release (Exn.capture TextIO.inputAll instream before TextIO.closeIn instream);
+  in use_text context (1, name) verbose txt end;
+
+end;
+
--- a/src/Pure/ML-Systems/install_pp_polyml-experimental.ML	Mon Jun 01 09:26:28 2009 +0200
+++ b/src/Pure/ML-Systems/install_pp_polyml-experimental.ML	Tue Jun 02 12:18:08 2009 +0200
@@ -1,18 +1,17 @@
 (*  Title:      Pure/ML-Systems/install_pp_polyml-experimental.ML
 
-Extra toplevel pretty-printing for Poly/ML; experimental version for
-Poly/ML 5.3.
+Extra toplevel pretty-printing for Poly/ML 5.3 (SVN experimental).
 *)
 
-addPrettyPrinter (fn depth => fn pretty => fn x =>
+PolyML.addPrettyPrinter (fn depth => fn pretty => fn x =>
   (case Future.peek x of
-    NONE => PrettyString "<future>"
-  | SOME (Exn.Exn _) => PrettyString "<failed>"
+    NONE => PolyML.PrettyString "<future>"
+  | SOME (Exn.Exn _) => PolyML.PrettyString "<failed>"
   | SOME (Exn.Result y) => pretty (y, depth)));
 
-addPrettyPrinter (fn depth => fn pretty => fn x =>
+PolyML.addPrettyPrinter (fn depth => fn pretty => fn x =>
   (case Lazy.peek x of
-    NONE => PrettyString "<lazy>"
-  | SOME (Exn.Exn _) => PrettyString "<failed>"
+    NONE => PolyML.PrettyString "<lazy>"
+  | SOME (Exn.Exn _) => PolyML.PrettyString "<failed>"
   | SOME (Exn.Result y) => pretty (y, depth)));
 
--- a/src/Pure/ML-Systems/install_pp_polyml.ML	Mon Jun 01 09:26:28 2009 +0200
+++ b/src/Pure/ML-Systems/install_pp_polyml.ML	Tue Jun 02 12:18:08 2009 +0200
@@ -3,15 +3,17 @@
 Extra toplevel pretty-printing for Poly/ML.
 *)
 
-install_pp (fn (str, _, _, _) => fn depth => fn (print: 'a * int -> unit) => fn (x: 'a future) =>
-  (case Future.peek x of
-    NONE => str "<future>"
-  | SOME (Exn.Exn _) => str "<failed>"
-  | SOME (Exn.Result y) => print (y, depth)));
+PolyML.install_pp
+  (fn (str, _, _, _) => fn depth => fn (print: 'a * int -> unit) => fn (x: 'a future) =>
+    (case Future.peek x of
+      NONE => str "<future>"
+    | SOME (Exn.Exn _) => str "<failed>"
+    | SOME (Exn.Result y) => print (y, depth)));
 
-install_pp (fn (str, _, _, _) => fn depth => fn (print: 'a * int -> unit) => fn (x: 'a lazy) =>
-  (case Lazy.peek x of
-    NONE => str "<lazy>"
-  | SOME (Exn.Exn _) => str "<failed>"
-  | SOME (Exn.Result y) => print (y, depth)));
+PolyML.install_pp
+  (fn (str, _, _, _) => fn depth => fn (print: 'a * int -> unit) => fn (x: 'a lazy) =>
+    (case Lazy.peek x of
+      NONE => str "<lazy>"
+    | SOME (Exn.Exn _) => str "<failed>"
+    | SOME (Exn.Result y) => print (y, depth)));
 
--- a/src/Pure/ML-Systems/mosml.ML	Mon Jun 01 09:26:28 2009 +0200
+++ b/src/Pure/ML-Systems/mosml.ML	Tue Jun 02 12:18:08 2009 +0200
@@ -132,8 +132,6 @@
 (*dummy implementation*)
 fun exception_trace f = f ();
 
-(*dummy implementation*)
-fun print x = x;
 
 
 (** Compiler-independent timing functions **)
--- a/src/Pure/ML-Systems/multithreading_polyml.ML	Mon Jun 01 09:26:28 2009 +0200
+++ b/src/Pure/ML-Systems/multithreading_polyml.ML	Tue Jun 02 12:18:08 2009 +0200
@@ -1,7 +1,7 @@
 (*  Title:      Pure/ML-Systems/multithreading_polyml.ML
     Author:     Makarius
 
-Multithreading in Poly/ML 5.2 or later (cf. polyml/basis/Thread.sml).
+Multithreading in Poly/ML 5.2.1 or later (cf. polyml/basis/Thread.sml).
 *)
 
 signature MULTITHREADING_POLYML =
--- a/src/Pure/ML-Systems/polyml-4.1.3.ML	Mon Jun 01 09:26:28 2009 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,15 +0,0 @@
-(*  Title:      Pure/ML-Systems/polyml-4.1.3.ML
-
-Compatibility wrapper for Poly/ML 4.1.3.
-*)
-
-use "ML-Systems/polyml_old_basis.ML";
-use "ML-Systems/universal.ML";
-use "ML-Systems/thread_dummy.ML";
-use "ML-Systems/ml_name_space.ML";
-use "ML-Systems/polyml_common.ML";
-use "ML-Systems/polyml_old_compiler4.ML";
-use "ML-Systems/polyml_pp.ML";
-
-val pointer_eq = Address.wordEq;
-
--- a/src/Pure/ML-Systems/polyml-4.1.4.ML	Mon Jun 01 09:26:28 2009 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,15 +0,0 @@
-(*  Title:      Pure/ML-Systems/polyml-4.1.4.ML
-
-Compatibility wrapper for Poly/ML 4.1.4.
-*)
-
-use "ML-Systems/polyml_old_basis.ML";
-use "ML-Systems/universal.ML";
-use "ML-Systems/thread_dummy.ML";
-use "ML-Systems/ml_name_space.ML";
-use "ML-Systems/polyml_common.ML";
-use "ML-Systems/polyml_old_compiler4.ML";
-use "ML-Systems/polyml_pp.ML";
-
-val pointer_eq = Address.wordEq;
-
--- a/src/Pure/ML-Systems/polyml-4.2.0.ML	Mon Jun 01 09:26:28 2009 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,14 +0,0 @@
-(*  Title:      Pure/ML-Systems/polyml-4.2.0.ML
-
-Compatibility wrapper for Poly/ML 4.2.0.
-*)
-
-use "ML-Systems/universal.ML";
-use "ML-Systems/thread_dummy.ML";
-use "ML-Systems/ml_name_space.ML";
-use "ML-Systems/polyml_common.ML";
-use "ML-Systems/polyml_old_compiler4.ML";
-use "ML-Systems/polyml_pp.ML";
-
-val pointer_eq = Address.wordEq;
-
--- a/src/Pure/ML-Systems/polyml-5.0.ML	Mon Jun 01 09:26:28 2009 +0200
+++ b/src/Pure/ML-Systems/polyml-5.0.ML	Tue Jun 02 12:18:08 2009 +0200
@@ -7,8 +7,8 @@
 use "ML-Systems/thread_dummy.ML";
 use "ML-Systems/ml_name_space.ML";
 use "ML-Systems/polyml_common.ML";
-use "ML-Systems/polyml_old_compiler5.ML";
-use "ML-Systems/polyml_pp.ML";
+use "ML-Systems/compiler_polyml-5.0.ML";
+use "ML-Systems/pp_polyml.ML";
 
 val pointer_eq = PolyML.pointerEq;
 
--- a/src/Pure/ML-Systems/polyml-5.1.ML	Mon Jun 01 09:26:28 2009 +0200
+++ b/src/Pure/ML-Systems/polyml-5.1.ML	Tue Jun 02 12:18:08 2009 +0200
@@ -6,8 +6,8 @@
 use "ML-Systems/thread_dummy.ML";
 use "ML-Systems/ml_name_space.ML";
 use "ML-Systems/polyml_common.ML";
-use "ML-Systems/polyml_old_compiler5.ML";
-use "ML-Systems/polyml_pp.ML";
+use "ML-Systems/compiler_polyml-5.0.ML";
+use "ML-Systems/pp_polyml.ML";
 
 val pointer_eq = PolyML.pointerEq;
 
--- a/src/Pure/ML-Systems/polyml-experimental.ML	Mon Jun 01 09:26:28 2009 +0200
+++ b/src/Pure/ML-Systems/polyml-experimental.ML	Tue Jun 02 12:18:08 2009 +0200
@@ -1,6 +1,6 @@
-(*  Title:      Pure/ML-Systems/polyml.ML
+(*  Title:      Pure/ML-Systems/polyml-experimental.ML
 
-Compatibility wrapper for experimental versions of Poly/ML after 5.2.1.
+Compatibility wrapper for Poly/ML 5.3 (SVN experimental).
 *)
 
 open Thread;
@@ -19,92 +19,42 @@
 
 fun share_common_data () = PolyML.shareCommonData PolyML.rootFunction;
 
-
-(* runtime compilation *)
-
-local
-
-fun drop_newline s =
-  if String.isSuffix "\n" s then String.substring (s, 0, size s - 1)
-  else s;
-
-in
-
-fun use_text ({tune_source, name_space, str_of_pos, print, error, ...}: use_context)
-    (start_line, name) verbose txt =
-  let
-    val current_line = ref start_line;
-    val in_buffer = ref (String.explode (tune_source txt));
-    val out_buffer = ref ([]: string list);
-    fun output () = drop_newline (implode (rev (! out_buffer)));
-
-    fun get () =
-      (case ! in_buffer of
-        [] => NONE
-      | c :: cs =>
-          (in_buffer := cs; if c = #"\n" then current_line := ! current_line + 1 else (); SOME c));
-    fun put s = out_buffer := s :: ! out_buffer;
-    fun put_message {message = msg1, hard, location = {startLine = line, ...}, context} =
-     (put (if hard then "Error: " else "Warning: ");
-      PolyML.prettyPrint (put, 76) msg1;
-      (case context of NONE => () | SOME msg2 => PolyML.prettyPrint (put, 76) msg2);
-      put ("At" ^ str_of_pos line name ^ "\n"));
-
-    val parameters =
-     [PolyML.Compiler.CPOutStream put,
-      PolyML.Compiler.CPLineNo (fn () => ! current_line),
-      PolyML.Compiler.CPErrorMessageProc put_message,
-      PolyML.Compiler.CPNameSpace name_space,
-      PolyML.Compiler.CPPrintInAlphabeticalOrder false];
-    val _ =
-      (while not (List.null (! in_buffer)) do
-        PolyML.compiler (get, parameters) ())
-      handle exn =>
-       (put ("Exception- " ^ General.exnMessage exn ^ " raised");
-        error (output ()); raise exn);
-  in if verbose then print (output ()) else () end;
-
-fun use_file context verbose name =
-  let
-    val instream = TextIO.openIn name;
-    val txt = Exn.release (Exn.capture TextIO.inputAll instream before TextIO.closeIn instream);
-  in use_text context (1, name) verbose txt end;
-
-end;
+use "ML-Systems/compiler_polyml-5.3.ML";
 
 
 (* toplevel pretty printing *)
 
 val pretty_ml =
   let
-    fun convert len (PrettyBlock (ind, _, context, prts)) =
+    fun convert len (PolyML.PrettyBlock (ind, _, context, prts)) =
           let
             fun property name default =
-              (case List.find (fn ContextProperty (a, _) => name = a | _ => false) context of
-                SOME (ContextProperty (_, b)) => b
+              (case List.find (fn PolyML.ContextProperty (a, _) => name = a | _ => false) context of
+                SOME (PolyML.ContextProperty (_, b)) => b
               | NONE => default);
             val bg = property "begin" "";
             val en = property "end" "";
             val len' = property "length" len;
           in ML_Pretty.Block ((bg, en), map (convert len') prts, ind) end
-      | convert len (PrettyString s) =
+      | convert len (PolyML.PrettyString s) =
           ML_Pretty.String (s, case Int.fromString len of SOME i => i | NONE => size s)
-      | convert _ (PrettyBreak (wd, _)) =
+      | convert _ (PolyML.PrettyBreak (wd, _)) =
           ML_Pretty.Break (if wd < 99999 then (false, wd) else (true, 2));
   in convert "" end;
 
 fun ml_pretty (ML_Pretty.Block ((bg, en), prts, ind)) =
       let val context =
-        (if bg = "" then [] else [ContextProperty ("begin", bg)]) @
-        (if en = "" then [] else [ContextProperty ("end", en)])
-      in PrettyBlock (ind, false, context, map ml_pretty prts) end
+        (if bg = "" then [] else [PolyML.ContextProperty ("begin", bg)]) @
+        (if en = "" then [] else [PolyML.ContextProperty ("end", en)])
+      in PolyML.PrettyBlock (ind, false, context, map ml_pretty prts) end
   | ml_pretty (ML_Pretty.String (s, len)) =
-      if len = size s then PrettyString s
-      else PrettyBlock (0, false, [ContextProperty ("length", Int.toString len)], [PrettyString s])
-  | ml_pretty (ML_Pretty.Break (false, wd)) = PrettyBreak (wd, 0)
-  | ml_pretty (ML_Pretty.Break (true, _)) = PrettyBreak (99999, 0);
+      if len = size s then PolyML.PrettyString s
+      else PolyML.PrettyBlock
+        (0, false, [PolyML.ContextProperty ("length", Int.toString len)], [PolyML.PrettyString s])
+  | ml_pretty (ML_Pretty.Break (false, wd)) = PolyML.PrettyBreak (wd, 0)
+  | ml_pretty (ML_Pretty.Break (true, _)) = PolyML.PrettyBreak (99999, 0);
 
 fun toplevel_pp context (_: string list) pp =
   use_text context (1, "pp") false
-    ("addPrettyPrinter (fn _ => fn _ => ml_pretty o Pretty.to_ML o (" ^ pp ^ "))");
+    ("PolyML.addPrettyPrinter (fn _ => fn _ => ml_pretty o Pretty.to_ML o (" ^ pp ^ "))");
 
--- a/src/Pure/ML-Systems/polyml.ML	Mon Jun 01 09:26:28 2009 +0200
+++ b/src/Pure/ML-Systems/polyml.ML	Tue Jun 02 12:18:08 2009 +0200
@@ -1,6 +1,6 @@
 (*  Title:      Pure/ML-Systems/polyml.ML
 
-Compatibility wrapper for Poly/ML 5.2 or later.
+Compatibility wrapper for Poly/ML 5.2 and 5.2.1.
 *)
 
 open Thread;
@@ -22,54 +22,6 @@
 
 fun share_common_data () = PolyML.shareCommonData PolyML.rootFunction;
 
-
-(* runtime compilation *)
-
-local
-
-fun drop_newline s =
-  if String.isSuffix "\n" s then String.substring (s, 0, size s - 1)
-  else s;
-
-in
-
-fun use_text ({tune_source, name_space, str_of_pos, print, error, ...}: use_context)
-    (start_line, name) verbose txt =
-  let
-    val current_line = ref start_line;
-    val in_buffer = ref (String.explode (tune_source txt));
-    val out_buffer = ref ([]: string list);
-    fun output () = drop_newline (implode (rev (! out_buffer)));
+use "ML-Systems/compiler_polyml-5.2.ML";
+use "ML-Systems/pp_polyml.ML";
 
-    fun get () =
-      (case ! in_buffer of
-        [] => NONE
-      | c :: cs =>
-          (in_buffer := cs; if c = #"\n" then current_line := ! current_line + 1 else (); SOME c));
-    fun put s = out_buffer := s :: ! out_buffer;
-    fun message (msg, is_err, line) =
-      (if is_err then "Error: " else "Warning: ") ^ drop_newline msg ^ str_of_pos line name ^ "\n";
-
-    val parameters =
-     [PolyML.Compiler.CPOutStream put,
-      PolyML.Compiler.CPLineNo (fn () => ! current_line),
-      PolyML.Compiler.CPErrorMessageProc (put o message),
-      PolyML.Compiler.CPNameSpace name_space];
-    val _ =
-      (while not (List.null (! in_buffer)) do
-        PolyML.compiler (get, parameters) ())
-      handle exn =>
-       (put ("Exception- " ^ General.exnMessage exn ^ " raised");
-        error (output ()); raise exn);
-  in if verbose then print (output ()) else () end;
-
-fun use_file context verbose name =
-  let
-    val instream = TextIO.openIn name;
-    val txt = Exn.release (Exn.capture TextIO.inputAll instream before TextIO.closeIn instream);
-  in use_text context (1, name) verbose txt end;
-
-end;
-
-use "ML-Systems/polyml_pp.ML";
-
--- a/src/Pure/ML-Systems/polyml_common.ML	Mon Jun 01 09:26:28 2009 +0200
+++ b/src/Pure/ML-Systems/polyml_common.ML	Tue Jun 02 12:18:08 2009 +0200
@@ -1,6 +1,6 @@
 (*  Title:      Pure/ML-Systems/polyml_common.ML
 
-Compatibility file for Poly/ML -- common part for 4.x and 5.x.
+Compatibility file for Poly/ML -- common part for 5.x.
 *)
 
 exception Interrupt = SML90.Interrupt;
@@ -28,13 +28,7 @@
 
 (* old Poly/ML emulation *)
 
-local
-  val orig_exit = exit;
-in
-  open PolyML;
-  val exit = orig_exit;
-  fun quit () = exit 0;
-end;
+fun quit () = exit 0;
 
 
 (* restore old-style character / string functions *)
@@ -83,6 +77,8 @@
   fun print_depth n = (depth := n; PolyML.print_depth n);
 end;
 
+val error_depth = PolyML.error_depth;
+
 
 
 (** interrupts **)
@@ -134,7 +130,12 @@
   | SOME txt => txt);
 
 
-(* profile execution *)
+
+(** Runtime system **)
+
+val exception_trace = PolyML.exception_trace;
+val timing = PolyML.timing;
+val profiling = PolyML.profiling;
 
 fun profile 0 f x = f x
   | profile n f x =
--- a/src/Pure/ML-Systems/polyml_old_basis.ML	Mon Jun 01 09:26:28 2009 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,29 +0,0 @@
-(*  Title:      Pure/ML-Systems/polyml_old_basis.ML
-
-Fixes for the old SML basis library (before Poly/ML 4.2.0).
-*)
-
-structure String =
-struct
-  fun isSuffix s1 s2 =
-    let val n1 = size s1 and n2 = size s2
-    in if n1 = n2 then s1 = s2 else n1 <= n2 andalso String.substring (s2, n2 - n1, n1) = s1 end;
-  fun isSubstring s1 s2 =
-    String.isPrefix s1 s2 orelse
-      size s1 < size s2 andalso isSubstring s1 (String.extract (s2, 1, NONE)); 
-  open String;
-end;
-
-structure Substring =
-struct
-  open Substring;
-  val full = all;
-end;
-
-structure TextIO =
-struct
-  open TextIO;
-  fun inputLine is =
-    let val s = TextIO.inputLine is
-    in if s = "" then NONE else SOME s end;
-end;
--- a/src/Pure/ML-Systems/polyml_old_compiler4.ML	Mon Jun 01 09:26:28 2009 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,32 +0,0 @@
-(*  Title:      Pure/ML-Systems/polyml_old_compiler4.ML
-
-Runtime compilation -- for old PolyML.compiler (version 4.x).
-*)
-
-fun use_text ({tune_source, print, error, ...}: use_context) (line: int, name) verbose txt =
-  let
-    val in_buffer = ref (explode (tune_source txt));
-    val out_buffer = ref ([]: string list);
-    fun output () = implode (rev (case ! out_buffer of "\n" :: cs => cs | cs => cs));
-
-    fun get () =
-      (case ! in_buffer of
-        [] => ""
-      | c :: cs => (in_buffer := cs; c));
-    fun put s = out_buffer := s :: ! out_buffer;
-
-    fun exec () =
-      (case ! in_buffer of
-        [] => ()
-      | _ => (PolyML.compiler (get, put) (); exec ()));
-  in
-    exec () handle exn =>
-      (error ((if name = "" then "" else "Error in " ^ name ^ "\n") ^ output ()); raise exn);
-    if verbose then print (output ()) else ()
-  end;
-
-fun use_file context verbose name =
-  let
-    val instream = TextIO.openIn name;
-    val txt = Exn.release (Exn.capture TextIO.inputAll instream before TextIO.closeIn instream);
-  in use_text context (1, name) verbose txt end;
--- a/src/Pure/ML-Systems/polyml_old_compiler5.ML	Mon Jun 01 09:26:28 2009 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,32 +0,0 @@
-(*  Title:      Pure/ML-Systems/polyml_old_compiler5.ML
-
-Runtime compilation -- for old PolyML.compilerEx (version 5.0, 5.1).
-*)
-
-fun use_text ({tune_source, print, error, ...}: use_context) (line, name) verbose txt =
-  let
-    val in_buffer = ref (explode (tune_source txt));
-    val out_buffer = ref ([]: string list);
-    fun output () = implode (rev (case ! out_buffer of "\n" :: cs => cs | cs => cs));
-
-    val current_line = ref line;
-    fun get () =
-      (case ! in_buffer of
-        [] => ""
-      | c :: cs => (in_buffer := cs; if c = "\n" then current_line := ! current_line + 1 else (); c));
-    fun put s = out_buffer := s :: ! out_buffer;
-
-    fun exec () =
-      (case ! in_buffer of
-        [] => ()
-      | _ => (PolyML.compilerEx (get, put, fn () => ! current_line, name) (); exec ()));
-  in
-    exec () handle exn => (error (output ()); raise exn);
-    if verbose then print (output ()) else ()
-  end;
-
-fun use_file context verbose name =
-  let
-    val instream = TextIO.openIn name;
-    val txt = Exn.release (Exn.capture TextIO.inputAll instream before TextIO.closeIn instream);
-  in use_text context (1, name) verbose txt end;
--- a/src/Pure/ML-Systems/polyml_pp.ML	Mon Jun 01 09:26:28 2009 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,20 +0,0 @@
-(*  Title:      Pure/ML-Systems/polyml_pp.ML
-
-Toplevel pretty printing for Poly/ML before 5.3.
-*)
-
-fun ml_pprint (print, begin_blk, brk, end_blk) =
-  let
-    fun str "" = ()
-      | str s = print s;
-    fun pprint (ML_Pretty.Block ((bg, en), prts, ind)) =
-          (str bg; begin_blk (ind, false); List.app pprint prts; end_blk (); str en)
-      | pprint (ML_Pretty.String (s, _)) = str s
-      | pprint (ML_Pretty.Break (false, wd)) = brk (wd, 0)
-      | pprint (ML_Pretty.Break (true, _)) = brk (99999, 0);
-  in pprint end;
-
-fun toplevel_pp context (_: string list) pp =
-  use_text context (1, "pp") false
-    ("install_pp (fn args => fn _ => fn _ => ml_pprint args o Pretty.to_ML o (" ^ pp ^ "))");
-
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/Pure/ML-Systems/pp_polyml.ML	Tue Jun 02 12:18:08 2009 +0200
@@ -0,0 +1,20 @@
+(*  Title:      Pure/ML-Systems/pp_polyml.ML
+
+Toplevel pretty printing for Poly/ML before 5.3.
+*)
+
+fun ml_pprint (print, begin_blk, brk, end_blk) =
+  let
+    fun str "" = ()
+      | str s = print s;
+    fun pprint (ML_Pretty.Block ((bg, en), prts, ind)) =
+          (str bg; begin_blk (ind, false); List.app pprint prts; end_blk (); str en)
+      | pprint (ML_Pretty.String (s, _)) = str s
+      | pprint (ML_Pretty.Break (false, wd)) = brk (wd, 0)
+      | pprint (ML_Pretty.Break (true, _)) = brk (99999, 0);
+  in pprint end;
+
+fun toplevel_pp context (_: string list) pp =
+  use_text context (1, "pp") false
+    ("PolyML.install_pp (fn args => fn _ => fn _ => ml_pprint args o Pretty.to_ML o (" ^ pp ^ "))");
+
--- a/src/Pure/ML-Systems/smlnj.ML	Mon Jun 01 09:26:28 2009 +0200
+++ b/src/Pure/ML-Systems/smlnj.ML	Tue Jun 02 12:18:08 2009 +0200
@@ -92,12 +92,6 @@
 (*dummy implementation*)
 fun exception_trace f = f ();
 
-(*dummy implementation*)
-fun print x = x;
-
-(*dummy implementation*)
-fun makestring x = "dummy string for SML New Jersey";
-
 
 (* ML command execution *)
 
--- a/src/Pure/ML/ml_test.ML	Mon Jun 01 09:26:28 2009 +0200
+++ b/src/Pure/ML/ml_test.ML	Tue Jun 02 12:18:08 2009 +0200
@@ -1,7 +1,7 @@
 (*  Title:      Pure/ML/ml_test.ML
     Author:     Makarius
 
-Test of advanced ML compiler invocation in Poly/ML 5.3 (SVN 719).
+Test of advanced ML compiler invocation in Poly/ML 5.3 (SVN 744).
 *)
 
 signature ML_TEST =
@@ -35,7 +35,7 @@
   in (regs, context') end;
 
 fun position_of ctxt
-    ({file, startLine = line, startPosition = i, endPosition = j, ...}: location) =
+    ({file, startLine = line, startPosition = i, endPosition = j, ...}: PolyML.location) =
   (case pairself (Inttab.lookup (Extra_Env.get (Context.Proof ctxt))) (i, j) of
     (SOME pos1, SOME pos2) => Position.encode_range (pos1, pos2)
   | (SOME pos, NONE) => pos
@@ -44,18 +44,18 @@
 
 (* parse trees *)
 
-fun report_parse_tree context depth =
+fun report_parse_tree context depth space =
   let
     val pos_of = position_of (Context.proof_of context);
-    fun report loc (PTtype types) =
-          PolyML.NameSpace.displayTypeExpression (types, depth)
+    fun report loc (PolyML.PTtype types) =
+          PolyML.NameSpace.displayTypeExpression (types, depth, space)
           |> pretty_ml |> Pretty.from_ML |> Pretty.string_of
           |> Position.report_text Markup.ML_typing (pos_of loc)
-      | report loc (PTdeclaredAt decl) =
+      | report loc (PolyML.PTdeclaredAt decl) =
           Markup.markup (Markup.properties (Position.properties_of (pos_of decl)) Markup.ML_def) ""
           |> Position.report_text Markup.ML_ref (pos_of loc)
-      | report _ (PTnextSibling tree) = report_tree (tree ())
-      | report _ (PTfirstChild tree) = report_tree (tree ())
+      | report _ (PolyML.PTnextSibling tree) = report_tree (tree ())
+      | report _ (PolyML.PTfirstChild tree) = report_tree (tree ())
       | report _ _ = ()
     and report_tree (loc, props) = List.app (report loc) props;
   in report_tree end;
@@ -132,7 +132,7 @@
 
     fun result_fun (phase1, phase2) () =
      (case phase1 of NONE => ()
-      | SOME parse_tree => report_parse_tree (the (Context.thread_data ())) depth parse_tree;
+      | SOME parse_tree => report_parse_tree (the (Context.thread_data ())) depth space parse_tree;
       case phase2 of NONE => error "Static Errors"
       | SOME code => apply_result (Toplevel.program code));
 
--- a/src/Pure/meta_simplifier.ML	Mon Jun 01 09:26:28 2009 +0200
+++ b/src/Pure/meta_simplifier.ML	Tue Jun 02 12:18:08 2009 +0200
@@ -158,11 +158,6 @@
   Thm.eq_thm_prop (thm1, thm2);
 
 
-(* congruences *)
-
-val eq_cong = Thm.eq_thm_prop
-
-
 (* simplification sets, procedures, and solvers *)
 
 (*A simpset contains data required during conversion:
@@ -785,7 +780,7 @@
       val prems' = merge Thm.eq_thm_prop (prems1, prems2);
       val bounds' = if #1 bounds1 < #1 bounds2 then bounds2 else bounds1;
       val depth' = if #1 depth1 < #1 depth2 then depth2 else depth1;
-      val congs' = merge (eq_cong o pairself #2) (congs1, congs2);
+      val congs' = merge (Thm.eq_thm_prop o pairself #2) (congs1, congs2);
       val weak' = merge (op =) (weak1, weak2);
       val procs' = Net.merge eq_proc (procs1, procs2);
       val loop_tacs' = AList.merge (op =) (K true) (loop_tacs1, loop_tacs2);
--- a/src/Pure/mk	Mon Jun 01 09:26:28 2009 +0200
+++ b/src/Pure/mk	Tue Jun 02 12:18:08 2009 +0200
@@ -114,7 +114,7 @@
     -e "val ml_platform = \"$ML_PLATFORM\";" \
     -e "(use\"$COMPAT\"; use\"ROOT.ML\") handle _ => exit 1;" \
     -e "ml_prompts \"ML> \" \"ML# \";" \
-    -f -c -q -w RAW_ML_SYSTEM Pure > "$LOG" 2>&1
+    -f -q -w RAW_ML_SYSTEM Pure > "$LOG" 2>&1
   RC="$?"
 fi
 
--- a/src/Pure/simplifier.ML	Mon Jun 01 09:26:28 2009 +0200
+++ b/src/Pure/simplifier.ML	Tue Jun 02 12:18:08 2009 +0200
@@ -348,16 +348,7 @@
 
 
 
-(** proof methods **)
-
-(* simplification *)
-
-val simp_options =
- (Args.parens (Args.$$$ no_asmN) >> K simp_tac ||
-  Args.parens (Args.$$$ no_asm_simpN) >> K asm_simp_tac ||
-  Args.parens (Args.$$$ no_asm_useN) >> K full_simp_tac ||
-  Args.parens (Args.$$$ asm_lrN) >> K asm_lr_simp_tac ||
-  Scan.succeed asm_full_simp_tac);
+(** method syntax **)
 
 val cong_modifiers =
  [Args.$$$ congN -- Args.colon >> K ((I, cong_add): Method.modifier),
@@ -379,25 +370,33 @@
     >> K (Context.proof_map (map_ss MetaSimplifier.clear_ss), simp_add)]
    @ cong_modifiers;
 
-fun simp_args more_mods =
-  Method.sectioned_args (Args.bang_facts -- Scan.lift simp_options)
-    (more_mods @ simp_modifiers');
+val simp_options =
+ (Args.parens (Args.$$$ no_asmN) >> K simp_tac ||
+  Args.parens (Args.$$$ no_asm_simpN) >> K asm_simp_tac ||
+  Args.parens (Args.$$$ no_asm_useN) >> K full_simp_tac ||
+  Args.parens (Args.$$$ asm_lrN) >> K asm_lr_simp_tac ||
+  Scan.succeed asm_full_simp_tac);
 
-fun simp_method (prems, tac) ctxt = METHOD (fn facts =>
-  ALLGOALS (Method.insert_tac (prems @ facts)) THEN
-    (CHANGED_PROP o ALLGOALS o tac) (local_simpset_of ctxt));
-
-fun simp_method' (prems, tac) ctxt = METHOD (fn facts =>
-  HEADGOAL (Method.insert_tac (prems @ facts) THEN'
-      ((CHANGED_PROP) oo tac) (local_simpset_of ctxt)));
+fun simp_method more_mods meth =
+  Args.bang_facts -- Scan.lift simp_options --|
+    Method.sections (more_mods @ simp_modifiers') >>
+    (fn (prems, tac) => fn ctxt => METHOD (fn facts => meth ctxt tac (prems @ facts)));
 
 
 
 (** setup **)
 
-fun method_setup more_mods = Method.add_methods
- [(simpN, simp_args more_mods simp_method', "simplification"),
-  ("simp_all", simp_args more_mods simp_method, "simplification (all goals)")];
+fun method_setup more_mods =
+  Method.setup (Binding.name simpN)
+    (simp_method more_mods (fn ctxt => fn tac => fn facts =>
+      HEADGOAL (Method.insert_tac facts THEN'
+        (CHANGED_PROP oo tac) (local_simpset_of ctxt))))
+    "simplification" #>
+  Method.setup (Binding.name "simp_all")
+    (simp_method more_mods (fn ctxt => fn tac => fn facts =>
+      ALLGOALS (Method.insert_tac facts) THEN
+        (CHANGED_PROP o ALLGOALS o tac) (local_simpset_of ctxt)))
+    "simplification (all goals)";
 
 fun easy_setup reflect trivs = method_setup [] #> Context.theory_map (map_ss (fn _ =>
   let
--- a/src/Tools/Compute_Oracle/am_sml.ML	Mon Jun 01 09:26:28 2009 +0200
+++ b/src/Tools/Compute_Oracle/am_sml.ML	Tue Jun 02 12:18:08 2009 +0200
@@ -320,7 +320,7 @@
 		val strict_args = (case toplevel_arity_of c of NONE => the (arity_of c) | SOME sa => sa)
 		val xs = map (fn n => if n < strict_args then "x"^(str n) else "x"^(str n)^"()") rightargs
 		val right = (indexed "C" c)^" "^(string_of_tuple xs)
-		val message = "(\"unresolved lazy call: "^(string_of_int c)^", \"^(makestring x"^(string_of_int (strict_args - 1))^"))"		
+		val message = "(\"unresolved lazy call: " ^ string_of_int c ^ "\")"
 		val right = if strict_args < the (arity_of c) then "raise AM_SML.Run "^message else right		
 	    in
 		(indexed "c" c)^(if gnum > 0 then "_"^(str gnum) else "")^leftargs^" = "^right
--- a/src/Tools/Compute_Oracle/compute.ML	Mon Jun 01 09:26:28 2009 +0200
+++ b/src/Tools/Compute_Oracle/compute.ML	Tue Jun 02 12:18:08 2009 +0200
@@ -379,7 +379,11 @@
         fun has_witness s = not (null (Sign.witness_sorts thy [] [s]))
         val shyptab = fold Sorttab.delete (filter has_witness (Sorttab.keys (shyptab))) shyptab
         val shyps = if Sorttab.is_empty shyptab then [] else Sorttab.keys (fold delete_term (prop::hyps) shyptab)
-        val _ = if not (null shyps) then raise Compute ("dangling sort hypotheses: "^(makestring shyps)) else ()
+        val _ =
+          if not (null shyps) then
+            raise Compute ("dangling sort hypotheses: " ^
+              commas (map (Syntax.string_of_sort_global thy) shyps))
+          else ()
     in
         Thm.cterm_of thy (fold_rev (fn hyp => fn p => Logic.mk_implies (hyp, p)) hyps prop)
     end)));
@@ -610,7 +614,8 @@
             case match_aterms varsubst b' a' of
                 NONE => 
                 let
-                    fun mk s = makestring (infer_types (naming_of computer) (encoding_of computer) ty s)
+                    fun mk s = Syntax.string_of_term_global Pure.thy
+                      (infer_types (naming_of computer) (encoding_of computer) ty s)
                     val left = "computed left side: "^(mk a')
                     val right = "computed right side: "^(mk b')
                 in
--- a/src/Tools/coherent.ML	Mon Jun 01 09:26:28 2009 +0200
+++ b/src/Tools/coherent.ML	Tue Jun 02 12:18:08 2009 +0200
@@ -1,6 +1,6 @@
 (*  Title:      Tools/coherent.ML
     Author:     Stefan Berghofer, TU Muenchen
-    Author:     Marc Bezem, Institutt for Informatikk, Universitetet i Bergen 
+    Author:     Marc Bezem, Institutt for Informatikk, Universitetet i Bergen
 
 Prover for coherent logic, see e.g.
 
@@ -22,14 +22,15 @@
 sig
   val verbose: bool ref
   val show_facts: bool ref
-  val coherent_tac: thm list -> Proof.context -> int -> tactic
-  val coherent_meth: thm list -> Proof.context -> Proof.method
+  val coherent_tac: Proof.context -> thm list -> int -> tactic
   val setup: theory -> theory
 end;
 
 functor CoherentFun(Data: COHERENT_DATA) : COHERENT =
 struct
 
+(** misc tools **)
+
 val verbose = ref false;
 
 fun message f = if !verbose then tracing (f ()) else ();
@@ -170,6 +171,7 @@
           | SOME prfs => SOME ((params, prf) :: prfs))
       end;
 
+
 (** proof replaying **)
 
 fun thm_of_cl_prf thy goal asms (ClPrf (th, (tye, env), insts, is, prfs)) =
@@ -210,7 +212,7 @@
 
 (** external interface **)
 
-fun coherent_tac rules ctxt = SUBPROOF (fn {prems, concl, params, context, ...} =>
+fun coherent_tac ctxt rules = SUBPROOF (fn {prems, concl, params, context, ...} =>
   rtac (rulify_elim_conv concl RS equal_elim_rule2) 1 THEN
   SUBPROOF (fn {prems = prems', concl, context, ...} =>
     let val xs = map term_of params @
@@ -224,10 +226,9 @@
            rtac (thm_of_cl_prf (ProofContext.theory_of context) concl [] prf) 1
     end) context 1) ctxt;
 
-fun coherent_meth rules ctxt =
-  METHOD (fn facts => coherent_tac (facts @ rules) ctxt 1);
-
-val setup = Method.add_method
-  ("coherent", Method.thms_ctxt_args coherent_meth, "prove coherent formula");
+val setup = Method.setup @{binding coherent}
+  (Attrib.thms >> (fn rules => fn ctxt =>
+      METHOD (fn facts => HEADGOAL (coherent_tac ctxt (facts @ rules)))))
+    "prove coherent formula";
 
 end;
--- a/src/Tools/eqsubst.ML	Mon Jun 01 09:26:28 2009 +0200
+++ b/src/Tools/eqsubst.ML	Tue Jun 02 12:18:08 2009 +0200
@@ -20,25 +20,25 @@
        * Zipper.T (* focusterm to search under *)
 
     exception eqsubst_occL_exp of
-       string * int list * Thm.thm list * int * Thm.thm
+       string * int list * thm list * int * thm
     
     (* low level substitution functions *)
     val apply_subst_in_asm :
        int ->
-       Thm.thm ->
-       Thm.thm ->
-       (Thm.cterm list * int * 'a * Thm.thm) * match -> Thm.thm Seq.seq
+       thm ->
+       thm ->
+       (cterm list * int * 'a * thm) * match -> thm Seq.seq
     val apply_subst_in_concl :
        int ->
-       Thm.thm ->
-       Thm.cterm list * Thm.thm ->
-       Thm.thm -> match -> Thm.thm Seq.seq
+       thm ->
+       cterm list * thm ->
+       thm -> match -> thm Seq.seq
 
     (* matching/unification within zippers *)
     val clean_match_z :
-       Context.theory -> Term.term -> Zipper.T -> match option
+       theory -> term -> Zipper.T -> match option
     val clean_unify_z :
-       Context.theory -> int -> Term.term -> Zipper.T -> match Seq.seq
+       theory -> int -> term -> Zipper.T -> match Seq.seq
 
     (* skipping things in seq seq's *)
 
@@ -57,65 +57,64 @@
     (* tactics *)
     val eqsubst_asm_tac :
        Proof.context ->
-       int list -> Thm.thm list -> int -> Thm.thm -> Thm.thm Seq.seq
+       int list -> thm list -> int -> tactic
     val eqsubst_asm_tac' :
        Proof.context ->
-       (searchinfo -> int -> Term.term -> match skipseq) ->
-       int -> Thm.thm -> int -> Thm.thm -> Thm.thm Seq.seq
+       (searchinfo -> int -> term -> match skipseq) ->
+       int -> thm -> int -> tactic
     val eqsubst_tac :
        Proof.context ->
        int list -> (* list of occurences to rewrite, use [0] for any *)
-       Thm.thm list -> int -> Thm.thm -> Thm.thm Seq.seq
+       thm list -> int -> tactic
     val eqsubst_tac' :
        Proof.context -> (* proof context *)
-       (searchinfo -> Term.term -> match Seq.seq) (* search function *)
-       -> Thm.thm (* equation theorem to rewrite with *)
+       (searchinfo -> term -> match Seq.seq) (* search function *)
+       -> thm (* equation theorem to rewrite with *)
        -> int (* subgoal number in goal theorem *)
-       -> Thm.thm (* goal theorem *)
-       -> Thm.thm Seq.seq (* rewritten goal theorem *)
+       -> thm (* goal theorem *)
+       -> thm Seq.seq (* rewritten goal theorem *)
 
 
     val fakefree_badbounds :
-       (string * Term.typ) list ->
-       Term.term ->
-       (string * Term.typ) list * (string * Term.typ) list * Term.term
+       (string * typ) list ->
+       term ->
+       (string * typ) list * (string * typ) list * term
 
     val mk_foo_match :
-       (Term.term -> Term.term) ->
-       ('a * Term.typ) list -> Term.term -> Term.term
+       (term -> term) ->
+       ('a * typ) list -> term -> term
 
     (* preparing substitution *)
-    val prep_meta_eq : Proof.context -> Thm.thm -> Thm.thm list
+    val prep_meta_eq : Proof.context -> thm -> thm list
     val prep_concl_subst :
-       int -> Thm.thm -> (Thm.cterm list * Thm.thm) * searchinfo
+       int -> thm -> (cterm list * thm) * searchinfo
     val prep_subst_in_asm :
-       int -> Thm.thm -> int ->
-       (Thm.cterm list * int * int * Thm.thm) * searchinfo
+       int -> thm -> int ->
+       (cterm list * int * int * thm) * searchinfo
     val prep_subst_in_asms :
-       int -> Thm.thm ->
-       ((Thm.cterm list * int * int * Thm.thm) * searchinfo) list
+       int -> thm ->
+       ((cterm list * int * int * thm) * searchinfo) list
     val prep_zipper_match :
-       Zipper.T -> Term.term * ((string * Term.typ) list * (string * Term.typ) list * Term.term)
+       Zipper.T -> term * ((string * typ) list * (string * typ) list * term)
 
     (* search for substitutions *)
     val valid_match_start : Zipper.T -> bool
     val search_lr_all : Zipper.T -> Zipper.T Seq.seq
     val search_lr_valid : (Zipper.T -> bool) -> Zipper.T -> Zipper.T Seq.seq
     val searchf_lr_unify_all :
-       searchinfo -> Term.term -> match Seq.seq Seq.seq
+       searchinfo -> term -> match Seq.seq Seq.seq
     val searchf_lr_unify_valid :
-       searchinfo -> Term.term -> match Seq.seq Seq.seq
+       searchinfo -> term -> match Seq.seq Seq.seq
     val searchf_bt_unify_valid :
-       searchinfo -> Term.term -> match Seq.seq Seq.seq
+       searchinfo -> term -> match Seq.seq Seq.seq
 
     (* syntax tools *)
     val ith_syntax : int list parser
     val options_syntax : bool parser
 
     (* Isar level hooks *)
-    val eqsubst_asm_meth : Proof.context -> int list -> Thm.thm list -> Proof.method
-    val eqsubst_meth : Proof.context -> int list -> Thm.thm list -> Proof.method
-    val subst_meth : Method.src -> Proof.context -> Proof.method
+    val eqsubst_asm_meth : Proof.context -> int list -> thm list -> Proof.method
+    val eqsubst_meth : Proof.context -> int list -> thm list -> Proof.method
     val setup : theory -> theory
 
 end;
@@ -560,15 +559,13 @@
     Scan.optional (Args.parens (Scan.repeat OuterParse.nat)) [0];
 
 (* combination method that takes a flag (true indicates that subst
-should be done to an assumption, false = apply to the conclusion of
-the goal) as well as the theorems to use *)
-fun subst_meth src =
-  Method.syntax ((Scan.lift options_syntax) -- (Scan.lift ith_syntax) -- Attrib.thms) src
-  #> (fn (((asmflag, occL), inthms), ctxt) =>
-    (if asmflag then eqsubst_asm_meth else eqsubst_meth) ctxt occL inthms);
-
-
+   should be done to an assumption, false = apply to the conclusion of
+   the goal) as well as the theorems to use *)
 val setup =
-  Method.add_method ("subst", subst_meth, "single-step substitution");
+  Method.setup @{binding subst}
+    (Scan.lift (options_syntax -- ith_syntax) -- Attrib.thms >>
+      (fn ((asmflag, occL), inthms) => fn ctxt =>
+        (if asmflag then eqsubst_asm_meth else eqsubst_meth) ctxt occL inthms))
+    "single-step substitution";
 
 end;
--- a/src/Tools/intuitionistic.ML	Mon Jun 01 09:26:28 2009 +0200
+++ b/src/Tools/intuitionistic.ML	Tue Jun 02 12:18:08 2009 +0200
@@ -7,7 +7,7 @@
 signature INTUITIONISTIC =
 sig
   val prover_tac: Proof.context -> int option -> int -> tactic
-  val method_setup: bstring -> theory -> theory
+  val method_setup: binding -> theory -> theory
 end;
 
 structure Intuitionistic: INTUITIONISTIC =
@@ -84,15 +84,16 @@
   modifier introN Args.colon (Scan.succeed ()) ContextRules.intro,
   Args.del -- Args.colon >> K (I, ContextRules.rule_del)];
 
-val method =
-  Method.bang_sectioned_args' modifiers (Scan.lift (Scan.option OuterParse.nat))
-    (fn n => fn prems => fn ctxt => METHOD (fn facts =>
-      HEADGOAL (Method.insert_tac (prems @ facts) THEN'
-      ObjectLogic.atomize_prems_tac THEN' prover_tac ctxt n)));
-
 in
 
-fun method_setup name = Method.add_method (name, method, "intuitionistic proof search");
+fun method_setup name =
+  Method.setup name
+    (Args.bang_facts -- Scan.lift (Scan.option OuterParse.nat) --|
+      Method.sections modifiers >>
+      (fn (prems, n) => fn ctxt => METHOD (fn facts =>
+        HEADGOAL (Method.insert_tac (prems @ facts) THEN'
+        ObjectLogic.atomize_prems_tac THEN' prover_tac ctxt n))))
+    "intuitionistic proof search";
 
 end;