Add some explanation about overlapping instances
[ghc-hetmet.git] / docs / users_guide / glasgow_exts.xml
index f6879fe..7e88a4f 100644 (file)
@@ -351,6 +351,15 @@ Indeed, the bindings can even be recursive.
              <entry>Name</entry>
            </row>
          </thead>
+
+<!--
+               to find the DocBook entities for these characters, find
+               the Unicode code point (e.g. 0x2237), and grep for it in
+               /usr/share/sgml/docbook/xml-dtd-*/ent/* (or equivalent on
+               your system.  Some of these Unicode code points don't have
+               equivalent DocBook entities.
+            -->
+
          <tbody>
            <row>
              <entry><literal>::</literal></entry>
@@ -399,6 +408,52 @@ Indeed, the bindings can even be recursive.
              <entry>MIDLINE HORIZONTAL ELLIPSIS</entry>
            </row>
           </tbody>
+
+         <tbody>
+           <row>
+             <entry>-&lt;</entry>
+             <entry>&larrtl;</entry>
+             <entry>0x2919</entry>
+             <entry>LEFTWARDS ARROW-TAIL</entry>
+           </row>
+          </tbody>
+
+         <tbody>
+           <row>
+             <entry>&gt;-</entry>
+             <entry>&rarrtl;</entry>
+             <entry>0x291A</entry>
+             <entry>RIGHTWARDS ARROW-TAIL</entry>
+           </row>
+          </tbody>
+
+         <tbody>
+           <row>
+             <entry>-&lt;&lt;</entry>
+             <entry></entry>
+             <entry>0x291B</entry>
+             <entry>LEFTWARDS DOUBLE ARROW-TAIL</entry>
+           </row>
+          </tbody>
+
+         <tbody>
+           <row>
+             <entry>&gt;&gt;-</entry>
+             <entry></entry>
+             <entry>0x291C</entry>
+             <entry>RIGHTWARDS DOUBLE ARROW-TAIL</entry>
+           </row>
+          </tbody>
+
+         <tbody>
+           <row>
+             <entry>*</entry>
+             <entry>&starf;</entry>
+             <entry>0x2605</entry>
+             <entry>BLACK STAR</entry>
+           </row>
+          </tbody>
+
         </tgroup>
       </informaltable>
     </sect2>
@@ -871,8 +926,6 @@ the do-notation.  The <option>-XDoRec</option> flag provides the necessary synta
 Here is a simple (albeit contrived) example:
 <programlisting>
 {-# LANGUAGE DoRec #-}
-import Control.Monad.Fix
-
 justOnes = do { rec { xs &lt;- Just (1:xs) }
               ; return (map negate xs) }
 </programlisting>
@@ -883,9 +936,9 @@ The background and motivation for recusrive do-notation is described in
 <ulink url="http://sites.google.com/site/leventerkok/">A recursive do for Haskell</ulink>,
 by Levent Erkok, John Launchbury,
 Haskell Workshop 2002, pages: 29-37. Pittsburgh, Pennsylvania. 
-This paper is essential reading for anyone making non-trivial use of mdo-notation,
-and we do not repeat it here.  However, note that GHC uses a different syntax than the one
-in the paper.
+The theory behind monadic value recursion is explained further in Erkok's thesis
+<ulink url="http://sites.google.com/site/leventerkok/erkok-thesis.pdf">Value Recursion in Monadic Computations</ulink>.
+However, note that GHC uses a different syntax than the one described in these documents.
 </para>
 
 <sect3>
@@ -913,30 +966,54 @@ while <literal>rec</literal> is monadic.  (In Haskell <literal>let</literal> is
 really <literal>letrec</literal>, of course.)
 </para>
 <para>
-The Control.Monad.Fix library introduces the <literal>MonadFix</literal> class.  Its definition is:
-</para>
+The static and dynamic semantics of <literal>rec</literal> can be described as follows:  
+<itemizedlist>
+<listitem><para>
+First,
+similar to let-bindings, the <literal>rec</literal> is broken into 
+minimal recursive groups, a process known as <emphasis>segmentation</emphasis>.
+For example:
 <programlisting>
-class Monad m => MonadFix m where
-   mfix :: (a -> m a) -> m a
+rec { a &lt;- getChar      ===>     a &lt;- getChar
+    ; b &lt;- f a c                 rec { b &lt;- f a c
+    ; c &lt;- f b a                     ; c &lt;- f b a }
+    ; putChar c }                putChar c 
 </programlisting>
-<para>
-The function <literal>mfix</literal>
-dictates how the required recursion operation should be performed.  For example, 
-<literal>justOnes</literal> desugars as follows:
+The details of segmentation are described in Section 3.2 of
+<ulink url="http://sites.google.com/site/leventerkok/">A recursive do for Haskell</ulink>.
+Segmentation improves polymorphism, reduces the size of the recursive "knot", and, as the paper 
+describes, also has a semantic effect (unless the monad satisfies the right-shrinking law).
+</para></listitem>
+<listitem><para>
+Then each resulting <literal>rec</literal> is desugared, using a call to <literal>Control.Monad.Fix.mfix</literal>.
+For example, the <literal>rec</literal> group in the preceding example is desugared like this:
 <programlisting>
-justOnes = do { xs &lt;- mfix (\xs' -&gt; do { xs &lt;- Just (1:xs'); return xs })
-              ; return (map negate xs) }
+rec { b &lt;- f a c     ===>    (b,c) &lt;- mfix (\~(b,c) -> do { b &lt;- f a c
+    ; c &lt;- f b a }                                        ; c &lt;- f b a
+                                                          ; return (b,c) })
 </programlisting>
 In general, the statment <literal>rec <replaceable>ss</replaceable></literal>
 is desugared to the statement
 <programlisting>
-  <replaceable>vs</replaceable> &lt;- mfix (\~<replaceable>vs</replaceable> -&gt; do { <replaceable>ss</replaceable>; return <replaceable>vs</replaceable> })
+<replaceable>vs</replaceable> &lt;- mfix (\~<replaceable>vs</replaceable> -&gt; do { <replaceable>ss</replaceable>; return <replaceable>vs</replaceable> })
 </programlisting>
 where <replaceable>vs</replaceable> is a tuple of the variables bound by <replaceable>ss</replaceable>.
-Moreover, the original <literal>rec</literal> typechecks exactly 
-when the above desugared version would do so.  (For example, this means that 
+</para><para>
+The original <literal>rec</literal> typechecks exactly 
+when the above desugared version would do so.  For example, this means that 
 the variables <replaceable>vs</replaceable> are all monomorphic in the statements
-following the <literal>rec</literal>, because they are bound by a lambda.)
+following the <literal>rec</literal>, because they are bound by a lambda.
+</para>
+<para>
+The <literal>mfix</literal> function is defined in the <literal>MonadFix</literal> 
+class, in <literal>Control.Monad.Fix</literal>, thus:
+<programlisting>
+class Monad m => MonadFix m where
+   mfix :: (a -> m a) -> m a
+</programlisting>
+</para>
+</listitem>
+</itemizedlist>
 </para>
 <para>
 Here are some other important points in using the recursive-do notation:
@@ -958,18 +1035,13 @@ for Haskell's internal state monad (strict and lazy, respectively).
 </para></listitem>
 
 <listitem><para>
-Unlike ordinary do-notation, but like <literal>let</literal> and <literal>where</literal> bindings,
-name shadowing is not allowed; that is, all the names bound in a single <literal>mdo</literal> must
+Like <literal>let</literal> and <literal>where</literal> bindings,
+name shadowing is not allowed within a <literal>rec</literal>; 
+that is, all the names bound in a single <literal>rec</literal> must
 be distinct (Section 3.3 of the paper).
 </para></listitem>
-
 <listitem><para>
-Similar to let-bindings, GHC implements the segmentation technique described in Section 3.2 of
-<ulink url="http://sites.google.com/site/leventerkok/">A recursive do for Haskell</ulink>,
-to break up a single <literal>rec</literal> statement into a sequence of statements with
-<literal>rec</literal> groups of minimal size.  This 
-improves polymorphism, reduces the size of the recursive "knot", and, as the paper 
-describes, also has a semantic effect (unless the monad satisfies the right-shrinking law).
+It supports rebindable syntax (see <xref linkend="rebindable-syntax"/>).
 </para></listitem>
 </itemizedlist>
 </para>
@@ -977,9 +1049,9 @@ describes, also has a semantic effect (unless the monad satisfies the right-shri
 
 <sect3> <title> Mdo-notation (deprecated) </title>
 
-<para> GHC used to support the flag <option>-XREecursiveDo</option>,
+<para> GHC used to support the flag <option>-XRecursiveDo</option>,
 which enabled the keyword <literal>mdo</literal>, precisely as described in
-<ulink url="http://citeseer.ist.psu.edu/erk02recursive.html">A recursive do for Haskell</ulink>,
+<ulink url="http://sites.google.com/site/leventerkok/">A recursive do for Haskell</ulink>,
 but this is now deprecated.  Instead of <literal>mdo { Q; e }</literal>, write
 <literal>do { rec Q; e }</literal>.
 </para>
@@ -3933,6 +4005,51 @@ of the instance declaration, thus:
 (You need <link linkend="instance-rules"><option>-XFlexibleInstances</option></link> to do this.)
 </para>
 <para>
+Warning: overlapping instances must be used with care.  They 
+can give rise to incoherence (ie different instance choices are made
+in different parts of the program) even without <option>-XIncoherentInstances</option>. Consider:
+<programlisting>
+{-# LANGUAGE OverlappingInstances #-}
+module Help where
+
+    class MyShow a where
+      myshow :: a -> String
+
+    instance MyShow a => MyShow [a] where
+      myshow xs = concatMap myshow xs
+
+    showHelp :: MyShow a => [a] -> String
+    showHelp xs = myshow xs
+
+{-# LANGUAGE FlexibleInstances, OverlappingInstances #-}
+module Main where
+    import Help
+
+    data T = MkT
+
+    instance MyShow T where
+      myshow x = "Used generic instance"
+
+    instance MyShow [T] where
+      myshow xs = "Used more specific instance"
+
+    main = do { print (myshow [MkT]); print (showHelp [MkT]) }
+</programlisting>
+In function <literal>showHelp</literal> GHC sees no overlapping
+instances, and so uses the <literal>MyShow [a]</literal> instance
+without complaint.  In the call to <literal>myshow</literal> in <literal>main</literal>,
+GHC resolves the <literal>MyShow [T]</literal> constraint using the overlapping
+instance declaration in module <literal>Main</literal>. As a result, 
+the program prints
+<programlisting>
+  "Used more specific instance"
+  "Used generic instance"
+</programlisting>
+(An alternative possible behaviour, not currently implemented, 
+would be to reject module <literal>Help</literal>
+on the grounds that a later instance declaration might overlap the local one.)
+</para>
+<para>
 The willingness to be overlapped or incoherent is a property of 
 the <emphasis>instance declaration</emphasis> itself, controlled by the
 presence or otherwise of the <option>-XOverlappingInstances</option> 
@@ -5667,6 +5784,9 @@ for rank-2 types.
 <sect2 id="impredicative-polymorphism">
 <title>Impredicative polymorphism
 </title>
+<para><emphasis>NOTE: the impredicative-polymorphism feature is deprecated in GHC 6.12, and
+will be removed or replaced in GHC 6.14.</emphasis></para>
+
 <para>GHC supports <emphasis>impredicative polymorphism</emphasis>, 
 enabled with <option>-XImpredicativeTypes</option>.  
 This means
@@ -7521,6 +7641,14 @@ itself, so an INLINE pragma is always ignored.</para>
         portable).</para>
       </sect3>
 
+      <sect3 id="conlike-pragma">
+       <title>CONLIKE modifier</title>
+       <indexterm><primary>CONLIKE</primary></indexterm>
+        <para>An INLINE or NOINLINE pragma may have a CONLIKE modifier, 
+        which affects matching in RULEs (only).  See <xref linkend="conlike"/>.
+        </para>
+      </sect3>
+
       <sect3 id="phase-control">
        <title>Phase control</title>
 
@@ -8156,18 +8284,24 @@ not be substituted, and the rule would not fire.
 
 </para>
 </listitem>
-<listitem>
+</itemizedlist>
+
+</para>
+
+</sect2>
+
+<sect2 id="conlike">
+<title>How rules interact with INLINE/NOINLINE and CONLIKE pragmas</title>
 
 <para>
 Ordinary inlining happens at the same time as rule rewriting, which may lead to unexpected
 results.  Consider this (artificial) example
 <programlisting>
 f x = x
-{-# RULES "f" f True = False #-}
-
 g y = f y
-
 h z = g True
+
+{-# RULES "f" f True = False #-}
 </programlisting>
 Since <literal>f</literal>'s right-hand side is small, it is inlined into <literal>g</literal>,
 to give
@@ -8181,14 +8315,37 @@ would have been a better chance that <literal>f</literal>'s RULE might fire.
 </para>
 <para>
 The way to get predictable behaviour is to use a NOINLINE 
-pragma on <literal>f</literal>, to ensure
+pragma, or an INLINE[<replaceable>phase</replaceable>] pragma, on <literal>f</literal>, to ensure
 that it is not inlined until its RULEs have had a chance to fire.
 </para>
-</listitem>
-</itemizedlist>
-
+<para>
+GHC is very cautious about duplicating work.  For example, consider
+<programlisting>
+f k z xs = let xs = build g
+           in ...(foldr k z xs)...sum xs...
+{-# RULES "foldr/build" forall k z g. foldr k z (build g) = g k z #-}
+</programlisting>
+Since <literal>xs</literal> is used twice, GHC does not fire the foldr/build rule.  Rightly
+so, because it might take a lot of work to compute <literal>xs</literal>, which would be
+duplicated if the rule fired.
+</para>
+<para>
+Sometimes, however, this approach is over-cautious, and we <emphasis>do</emphasis> want the
+rule to fire, even though doing so would duplicate redex.  There is no way that GHC can work out
+when this is a good idea, so we provide the CONLIKE pragma to declare it, thus:
+<programlisting>
+{-# INLINE[1] CONLIKE f #-}
+f x = <replaceable>blah</replaceable>
+</programlisting>
+CONLIKE is a modifier to an INLINE or NOINLINE pragam.  It specifies that an application
+of f to one argument (in general, the number of arguments to the left of the '=' sign)
+should be considered cheap enough to duplicate, if such a duplication would make rule
+fire.  (The name "CONLIKE" is short for "constructor-like", because constructors certainly
+have such a property.)
+The CONLIKE pragam is a modifier to INLINE/NOINLINE because it really only makes sense to match 
+<literal>f</literal> on the LHS of a rule if you are sure that <literal>f</literal> is
+not going to be inlined before the rule has a chance to fire.
 </para>
-
 </sect2>
 
 <sect2>
@@ -8460,15 +8617,22 @@ comparison.
  Use <option>-ddump-rules</option> to see what transformation rules GHC is using.
 </para>
 </listitem>
-<listitem>
 
+<listitem>
 <para>
  Use <option>-ddump-simpl-stats</option> to see what rules are being fired.
 If you add <option>-dppr-debug</option> you get a more detailed listing.
 </para>
 </listitem>
+
 <listitem>
+<para>
+ Use <option>-ddump-rule-firings</option> to see in great detail what rules are being fired.
+If you add <option>-dppr-debug</option> you get a still more detailed listing.
+</para>
+</listitem>
 
+<listitem>
 <para>
  The definition of (say) <function>build</function> in <filename>GHC/Base.lhs</filename> looks like this: