[project @ 2001-02-15 17:33:53 by simonmar]
[ghc-hetmet.git] / ghc / docs / users_guide / glasgow_exts.sgml
index 6cbb5fe..bedbc08 100644 (file)
@@ -12,9 +12,7 @@ the underlying facilities with which we implement Haskell.  Thus, you
 can get at the Raw Iron, if you are willing to write some non-standard
 code at a more primitive level.  You need not be “stuck” on
 performance because of the implementation costs of Haskell's
-“high-level” features—you can always code “under” them.  In an
-extreme case, you can write all your time-critical code in C, and then
-just glue it together with Haskell!
+“high-level” features—you can always code “under” them.  In an extreme case, you can write all your time-critical code in C, and then just glue it together with Haskell!
 </Para>
 
 <Para>
@@ -78,11 +76,20 @@ for some nested declarations, where this would not be legal in Haskell
 </VarListEntry>
 
 <VarListEntry>
-<Term>Calling out to C:</Term>
+<Term>Pattern guards</Term>
+<ListItem>
+<Para>
+Instead of being a boolean expression, a guard is a list of qualifiers, exactly as in a list comprehension. See <XRef LinkEnd="pattern-guards">.
+</Para>
+</ListItem>
+</VarListEntry>
+
+<VarListEntry>
+<Term>Foreign calling:</Term>
 <ListItem>
 <Para>
 Just what it sounds like.  We provide <Emphasis>lots</Emphasis> of rope that you
-can dangle around your neck.  Please see <XRef LinkEnd="glasgow-ccalls">.
+can dangle around your neck.  Please see <XRef LinkEnd="ffi">.
 </Para>
 </ListItem>
 </VarListEntry>
@@ -107,6 +114,20 @@ Details in <XRef LinkEnd="rewrite-rules">.
 </Para>
 </ListItem>
 </VarListEntry>
+
+<VarListEntry>
+<Term>Generic classes:</Term>
+<ListItem>
+<Para>
+Generic class declarations allow you to define a class
+whose methods say how to work over an arbitrary data type.
+Then it's really easy to make any new type into an instance of
+the class.  This generalises the rather ad-hoc "deriving" feature
+of Haskell 98.
+Details in <XRef LinkEnd="generic-classes">.
+</Para>
+</ListItem>
+</VarListEntry>
 </VariableList>
 </Para>
 
@@ -118,6 +139,144 @@ program), you may wish to check if there are libraries that provide a
 <xref linkend="book-hslibs">.
 </Para>
 
+  <sect1 id="options-language">
+    <title>Language options</title>
+
+    <indexterm><primary>language</primary><secondary>option</secondary>
+    </indexterm>
+    <indexterm><primary>options</primary><secondary>language</secondary>
+    </indexterm>
+    <indexterm><primary>extensions</primary><secondary>options controlling</secondary>
+    </indexterm>
+
+    <para> These flags control what variation of the language are
+    permitted.  Leaving out all of them gives you standard Haskell
+    98.</Para>
+
+    <variablelist>
+
+      <varlistentry>
+       <term><option>-fglasgow-exts</option>:</term>
+       <indexterm><primary><option>-fglasgow-exts</option></primary></indexterm>
+       <listitem>
+         <para>This simultaneously enables all of the extensions to
+          Haskell 98 described in <xref
+          linkend="ghc-language-features">, except where otherwise
+          noted. </para>
+       </listitem>
+      </varlistentry>
+
+      <varlistentry>
+       <term><option>-fno-monomorphism-restriction</option>:</term>
+       <indexterm><primary><option>-fno-monomorphism-restriction</option></primary></indexterm>
+       <listitem>
+         <para> Switch off the Haskell 98 monomorphism restriction.
+          Independent of the <Option>-fglasgow-exts</Option>
+          flag. </para>
+       </listitem>
+      </varlistentry>
+
+      <varlistentry>
+       <term><option>-fallow-overlapping-instances</option></term>
+       <term><option>-fallow-undecidable-instances</option></term>
+       <term><option>-fcontext-stack</option></term>
+       <indexterm><primary><option>-fallow-overlapping-instances</option></primary></indexterm>
+       <indexterm><primary><option>-fallow-undecidable-instances</option></primary></indexterm>
+       <indexterm><primary><option>-fcontext-stack</option></primary></indexterm>
+       <listitem>
+         <para> See <XRef LinkEnd="instance-decls">.  Only relevant
+          if you also use <option>-fglasgow-exts</option>.</para>
+       </listitem>
+      </varlistentry>
+
+      <varlistentry>
+       <term><option>-fignore-asserts</option>:</term>
+       <indexterm><primary><option>-fignore-asserts</option></primary></indexterm>
+       <listitem>
+         <para>See <XRef LinkEnd="sec-assertions">.  Only relevant if
+          you also use <option>-fglasgow-exts</option>.</Para>
+       </listitem>
+      </varlistentry>
+
+      <varlistentry>
+       <term><option>-finline-phase</option></term>
+       <indexterm><primary><option>-finline-phase</option></primary></indexterm>
+       <listitem>
+         <para>See <XRef LinkEnd="rewrite-rules">.  Only relevant if
+          you also use <Option>-fglasgow-exts</Option>.</para>
+       </listitem>
+      </varlistentry>
+
+      <varlistentry>
+       <term><option>-fgenerics</option></term>
+       <indexterm><primary><option>-fgenerics</option></primary></indexterm>
+       <listitem>
+         <para>See <XRef LinkEnd="generic-classes">.  Independent of
+          <Option>-fglasgow-exts</Option>.</para>
+       </listitem>
+      </varlistentry>
+
+       <varlistentry>
+         <term><option>-fno-implicit-prelude</option></term>
+         <listitem>
+           <para><indexterm><primary>-fno-implicit-prelude
+            option</primary></indexterm> GHC normally imports
+            <filename>Prelude.hi</filename> files for you.  If you'd
+            rather it didn't, then give it a
+            <option>-fno-implicit-prelude</option> option.  The idea
+            is that you can then import a Prelude of your own.  (But
+            don't call it <literal>Prelude</literal>; the Haskell
+            module namespace is flat, and you must not conflict with
+            any Prelude module.)</para>
+
+           <para>Even though you have not imported the Prelude, all
+            the built-in syntax still refers to the built-in Haskell
+            Prelude types and values, as specified by the Haskell
+            Report.  For example, the type <literal>[Int]</literal>
+            still means <literal>Prelude.[] Int</literal>; tuples
+            continue to refer to the standard Prelude tuples; the
+            translation for list comprehensions continues to use
+            <literal>Prelude.map</literal> etc.</para>
+
+           <para> With one group of exceptions!  You may want to
+            define your own numeric class hierarchy.  It completely
+            defeats that purpose if the literal "1" means
+            "<literal>Prelude.fromInteger 1</literal>", which is what
+            the Haskell Report specifies.  So the
+            <option>-fno-implicit-prelude</option> flag causes the
+            following pieces of built-in syntax to refer to whatever
+            is in scope, not the Prelude versions:</para>
+
+           <itemizedlist>
+             <listitem>
+               <para>Integer and fractional literals mean
+                "<literal>fromInteger 1</literal>" and
+                "<literal>fromRational 3.2</literal>", not the
+                Prelude-qualified versions; both in expressions and in
+                patterns.</para>
+             </listitem>
+
+             <listitem>
+               <para>Negation (e.g. "<literal>- (f x)</literal>")
+               means "<literal>negate (f x)</literal>" (not
+               <literal>Prelude.negate</literal>).</para>
+             </listitem>
+
+             <listitem>
+               <para>In an n+k pattern, the standard Prelude
+                <literal>Ord</literal> class is used for comparison,
+                but the necessary subtraction uses whatever
+                "<literal>(-)</literal>" is in scope (not
+                "<literal>Prelude.(-)</literal>").</para>
+             </listitem>
+           </itemizedlist>
+
+         </listitem>
+       </varlistentry>
+
+    </variablelist>
+  </sect1>
+
 <Sect1 id="primitives">
 <Title>Unboxed types and primitive operations
 </Title>
@@ -302,8 +461,8 @@ Note: we may relax some of these restrictions in the future.
 </Para>
 
 <Para>
-The <Literal>IO</Literal> and <Literal>ST</Literal> monads use unboxed tuples to avoid unnecessary
-allocation during sequences of operations.
+The <Literal>IO</Literal> and <Literal>ST</Literal> monads use unboxed
+tuples to avoid unnecessary allocation during sequences of operations.
 </Para>
 
 </Sect2>
@@ -311,16 +470,14 @@ allocation during sequences of operations.
 <Sect2>
 <Title>Character and numeric types</Title>
 
-<Para>
 <IndexTerm><Primary>character types, primitive</Primary></IndexTerm>
 <IndexTerm><Primary>numeric types, primitive</Primary></IndexTerm>
 <IndexTerm><Primary>integer types, primitive</Primary></IndexTerm>
 <IndexTerm><Primary>floating point types, primitive</Primary></IndexTerm>
+<Para>
 There are the following obvious primitive types:
 </Para>
 
-<Para>
-
 <ProgramListing>
 type Char#
 type Int#
@@ -340,7 +497,6 @@ type Word64#
 <IndexTerm><Primary><literal>Double&num;</literal></Primary></IndexTerm>
 <IndexTerm><Primary><literal>Int64&num;</literal></Primary></IndexTerm>
 <IndexTerm><Primary><literal>Word64&num;</literal></Primary></IndexTerm>
-</Para>
 
 <Para>
 If you really want to know their exact equivalents in C, see
@@ -357,8 +513,8 @@ Literals for these types may be written as follows:
 1#              an Int#
 1.2#            a Float#
 1.34##          a Double#
-'a'#            a Char#; for weird characters, use '\o&#60;octal&#62;'#
-"a"#            an Addr# (a `char *')
+'a'#            a Char#; for weird characters, use e.g. '\o&#60;octal&#62;'#
+"a"#            an Addr# (a `char *'); only characters '\0'..'\255' allowed
 </ProgramListing>
 
 <IndexTerm><Primary>literals, primitive</Primary></IndexTerm>
@@ -1311,7 +1467,7 @@ C.
 </Para>
 
 <Para>
-Please see <XRef LinkEnd="glasgow-stablePtrs"> for more details.
+Please see <XRef LinkEnd="sec-stable-pointers"> for more details.
 </Para>
 </ListItem>
 </VarListEntry>
@@ -1327,7 +1483,7 @@ memory when you're done with it.&rdquo;
 </Para>
 
 <Para>
-Please see <XRef LinkEnd="glasgow-foreignObjs"> for more details.
+Please see <XRef LinkEnd="sec-ForeignObj"> for more details.
 </Para>
 </ListItem>
 </VarListEntry>
@@ -1341,154 +1497,189 @@ The libraries documentatation gives more details on all these
 
 </Sect1>
 
-<Sect1 id="glasgow-ccalls">
-<Title>Calling&nbsp;C directly from Haskell
-</Title>
 
-<Para>
-<IndexTerm><Primary>C calls (Glasgow extension)</Primary></IndexTerm>
-<IndexTerm><Primary>&lowbar;ccall&lowbar; (Glasgow extension)</Primary></IndexTerm>
-<IndexTerm><Primary>&lowbar;casm&lowbar; (Glasgow extension)</Primary></IndexTerm>
-</Para>
+<Sect1 id="pattern-guards">
+<Title>Pattern guards</Title>
 
 <Para>
-GOOD ADVICE: Because this stuff is not Entirely Stable as far as names
-and things go, you would be well-advised to keep your C-callery
-corraled in a few modules, rather than sprinkled all over your code.
-It will then be quite easy to update later on.
-</Para>
-
-<Sect2 id="ccall-intro">
-<Title><Function>&lowbar;ccall&lowbar;</Function> and <Function>&lowbar;casm&lowbar;</Function>: an introduction
-</Title>
-
-<Para>
-The simplest way to use a simple C function
+<IndexTerm><Primary>Pattern guards (Glasgow extension)</Primary></IndexTerm>
+The discussion that follows is an abbreviated version of Simon Peyton Jones's original <ULink URL="http://research.microsoft.com/~simonpj/Haskell/guards.html">proposal</ULink>. (Note that the proposal was written before pattern guards were implemented, so refers to them as unimplemented.)
 </Para>
 
 <Para>
+Suppose we have an abstract data type of finite maps, with a
+lookup operation:
 
 <ProgramListing>
-double fooC( FILE *in, char c, int i, double d, unsigned int u )
+lookup :: FiniteMap -> Int -> Maybe Int
 </ProgramListing>
 
+The lookup returns <Function>Nothing</Function> if the supplied key is not in the domain of the mapping, and <Function>(Just v)</Function> otherwise,
+where <VarName>v</VarName> is the value that the key maps to.  Now consider the following definition:
 </Para>
 
-<Para>
-is to provide a Haskell wrapper:
-</Para>
-
-<Para>
-
 <ProgramListing>
-fooH :: Char -> Int -> Double -> Word -> IO Double
-fooH c i d w = _ccall_ fooC (&ldquo;stdin&rdquo;::Addr) c i d w
+clunky env var1 var2 | ok1 && ok2 = val1 + val2
+| otherwise  = var1 + var2
+where
+  m1 = lookup env var1
+  m2 = lookup env var2
+  ok1 = maybeToBool m1
+  ok2 = maybeToBool m2
+  val1 = expectJust m1
+  val2 = expectJust m2
 </ProgramListing>
 
-</Para>
-
-<Para>
-The function <Function>fooH</Function> unbox all of its arguments, call the C
-function <Function>fooC</Function> and box the corresponding arguments.
-</Para>
-
 <Para>
-One of the annoyances about <Function>&lowbar;ccall&lowbar;</Function>s is when the C types don't quite
-match the Haskell compiler's ideas.  For this, the <Function>&lowbar;casm&lowbar;</Function> variant
-may be just the ticket (NB: <Emphasis>no chance</Emphasis> of such code going
-through a native-code generator):
+The auxiliary functions are 
 </Para>
 
-<Para>
-
 <ProgramListing>
-import Addr
-import CString
+maybeToBool :: Maybe a -&gt; Bool
+maybeToBool (Just x) = True
+maybeToBool Nothing  = False
 
-oldGetEnv name
-  = _casm_ &ldquo;%r = getenv((char *) %0);&rdquo; name >>= \ litstring ->
-    return (
-        if (litstring == nullAddr) then
-            Left ("Fail:oldGetEnv:"++name)
-        else
-            Right (unpackCString litstring)
-    )
+expectJust :: Maybe a -&gt; a
+expectJust (Just x) = x
+expectJust Nothing  = error "Unexpected Nothing"
 </ProgramListing>
 
-</Para>
-
-<Para>
-The first literal-literal argument to a <Function>&lowbar;casm&lowbar;</Function> is like a <Function>printf</Function>
-format: <Literal>&percnt;r</Literal> is replaced with the &ldquo;result,&rdquo; <Literal>&percnt;0</Literal>&ndash;<Literal>&percnt;n-1</Literal> are
-replaced with the 1st&ndash;nth arguments.  As you can see above, it is an
-easy way to do simple C&nbsp;casting.  Everything said about <Function>&lowbar;ccall&lowbar;</Function> goes
-for <Function>&lowbar;casm&lowbar;</Function> as well.
-</Para>
-
 <Para>
-The use of <Function>&lowbar;casm&lowbar;</Function> in your code does pose a problem to the compiler
-when it comes to generating an interface file for a freshly compiled
-module. Included in an interface file is the unfolding (if any) of a
-declaration. However, if a declaration's unfolding happens to contain
-a <Function>&lowbar;casm&lowbar;</Function>, its unfolding will <Emphasis>not</Emphasis> be emitted into the interface
-file even if it qualifies by all the other criteria. The reason why
-the compiler prevents this from happening is that unfolding <Function>&lowbar;casm&lowbar;</Function>s
-into an interface file unduly constrains how code that import your
-module have to be compiled. If an imported declaration is unfolded and
-it contains a <Function>&lowbar;casm&lowbar;</Function>, you now have to be using a compiler backend
-capable of dealing with it (i.e., the C compiler backend). If you are
-using the C compiler backend, the unfolded <Function>&lowbar;casm&lowbar;</Function> may still cause you
-problems since the C code snippet it contains may mention CPP symbols
-that were in scope when compiling the original module are not when
-compiling the importing module.
+What is <Function>clunky</Function> doing? The guard <Literal>ok1 &&
+ok2</Literal> checks that both lookups succeed, using
+<Function>maybeToBool</Function> to convert the <Function>Maybe</Function>
+types to booleans. The (lazily evaluated) <Function>expectJust</Function>
+calls extract the values from the results of the lookups, and binds the
+returned values to <VarName>val1</VarName> and <VarName>val2</VarName>
+respectively.  If either lookup fails, then clunky takes the
+<Literal>otherwise</Literal> case and returns the sum of its arguments.
 </Para>
 
 <Para>
-If you're willing to put up with the drawbacks of doing cross-module
-inlining of C code (GHC - A Better C Compiler :-), the option
-<Option>-funfold-casms-in-hi-file</Option> will turn off the default behaviour.
-<IndexTerm><Primary>-funfold-casms-in-hi-file option</Primary></IndexTerm>
+This is certainly legal Haskell, but it is a tremendously verbose and
+un-obvious way to achieve the desired effect.  Arguably, a more direct way
+to write clunky would be to use case expressions:
 </Para>
 
-</Sect2>
-
-<Sect2 id="glasgow-literal-literals">
-<Title>Literal-literals</Title>
+<ProgramListing>
+clunky env var1 var1 = case lookup env var1 of
+  Nothing -&gt; fail
+  Just val1 -&gt; case lookup env var2 of
+    Nothing -&gt; fail
+    Just val2 -&gt; val1 + val2
+where
+  fail = val1 + val2
+</ProgramListing>
 
 <Para>
-<IndexTerm><Primary>Literal-literals</Primary></IndexTerm>
-The literal-literal argument to <Function>&lowbar;casm&lowbar;</Function> can be made use of separately
-from the <Function>&lowbar;casm&lowbar;</Function> construct itself. Indeed, we've already used it:
+This is a bit shorter, but hardly better.  Of course, we can rewrite any set
+of pattern-matching, guarded equations as case expressions; that is
+precisely what the compiler does when compiling equations! The reason that
+Haskell provides guarded equations is because they allow us to write down
+the cases we want to consider, one at a time, independently of each other. 
+This structure is hidden in the case version.  Two of the right-hand sides
+are really the same (<Function>fail</Function>), and the whole expression
+tends to become more and more indented. 
 </Para>
 
 <Para>
+Here is how I would write clunky:
+</Para>
 
 <ProgramListing>
-fooH :: Char -> Int -> Double -> Word -> IO Double
-fooH c i d w = _ccall_ fooC (&ldquo;stdin&rdquo;::Addr) c i d w
+clunky env var1 var1
+  | Just val1 &lt;- lookup env var1
+  , Just val2 &lt;- lookup env var2
+  = val1 + val2
+...other equations for clunky...
 </ProgramListing>
 
-</Para>
-
 <Para>
-The first argument that's passed to <Function>fooC</Function> is given as a literal-literal,
-that is, a literal chunk of C code that will be inserted into the generated
-<Filename>.hc</Filename> code at the right place.
+The semantics should be clear enough.  The qualifers are matched in order. 
+For a <Literal>&lt;-</Literal> qualifier, which I call a pattern guard, the
+right hand side is evaluated and matched against the pattern on the left. 
+If the match fails then the whole guard fails and the next equation is
+tried.  If it succeeds, then the appropriate binding takes place, and the
+next qualifier is matched, in the augmented environment.  Unlike list
+comprehensions, however, the type of the expression to the right of the
+<Literal>&lt;-</Literal> is the same as the type of the pattern to its
+left.  The bindings introduced by pattern guards scope over all the
+remaining guard qualifiers, and over the right hand side of the equation.
 </Para>
 
 <Para>
-A literal-literal is restricted to having a type that's an instance of
-the <Literal>CCallable</Literal> class, see <XRef LinkEnd="ccall-gotchas">
-for more information.
+Just as with list comprehensions, boolean expressions can be freely mixed
+with among the pattern guards.  For example:
 </Para>
 
+<ProgramListing>
+f x | [y] <- x
+    , y > 3
+    , Just z <- h y
+    = ...
+</ProgramListing>
+
 <Para>
-Notice that literal-literals are by their very nature unfriendly to
-native code generators, so exercise judgement about whether or not to
-make use of them in your code.
+Haskell's current guards therefore emerge as a special case, in which the
+qualifier list has just one element, a boolean expression.
 </Para>
+</Sect1>
 
-</Sect2>
+  <sect1 id="sec-ffi">
+    <title>The foreign interface</title>
+
+    <para>The foreign interface consists of the following components:</para>
+
+    <itemizedlist>
+      <listitem>
+       <para>The Foreign Function Interface language specification
+       (included in this manual, in <xref linkend="ffi">).</para>
+      </listitem>
+
+      <listitem>
+       <para>The <literal>Foreign</literal> module (see <xref
+       linkend="sec-Foreign">) collects together several interfaces
+       which are useful in specifying foreign language
+       interfaces, including the following:</para>
+
+       <itemizedlist>
+         <listitem>
+           <para>The <literal>ForeignObj</literal> module (see <xref
+           linkend="sec-ForeignObj">), for managing pointers from
+           Haskell into the outside world.</para>
+         </listitem>
+      
+         <listitem>
+           <para>The <literal>StablePtr</literal> module (see <xref
+           linkend="sec-stable-pointers">), for managing pointers
+           into Haskell from the outside world.</para>
+         </listitem>
+      
+         <listitem>
+           <para>The <literal>CTypes</literal> module (see <xref
+           linkend="sec-CTypes">) gives Haskell equivalents for the
+           standard C datatypes, for use in making Haskell bindings
+           to existing C libraries.</para>
+         </listitem>
+      
+         <listitem>
+           <para>The <literal>CTypesISO</literal> module (see <xref
+           linkend="sec-CTypesISO">) gives Haskell equivalents for C
+           types defined by the ISO C standard.</para>
+         </listitem>
+      
+         <listitem>
+           <para>The <literal>Storable</literal> library, for
+           primitive marshalling of data types between Haskell and
+           the foreign language.</para>
+         </listitem>
+       </itemizedlist>
+
+      </listitem>
+    </itemizedlist>
+
+<para>The following sections also give some hints and tips on the use
+of the foreign function interface in GHC.</para>
 
 <Sect2 id="glasgow-foreign-headers">
 <Title>Using function headers
@@ -1511,693 +1702,26 @@ For example,
 <Para>
 
 <ProgramListing>
-typedef unsigned long *StgForeignObj;
-typedef long StgInt;
-
-void          initialiseEFS (StgInt size);
-StgInt        terminateEFS (void);
-StgForeignObj emptyEFS(void);
-StgForeignObj updateEFS (StgForeignObj a, StgInt i, StgInt x);
-StgInt        lookupEFS (StgForeignObj a, StgInt i);
-</ProgramListing>
-
-</Para>
-
-<Para>
-You can find appropriate definitions for <Literal>StgInt</Literal>, <Literal>StgForeignObj</Literal>,
-etc using <Command>gcc</Command> on your architecture by consulting
-<Filename>ghc/includes/StgTypes.h</Filename>.  The following table summarises the
-relationship between Haskell types and C types.
-</Para>
-
-<Para>
-
-<InformalTable>
-<TGroup Cols="2">
-<ColSpec Align="Left" Colsep="0">
-<ColSpec Align="Left" Colsep="0">
-<TBody>
-<Row>
-<Entry><Emphasis>C type name</Emphasis> </Entry>
-<Entry> <Emphasis>Haskell Type</Emphasis> </Entry>
-</Row>
-
-<Row>
-<Entry>
-<Literal>StgChar</Literal> </Entry>
-<Entry> <Literal>Char&num;</Literal> </Entry>
-</Row>
-<Row>
-<Entry>
-<Literal>StgInt</Literal> </Entry>
-<Entry> <Literal>Int&num;</Literal> </Entry>
-</Row>
-<Row>
-<Entry>
-<Literal>StgWord</Literal> </Entry>
-<Entry> <Literal>Word&num;</Literal> </Entry>
-</Row>
-<Row>
-<Entry>
-<Literal>StgAddr</Literal> </Entry>
-<Entry> <Literal>Addr&num;</Literal> </Entry>
-</Row>
-<Row>
-<Entry>
-<Literal>StgFloat</Literal> </Entry>
-<Entry> <Literal>Float&num;</Literal> </Entry>
-</Row>
-<Row>
-<Entry>
-<Literal>StgDouble</Literal> </Entry>
-<Entry> <Literal>Double&num;</Literal> </Entry>
-</Row>
-<Row>
-<Entry>
-<Literal>StgArray</Literal> </Entry>
-<Entry> <Literal>Array&num;</Literal> </Entry>
-</Row>
-<Row>
-<Entry>
-<Literal>StgByteArray</Literal> </Entry>
-<Entry> <Literal>ByteArray&num;</Literal> </Entry>
-</Row>
-<Row>
-<Entry>
-<Literal>StgArray</Literal> </Entry>
-<Entry> <Literal>MutableArray&num;</Literal> </Entry>
-</Row>
-<Row>
-<Entry>
-<Literal>StgByteArray</Literal> </Entry>
-<Entry> <Literal>MutableByteArray&num;</Literal> </Entry>
-</Row>
-<Row>
-<Entry>
-<Literal>StgStablePtr</Literal> </Entry>
-<Entry> <Literal>StablePtr&num;</Literal> </Entry>
-</Row>
-<Row>
-<Entry>
-<Literal>StgForeignObj</Literal> </Entry>
-<Entry> <Literal>ForeignObj&num;</Literal></Entry>
-</Row>
-</TBody>
-
-</TGroup>
-</InformalTable>
-</Para>
-
-<Para>
-Note that this approach is only <Emphasis>essential</Emphasis> for returning
-<Literal>float</Literal>s (or if <Literal>sizeof(int) != sizeof(int *)</Literal> on your
-architecture) but is a Good Thing for anyone who cares about writing
-solid code.  You're crazy not to do it.
-</Para>
-
-</Sect2>
-
-<Sect2 id="glasgow-stablePtrs">
-<Title>Subverting automatic unboxing with &ldquo;stable pointers&rdquo;
-</Title>
-
-<Para>
-<IndexTerm><Primary>stable pointers (Glasgow extension)</Primary></IndexTerm>
-</Para>
-
-<Para>
-The arguments of a <Function>&lowbar;ccall&lowbar;</Function> automatically unboxed before the
-call.  There are two reasons why this is usually the Right Thing to
-do:
-</Para>
-
-<Para>
-
-<ItemizedList>
-<ListItem>
-
-<Para>
-C is a strict language: it would be excessively tedious to pass
-unevaluated arguments and require the C programmer to force their
-evaluation before using them.
-
-</Para>
-</ListItem>
-<ListItem>
-
-<Para>
- Boxed values are stored on the Haskell heap and may be moved
-within the heap if a garbage collection occurs&mdash;that is, pointers
-to boxed objects are not <Emphasis>stable</Emphasis>.
-</Para>
-</ListItem>
-
-</ItemizedList>
-
-</Para>
-
-<Para>
-It is possible to subvert the unboxing process by creating a &ldquo;stable
-pointer&rdquo; to a value and passing the stable pointer instead.  For
-example, to pass/return an integer lazily to C functions <Function>storeC</Function> and
-<Function>fetchC</Function> might write:
-</Para>
-
-<Para>
-
-<ProgramListing>
-storeH :: Int -> IO ()
-storeH x = makeStablePtr x              >>= \ stable_x ->
-           _ccall_ storeC stable_x
-
-fetchH :: IO Int
-fetchH x = _ccall_ fetchC               >>= \ stable_x ->
-           deRefStablePtr stable_x      >>= \ x ->
-           freeStablePtr stable_x       >>
-           return x
-</ProgramListing>
-
-</Para>
-
-<Para>
-The garbage collector will refrain from throwing a stable pointer away
-until you explicitly call one of the following from C or Haskell.
-</Para>
-
-<Para>
-
-<ProgramListing>
-void freeStablePointer( StgStablePtr stablePtrToToss )
-freeStablePtr :: StablePtr a -> IO ()
-</ProgramListing>
-
-</Para>
-
-<Para>
-As with the use of <Function>free</Function> in C programs, GREAT CARE SHOULD BE
-EXERCISED to ensure these functions are called at the right time: too
-early and you get dangling references (and, if you're lucky, an error
-message from the runtime system); too late and you get space leaks.
-</Para>
-
-<Para>
-And to force evaluation of the argument within <Function>fooC</Function>, one would
-call one of the following C functions (according to type of argument).
-</Para>
-
-<Para>
-
-<ProgramListing>
-void     performIO  ( StgStablePtr stableIndex /* StablePtr s (IO ()) */ );
-StgInt   enterInt   ( StgStablePtr stableIndex /* StablePtr s Int */ );
-StgFloat enterFloat ( StgStablePtr stableIndex /* StablePtr s Float */ );
-</ProgramListing>
-
-</Para>
-
-<Para>
-<IndexTerm><Primary>performIO</Primary></IndexTerm>
-<IndexTerm><Primary>enterInt</Primary></IndexTerm>
-<IndexTerm><Primary>enterFloat</Primary></IndexTerm>
-</Para>
-
-<Para>
-Nota Bene: <Function>&lowbar;ccall&lowbar;GC&lowbar;</Function><IndexTerm><Primary>&lowbar;ccall&lowbar;GC&lowbar;</Primary></IndexTerm> must be used if any of
-these functions are used.
-</Para>
-
-</Sect2>
-
-<Sect2 id="glasgow-foreignObjs">
-<Title>Foreign objects: pointing outside the Haskell heap
-</Title>
-
-<Para>
-<IndexTerm><Primary>foreign objects (Glasgow extension)</Primary></IndexTerm>
-</Para>
-
-<Para>
-There are two types that GHC programs can use to reference
-(heap-allocated) objects outside the Haskell world: <Literal>Addr</Literal> and
-<Literal>ForeignObj</Literal>.
-</Para>
-
-<Para>
-If you use <Literal>Addr</Literal>, it is up to you to the programmer to arrange
-allocation and deallocation of the objects.
-</Para>
-
-<Para>
-If you use <Literal>ForeignObj</Literal>, GHC's garbage collector will call upon the
-user-supplied <Emphasis>finaliser</Emphasis> function to free the object when the
-Haskell world no longer can access the object.  (An object is
-associated with a finaliser function when the abstract
-Haskell type <Literal>ForeignObj</Literal> is created). The finaliser function is
-expressed in C, and is passed as argument the object:
-</Para>
-
-<Para>
-
-<ProgramListing>
-void foreignFinaliser ( StgForeignObj fo )
-</ProgramListing>
-
-</Para>
-
-<Para>
-when the Haskell world can no longer access the object.  Since
-<Literal>ForeignObj</Literal>s only get released when a garbage collection occurs, we
-provide ways of triggering a garbage collection from within C and from
-within Haskell.
-</Para>
-
-<Para>
-
-<ProgramListing>
-void GarbageCollect()
-performGC :: IO ()
-</ProgramListing>
-
-</Para>
-
-<Para>
-More information on the programmers' interface to <Literal>ForeignObj</Literal> can be
-found in the library documentation.
-</Para>
-
-</Sect2>
-
-<Sect2 id="glasgow-avoiding-monads">
-<Title>Avoiding monads
-</Title>
-
-<Para>
-<IndexTerm><Primary>C calls to `pure C'</Primary></IndexTerm>
-<IndexTerm><Primary>unsafePerformIO</Primary></IndexTerm>
-</Para>
-
-<Para>
-The <Function>&lowbar;ccall&lowbar;</Function> construct is part of the <Literal>IO</Literal> monad because 9 out of 10
-uses will be to call imperative functions with side effects such as
-<Function>printf</Function>.  Use of the monad ensures that these operations happen in a
-predictable order in spite of laziness and compiler optimisations.
-</Para>
-
-<Para>
-To avoid having to be in the monad to call a C function, it is
-possible to use <Function>unsafePerformIO</Function>, which is available from the
-<Literal>IOExts</Literal> module.  There are three situations where one might like to
-call a C function from outside the IO world:
-</Para>
-
-<Para>
-
-<ItemizedList>
-<ListItem>
-
-<Para>
-Calling a function with no side-effects:
-
-<ProgramListing>
-atan2d :: Double -> Double -> Double
-atan2d y x = unsafePerformIO (_ccall_ atan2d y x)
-
-sincosd :: Double -> (Double, Double)
-sincosd x = unsafePerformIO $ do
-        da &#60;- newDoubleArray (0, 1)
-        _casm_ &ldquo;sincosd( %0, &amp;((double *)%1[0]), &amp;((double *)%1[1]) );&rdquo; x da
-        s &#60;- readDoubleArray da 0
-        c &#60;- readDoubleArray da 1
-        return (s, c)
-</ProgramListing>
-
-
-</Para>
-</ListItem>
-<ListItem>
-
-<Para>
- Calling a set of functions which have side-effects but which can
-be used in a purely functional manner.
-
-For example, an imperative implementation of a purely functional
-lookup-table might be accessed using the following functions.
-
-
-<ProgramListing>
-empty  :: EFS x
-update :: EFS x -> Int -> x -> EFS x
-lookup :: EFS a -> Int -> a
-
-empty = unsafePerformIO (_ccall_ emptyEFS)
-
-update a i x = unsafePerformIO $
-        makeStablePtr x         >>= \ stable_x ->
-        _ccall_ updateEFS a i stable_x
-
-lookup a i = unsafePerformIO $
-        _ccall_ lookupEFS a i   >>= \ stable_x ->
-        deRefStablePtr stable_x
-</ProgramListing>
-
-
-You will almost always want to use <Literal>ForeignObj</Literal>s with this.
-
-</Para>
-</ListItem>
-<ListItem>
-
-<Para>
- Calling a side-effecting function even though the results will
-be unpredictable.  For example the <Function>trace</Function> function is defined by:
-
-
-<ProgramListing>
-trace :: String -> a -> a
-trace string expr
-  = unsafePerformIO (
-        ((_ccall_ PreTraceHook sTDERR{-msg-}):: IO ())  >>
-        fputs sTDERR string                             >>
-        ((_ccall_ PostTraceHook sTDERR{-msg-}):: IO ()) >>
-        return expr )
-  where
-    sTDERR = (&ldquo;stderr&rdquo; :: Addr)
-</ProgramListing>
-
+#include "HsFFI.h"
 
-(This kind of use is not highly recommended&mdash;it is only really
-useful in debugging code.)
-</Para>
-</ListItem>
-
-</ItemizedList>
-
-</Para>
-
-</Sect2>
-
-<Sect2 id="ccall-gotchas">
-<Title>C-calling &ldquo;gotchas&rdquo; checklist
-</Title>
-
-<Para>
-<IndexTerm><Primary>C call dangers</Primary></IndexTerm>
-<IndexTerm><Primary>CCallable</Primary></IndexTerm>
-<IndexTerm><Primary>CReturnable</Primary></IndexTerm>
-</Para>
-
-<Para>
-And some advice, too.
-</Para>
-
-<Para>
-
-<ItemizedList>
-<ListItem>
-
-<Para>
- For modules that use <Function>&lowbar;ccall&lowbar;</Function>s, etc., compile with
-<Option>-fvia-C</Option>.<IndexTerm><Primary>-fvia-C option</Primary></IndexTerm> You don't have to, but you should.
-
-Also, use the <Option>-&num;include "prototypes.h"</Option> flag (hack) to inform the C
-compiler of the fully-prototyped types of all the C functions you
-call.  (<XRef LinkEnd="glasgow-foreign-headers"> says more about this&hellip;)
-
-This scheme is the <Emphasis>only</Emphasis> way that you will get <Emphasis>any</Emphasis>
-typechecking of your <Function>&lowbar;ccall&lowbar;</Function>s.  (It shouldn't be that way, but&hellip;).
-GHC will pass the flag <Option>-Wimplicit</Option> to <Command>gcc</Command> so that you'll get warnings
-if any <Function>&lowbar;ccall&lowbar;</Function>ed functions have no prototypes.
-
-</Para>
-</ListItem>
-<ListItem>
-
-<Para>
-Try to avoid <Function>&lowbar;ccall&lowbar;</Function>s to C&nbsp;functions that take <Literal>float</Literal>
-arguments or return <Literal>float</Literal> results.  Reason: if you do, you will
-become entangled in (ANSI?) C's rules for when arguments/results are
-promoted to <Literal>doubles</Literal>.  It's a nightmare and just not worth it.
-Use <Literal>doubles</Literal> if possible.
-
-If you do use <Literal>floats</Literal>, check and re-check that the right thing is
-happening.  Perhaps compile with <Option>-keep-hc-file-too</Option> and look at
-the intermediate C (<Function>.hc</Function>).
-
-</Para>
-</ListItem>
-<ListItem>
-
-<Para>
- The compiler uses two non-standard type-classes when
-type-checking the arguments and results of <Function>&lowbar;ccall&lowbar;</Function>: the arguments
-(respectively result) of <Function>&lowbar;ccall&lowbar;</Function> must be instances of the class
-<Literal>CCallable</Literal> (respectively <Literal>CReturnable</Literal>).  Both classes may be
-imported from the module <Literal>CCall</Literal>, but this should only be
-necessary if you want to define a new instance.  (Neither class
-defines any methods&mdash;their only function is to keep the
-type-checker happy.)
-
-The type checker must be able to figure out just which of the
-C-callable/returnable types is being used.  If it can't, you have to
-add type signatures. For example,
-
-
-<ProgramListing>
-f x = _ccall_ foo x
-</ProgramListing>
-
-
-is not good enough, because the compiler can't work out what type <VarName>x</VarName>
-is, nor what type the <Function>&lowbar;ccall&lowbar;</Function> returns.  You have to write, say:
-
-
-<ProgramListing>
-f :: Int -> IO Double
-f x = _ccall_ foo x
-</ProgramListing>
-
-
-This table summarises the standard instances of these classes.
-
-<InformalTable>
-<TGroup Cols="4">
-<ColSpec Align="Left" Colsep="0">
-<ColSpec Align="Left" Colsep="0">
-<ColSpec Align="Left" Colsep="0">
-<ColSpec Align="Left" Colsep="0">
-<TBody>
-<Row>
-<Entry><Emphasis>Type</Emphasis> </Entry>
-<Entry><Emphasis>CCallable</Emphasis></Entry>
-<Entry><Emphasis>CReturnable</Emphasis> </Entry>
-<Entry><Emphasis>Which is probably&hellip;</Emphasis> </Entry>
-</Row>
-<Row>
-<Entry>
-<Literal>Char</Literal> </Entry>
-<Entry> Yes </Entry>
-<Entry> Yes </Entry>
-<Entry> <Literal>unsigned char</Literal> </Entry>
-</Row>
-<Row>
-<Entry>
-<Literal>Int</Literal> </Entry>
-<Entry> Yes </Entry>
-<Entry> Yes </Entry>
-<Entry> <Literal>long int</Literal> </Entry>
-</Row>
-<Row>
-<Entry>
-<Literal>Word</Literal> </Entry>
-<Entry> Yes </Entry>
-<Entry> Yes </Entry>
-<Entry> <Literal>unsigned long int</Literal> </Entry>
-</Row>
-<Row>
-<Entry>
-<Literal>Addr</Literal> </Entry>
-<Entry> Yes </Entry>
-<Entry> Yes </Entry>
-<Entry> <Literal>void *</Literal> </Entry>
-</Row>
-<Row>
-<Entry>
-<Literal>Float</Literal> </Entry>
-<Entry> Yes </Entry>
-<Entry> Yes </Entry>
-<Entry> <Literal>float</Literal> </Entry>
-</Row>
-<Row>
-<Entry>
-<Literal>Double</Literal> </Entry>
-<Entry> Yes </Entry>
-<Entry> Yes </Entry>
-<Entry> <Literal>double</Literal> </Entry>
-</Row>
-<Row>
-<Entry>
-<Literal>()</Literal> </Entry>
-<Entry> No </Entry>
-<Entry> Yes </Entry>
-<Entry> <Literal>void</Literal> </Entry>
-</Row>
-<Row>
-<Entry>
-<Literal>[Char]</Literal> </Entry>
-<Entry> Yes </Entry>
-<Entry> No </Entry>
-<Entry> <Literal>char *</Literal> (null-terminated) </Entry>
-</Row>
-<Row>
-<Entry>
-<Literal>Array</Literal> </Entry>
-<Entry> Yes </Entry>
-<Entry> No </Entry>
-<Entry> <Literal>unsigned long *</Literal> </Entry>
-</Row>
-<Row>
-<Entry>
-<Literal>ByteArray</Literal> </Entry>
-<Entry> Yes </Entry>
-<Entry> No </Entry>
-<Entry> <Literal>unsigned long *</Literal> </Entry>
-</Row>
-<Row>
-<Entry>
-<Literal>MutableArray</Literal> </Entry>
-<Entry> Yes </Entry>
-<Entry> No </Entry>
-<Entry> <Literal>unsigned long *</Literal> </Entry>
-</Row>
-<Row>
-<Entry>
-<Literal>MutableByteArray</Literal> </Entry>
-<Entry> Yes </Entry>
-<Entry> No </Entry>
-<Entry> <Literal>unsigned long *</Literal> </Entry>
-</Row>
-<Row>
-<Entry>
-<Literal>State</Literal> </Entry>
-<Entry> Yes </Entry>
-<Entry> Yes </Entry>
-<Entry> nothing!</Entry>
-</Row>
-<Row>
-<Entry>
-<Literal>StablePtr</Literal> </Entry>
-<Entry> Yes </Entry>
-<Entry> Yes </Entry>
-<Entry> <Literal>unsigned long *</Literal> </Entry>
-</Row>
-<Row>
-<Entry>
-<Literal>ForeignObjs</Literal> </Entry>
-<Entry> Yes </Entry>
-<Entry> Yes </Entry>
-<Entry> see later </Entry>
-</Row>
-
-</TBody>
-
-</TGroup>
-</InformalTable>
-
-Actually, the <Literal>Word</Literal> type is defined as being the same size as a
-pointer on the target architecture, which is <Emphasis>probably</Emphasis>
-<Literal>unsigned long int</Literal>.
-
-The brave and careful programmer can add their own instances of these
-classes for the following types:
-
-
-<ItemizedList>
-<ListItem>
-
-<Para>
-A <Emphasis>boxed-primitive</Emphasis> type may be made an instance of both
-<Literal>CCallable</Literal> and <Literal>CReturnable</Literal>.
-
-A boxed primitive type is any data type with a
-single unary constructor with a single primitive argument.  For
-example, the following are all boxed primitive types:
-
-
-<ProgramListing>
-Int
-Double
-data XDisplay = XDisplay Addr#
-data EFS a = EFS# ForeignObj#
-</ProgramListing>
-
-
-
-<ProgramListing>
-instance CCallable   (EFS a)
-instance CReturnable (EFS a)
-</ProgramListing>
-
-
-</Para>
-</ListItem>
-<ListItem>
-
-<Para>
- Any datatype with a single nullary constructor may be made an
-instance of <Literal>CReturnable</Literal>.  For example:
-
-
-<ProgramListing>
-data MyVoid = MyVoid
-instance CReturnable MyVoid
+void         initialiseEFS (HsInt size);
+HsInt        terminateEFS (void);
+HsForeignObj emptyEFS(void);
+HsForeignObj updateEFS (HsForeignObj a, HsInt i, HsInt x);
+HsInt        lookupEFS (HsForeignObj a, HsInt i);
 </ProgramListing>
-
-
-</Para>
-</ListItem>
-<ListItem>
-
-<Para>
- As at version 2.09, <Literal>String</Literal> (i.e., <Literal>[Char]</Literal>) is still
-not a <Literal>CReturnable</Literal> type.
-
-Also, the now-builtin type <Literal>PackedString</Literal> is neither
-<Literal>CCallable</Literal> nor <Literal>CReturnable</Literal>.  (But there are functions in
-the PackedString interface to let you get at the necessary bits&hellip;)
-</Para>
-</ListItem>
-
-</ItemizedList>
-
-
-</Para>
-</ListItem>
-<ListItem>
-
-<Para>
- The code-generator will complain if you attempt to use <Literal>&percnt;r</Literal> in
-a <Literal>&lowbar;casm&lowbar;</Literal> whose result type is <Literal>IO ()</Literal>; or if you don't use <Literal>&percnt;r</Literal>
-<Emphasis>precisely</Emphasis> once for any other result type.  These messages are
-supposed to be helpful and catch bugs&mdash;please tell us if they wreck
-your life.
-
-</Para>
-</ListItem>
-<ListItem>
-
-<Para>
- If you call out to C code which may trigger the Haskell garbage
-collector or create new threads (examples of this later&hellip;), then you
-must use the <Function>&lowbar;ccall&lowbar;GC&lowbar;</Function><IndexTerm><Primary>&lowbar;ccall&lowbar;GC&lowbar; primitive</Primary></IndexTerm> or
-<Function>&lowbar;casm&lowbar;GC&lowbar;</Function><IndexTerm><Primary>&lowbar;casm&lowbar;GC&lowbar; primitive</Primary></IndexTerm> variant of C-calls.  (This
-does not work with the native code generator&mdash;use <Option>-fvia-C</Option>.) This
-stuff is hairy with a capital H!
 </Para>
-</ListItem>
 
-</ItemizedList>
+      <para>The types <literal>HsInt</literal>,
+      <literal>HsForeignObj</literal> etc. are described in <xref
+      linkend="sec-mapping-table">.</Para>
 
-</Para>
+      <Para>Note that this approach is only
+      <Emphasis>essential</Emphasis> for returning
+      <Literal>float</Literal>s (or if <Literal>sizeof(int) !=
+      sizeof(int *)</Literal> on your architecture) but is a Good
+      Thing for anyone who cares about writing solid code.  You're
+      crazy not to do it.</Para>
 
 </Sect2>
 
@@ -2208,7 +1732,7 @@ stuff is hairy with a capital H!
 </Title>
 
 <Para>
-This section documents GHC's implementation of multi-paramter type
+This section documents GHC's implementation of multi-parameter type
 classes.  There's lots of background in the paper <ULink
 URL="http://research.microsoft.com/~simonpj/multi.ps.gz" >Type
 classes: exploring the design space</ULink > (Simon Peyton Jones, Mark
@@ -2508,7 +2032,7 @@ class like this:
 
 </Sect2>
 
-<Sect2>
+<Sect2 id="instance-decls">
 <Title>Instance declarations</Title>
 
 <Para>
@@ -3548,7 +3072,7 @@ use of <Function>assert</Function> in the user's source:
 
 <ProgramListing>
 kelvinToC :: Double -> Double
-kelvinToC k = assert (k &amp;gt;= 0.0) (k+273.15)
+kelvinToC k = assert (k &gt;= 0.0) (k+273.15)
 </ProgramListing>
 
 </Para>
@@ -4380,7 +3904,7 @@ to arbitrary expressions.  For example, this is <Emphasis>not</Emphasis> OK:
 "wrong2"   forall f.      f True = True
 </ProgramListing>
 
-In <Literal>"wrong1"</Literal>, the LHS is not an application; in <Literal>"wrong1"</Literal>, the LHS has a pattern variable
+In <Literal>"wrong1"</Literal>, the LHS is not an application; in <Literal>"wrong2"</Literal>, the LHS has a pattern variable
 in the head.
 </Para>
 </ListItem>
@@ -4845,6 +4369,256 @@ program even if fusion doesn't happen.  More rules in <Filename>PrelList.lhs</Fi
 
 </Sect1>
 
+<Sect1 id="generic-classes">
+<Title>Generic classes</Title>
+
+<Para>
+The ideas behind this extension are described in detail in "Derivable type classes",
+Ralf Hinze and Simon Peyton Jones, Haskell Workshop, Montreal Sept 2000, pp94-105.
+An example will give the idea:
+</Para>
+
+<ProgramListing>
+  import Generics
+
+  class Bin a where
+    toBin   :: a -> [Int]
+    fromBin :: [Int] -> (a, [Int])
+  
+    toBin {| Unit |}    Unit     = []
+    toBin {| a :+: b |} (Inl x)   = 0 : toBin x
+    toBin {| a :+: b |} (Inr y)   = 1 : toBin y
+    toBin {| a :*: b |} (x :*: y) = toBin x ++ toBin y
+  
+    fromBin {| Unit |}    bs      = (Unit, bs)
+    fromBin {| a :+: b |} (0:bs)  = (Inl x, bs')    where (x,bs') = fromBin bs
+    fromBin {| a :+: b |} (1:bs)  = (Inr y, bs')    where (y,bs') = fromBin bs
+    fromBin {| a :*: b |} bs     = (x :*: y, bs'') where (x,bs' ) = fromBin bs
+                                                         (y,bs'') = fromBin bs'
+</ProgramListing>
+<Para>
+This class declaration explains how <Literal>toBin</Literal> and <Literal>fromBin</Literal>
+work for arbitrary data types.  They do so by giving cases for unit, product, and sum,
+which are defined thus in the library module <Literal>Generics</Literal>:
+</Para>
+<ProgramListing>
+  data Unit    = Unit
+  data a :+: b = Inl a | Inr b
+  data a :*: b = a :*: b
+</ProgramListing>
+<Para>
+Now you can make a data type into an instance of Bin like this:
+<ProgramListing>
+  instance (Bin a, Bin b) => Bin (a,b)
+  instance Bin a => Bin [a]
+</ProgramListing>
+That is, just leave off the "where" clasuse.  Of course, you can put in the
+where clause and over-ride whichever methods you please.
+</Para>
+
+    <Sect2>
+      <Title> Using generics </Title>
+      <Para>To use generics you need to</para>
+      <ItemizedList>
+       <ListItem>
+         <Para>Use the <Option>-fgenerics</Option> flag.</Para>
+       </ListItem>
+       <ListItem>
+         <Para>Import the module <Literal>Generics</Literal> from the
+          <Literal>lang</Literal> package.  This import brings into
+          scope the data types <Literal>Unit</Literal>,
+          <Literal>:*:</Literal>, and <Literal>:+:</Literal>.  (You
+          don't need this import if you don't mention these types
+          explicitly; for example, if you are simply giving instance
+          declarations.)</Para>
+       </ListItem>
+      </ItemizedList>
+    </Sect2>
+
+<Sect2> <Title> Changes wrt the paper </Title>
+<Para>
+Note that the type constructors <Literal>:+:</Literal> and <Literal>:*:</Literal> 
+can be written infix (indeed, you can now use
+any operator starting in a colon as an infix type constructor).  Also note that
+the type constructors are not exactly as in the paper (Unit instead of 1, etc).
+Finally, note that the syntax of the type patterns in the class declaration
+uses "<Literal>{|</Literal>" and "<Literal>{|</Literal>" brackets; curly braces
+alone would ambiguous when they appear on right hand sides (an extension we 
+anticipate wanting).
+</Para>
+</Sect2>
+
+<Sect2> <Title>Terminology and restrictions</Title>
+<Para>
+Terminology.  A "generic default method" in a class declaration
+is one that is defined using type patterns as above.
+A "polymorphic default method" is a default method defined as in Haskell 98.
+A "generic class declaration" is a class declaration with at least one
+generic default method.
+</Para>
+
+<Para>
+Restrictions:
+<ItemizedList>
+<ListItem>
+<Para>
+Alas, we do not yet implement the stuff about constructor names and 
+field labels.
+</Para>
+</ListItem>
+
+<ListItem>
+<Para>
+A generic class can have only one parameter; you can't have a generic
+multi-parameter class.
+</Para>
+</ListItem>
+
+<ListItem>
+<Para>
+A default method must be defined entirely using type patterns, or entirely
+without.  So this is illegal:
+<ProgramListing>
+  class Foo a where
+    op :: a -> (a, Bool)
+    op {| Unit |} Unit = (Unit, True)
+    op x               = (x,    False)
+</ProgramListing>
+However it is perfectly OK for some methods of a generic class to have 
+generic default methods and others to have polymorphic default methods.
+</Para>
+</ListItem>
+
+<ListItem>
+<Para>
+The type variable(s) in the type pattern for a generic method declaration
+scope over the right hand side.  So this is legal (note the use of the type variable ``p'' in a type signature on the right hand side:
+<ProgramListing>
+  class Foo a where
+    op :: a -> Bool
+    op {| p :*: q |} (x :*: y) = op (x :: p)
+    ...
+</ProgramListing>
+</Para>
+</ListItem>
+
+<ListItem>
+<Para>
+The type patterns in a generic default method must take one of the forms:
+<ProgramListing>
+       a :+: b
+       a :*: b
+       Unit
+</ProgramListing>
+where "a" and "b" are type variables.  Furthermore, all the type patterns for
+a single type constructor (<Literal>:*:</Literal>, say) must be identical; they
+must use the same type variables.  So this is illegal:
+<ProgramListing>
+  class Foo a where
+    op :: a -> Bool
+    op {| a :+: b |} (Inl x) = True
+    op {| p :+: q |} (Inr y) = False
+</ProgramListing>
+The type patterns must be identical, even in equations for different methods of the class.
+So this too is illegal:
+<ProgramListing>
+  class Foo a where
+    op1 :: a -> Bool
+    op {| a :*: b |} (Inl x) = True
+
+    op2 :: a -> Bool
+    op {| p :*: q |} (Inr y) = False
+</ProgramListing>
+(The reason for this restriction is that we gather all the equations for a particular type consructor
+into a single generic instance declaration.)
+</Para>
+</ListItem>
+
+<ListItem>
+<Para>
+A generic method declaration must give a case for each of the three type constructors.
+</Para>
+</ListItem>
+
+<ListItem>
+<Para>
+The type for a generic method can be built only from:
+  <ItemizedList>
+  <ListItem> <Para> Function arrows </Para> </ListItem>
+  <ListItem> <Para> Type variables </Para> </ListItem>
+  <ListItem> <Para> Tuples </Para> </ListItem>
+  <ListItem> <Para> Arbitrary types not involving type variables </Para> </ListItem>
+  </ItemizedList>
+Here are some example type signatures for generic methods:
+<ProgramListing>
+    op1 :: a -> Bool
+    op2 :: Bool -> (a,Bool)
+    op3 :: [Int] -> a -> a
+    op4 :: [a] -> Bool
+</ProgramListing>
+Here, op1, op2, op3 are OK, but op4 is rejected, because it has a type variable
+inside a list.  
+</Para>
+<Para>
+This restriction is an implementation restriction: we just havn't got around to
+implementing the necessary bidirectional maps over arbitrary type constructors.
+It would be relatively easy to add specific type constructors, such as Maybe and list,
+to the ones that are allowed.</para>
+</ListItem>
+
+<ListItem>
+<Para>
+In an instance declaration for a generic class, the idea is that the compiler
+will fill in the methods for you, based on the generic templates.  However it can only
+do so if
+  <ItemizedList>
+  <ListItem>
+  <Para>
+  The instance type is simple (a type constructor applied to type variables, as in Haskell 98).
+  </Para>
+  </ListItem>
+  <ListItem>
+  <Para>
+  No constructor of the instance type has unboxed fields.
+  </Para>
+  </ListItem>
+  </ItemizedList>
+(Of course, these things can only arise if you are already using GHC extensions.)
+However, you can still give an instance declarations for types which break these rules,
+provided you give explicit code to override any generic default methods.
+</Para>
+</ListItem>
+
+</ItemizedList>
+</Para>
+
+<Para>
+The option <Option>-ddump-deriv</Option> dumps incomprehensible stuff giving details of 
+what the compiler does with generic declarations.
+</Para>
+
+</Sect2>
+
+<Sect2> <Title> Another example </Title>
+<Para>
+Just to finish with, here's another example I rather like:
+<ProgramListing>
+  class Tag a where
+    nCons :: a -> Int
+    nCons {| Unit |}    _ = 1
+    nCons {| a :*: b |} _ = 1
+    nCons {| a :+: b |} _ = nCons (bot::a) + nCons (bot::b)
+  
+    tag :: a -> Int
+    tag {| Unit |}    _       = 1
+    tag {| a :*: b |} _       = 1   
+    tag {| a :+: b |} (Inl x) = tag x
+    tag {| a :+: b |} (Inr y) = nCons (bot::a) + tag y
+</ProgramListing>
+</Para>
+</Sect2>
+</Sect1>
+
 <!-- Emacs stuff:
      ;;; Local Variables: ***
      ;;; mode: sgml ***