<chapter id="hugs-ghc">
<title>Language extensions supported by Hugs and GHC</title>

<para>These experimental features are enabled with the <option>-98</option>
option.
Most are described in
<ulink url="http://cvs.haskell.org/Hugs/pages/hugsman/exts.html">Section 7 of the <citetitle pubwork="article">Hugs 98 User Manual</citetitle></ulink>.
Those described in this chapter are also supported by
<ulink url="http://www.haskell.org/ghc/">GHC</ulink>
with appropriate options,
though in some cases the GHC versions are more general
</para>

<sect1 id="syntax-extensions">
<title>Syntactic extensions</title>

<sect2 id="recursive-do">
<title>Recursive do-notation</title>

<para>
The recursive do-notation (also known as mdo-notation) is implemented
as described in:

    <citetitle pubwork="article">A recursive do for Haskell</citetitle>,
    Levent Erk&ouml;k and John Launchbury,
    <citetitle pubwork="book">Haskell Workshop 2002</citetitle>,
    pages: 29&ndash;37. Pittsburgh, Pennsylvania.
</para>

<para>
The do-notation of Haskell does not allow recursive bindings, that is,
the variables bound in a do-expression are visible only in the textually
following code block. Compare this to a let-expression, where bound
variables are visible in the entire binding group. It turns out that
several applications can benefit from recursive bindings in the do-notation,
and this extension provides the necessary syntactic support.
</para>

<para>
Here is a simple (yet contrived) example:
<programlisting><![CDATA[
  import Control.Monad.Fix

  justOnes = mdo xs <- Just (1:xs)
                 return xs
]]></programlisting>
As you can guess <literal>justOnes</literal> will evaluate to
<literal>Just [1,1,1,...</literal>
</para>

<para>
The <literal>Control.Monad.Fix</literal> module introduces
the <literal>MonadFix</literal> class, defined as
<programlisting>
  class Monad m => MonadFix m where
      mfix :: (a -> m a) -> m a
</programlisting>
The function <literal>mfix</literal> dictates how the required recursion
operation should be performed.
If recursive bindings are required for a monad, then that
monad must be declared an instance of the <literal>MonadFix</literal> class.
For details, see the above mentioned reference.
</para>

<para>
The <literal>Control.Monad.Fix</literal> module also defines instances of
<literal>MonadFix</literal> for <literal>List</literal>,
<literal>Maybe</literal> and <literal>IO</literal>.
Furthermore, several other monad modules provide instances of the
<literal>MonadFix</literal> class, including
the <literal>Control.Monad.ST</literal> and
<literal>Control.Monad.ST.Lazy</literal>
modules for Haskell's internal state monad (strict and lazy, respectively).
</para>

<para>
There are three important points in using the recursive-do notation:
<itemizedlist>
<listitem><para>
The recursive version of the do-notation uses
the keyword <literal>mdo</literal> (rather than <literal>do</literal>).
</para></listitem>

<listitem><para>
You should <quote><literal>import Control.Monad.Fix</literal></quote>.
</para></listitem>

<listitem><para>
Hugs should be started with the flag <option>-98</option>.
</para></listitem>
</itemizedlist>
The web page: <quote><ulink url="http://www.cse.ogi.edu/PacSoft/projects/rmb">http://www.cse.ogi.edu/PacSoft/projects/rmb</ulink></quote>
contains up to date information on recursive monadic bindings.
</para>

<para>
Historical note: The old implementation of the mdo-notation (and most
of the existing documents) used the name <literal>MonadRec</literal>
for the class and the corresponding library.
</para>

</sect2>

<sect2 id="zip-comprehension">
<title>Parallel list comprehensions (a.k.a. zip-comprehensions)</title>

<para>
Parallel list comprehensions are a natural extension to list comprehensions.
List comprehensions can be thought of as a nice syntax for writing maps and
filters.
Parallel comprehensions extend this to include the <literal>zipWith</literal>
family.
</para>

<para>
A parallel list comprehension has multiple independent branches of qualifier
lists, each separated by a <quote><literal>|</literal></quote> symbol.
For example, the following zips together two lists:
<programlisting><![CDATA[
   [ (x, y) | x <- xs | y <- ys ]
]]></programlisting>
The behavior of parallel list comprehensions follows that
of <literal>zip</literal>, in that
the resulting list will have the same length as the shortest branch.
</para>

<para>
We can define parallel list comprehensions by translation to regular
comprehensions.
Given a parallel comprehension of the form:
<programlisting><![CDATA[
   [ e | p1 <- e11, p2 <- e12, ...
       | q1 <- e21, q2 <- e22, ...
       ...
   ]
]]></programlisting>
This will be translated to:
<programlisting><![CDATA[
   [ e | ((p1,p2), (q1,q2), ...) <- zipN [(p1,p2) | p1 <- e11, p2 <- e12, ...]
                                         [(q1,q2) | q1 <- e21, q2 <- e22, ...]
                                         ...
   ]
]]></programlisting>
where <quote><replaceable>zipN</replaceable></quote>
is the appropriate zip for the given number of branches.
</para>

</sect2>

</sect1>

<sect1 id="class-extensions">
<title>Type class extensions</title>

<sect2 id="flexible-contexts">
<title>More flexible contexts</title>

<para>In Haskell 98, contexts consist of class constraints
on type variables applied to zero or more types, as in
<programlisting>
  f :: (Functor f, Num (f Int)) => f String -> f Int -> f Int
</programlisting>
In class and instance declarations only type variables may be constrained.
With the <option>-98</option> option,
any type may be constrained by a class, as in
<programlisting>
  g :: (C [a], D (a -> b)) => [a] -> b
</programlisting>
Classes are not limited to a single argument either
(see <xref linkend="multi-param"/>).
</para>

</sect2>

<sect2 id="flexible-instances">
<title>More flexible instance declarations</title>

<para>In Haskell 98, instances may only be declared for
a <literal>data</literal> or <literal>newtype</literal> type constructor
applied to type variables.
With the <option>-98</option> option, any type may be made an instance:
<programlisting>
  instance Monoid (a -> a) where ...
  instance Show (Tree Int) where ...
  instance MyClass a where ...
  instance C String where
</programlisting>
This relaxation, together with the relaxation of contexts mentioned above,
makes the checking of constraints undecidable in general
(because you can now code arbitrary Prolog programs using instances).
To ensure that type checking terminates,
Hugs imposes a limit on the depth of constraints it will check,
and type checking fails if this limit is reached.
You can raise the limit with the
<link linkend="option-constraint-cutoff"><option>-c</option></link> option,
but such a failure usually indicates that the type checker wasn't going to
terminate for the particular constraint problem you set it.
</para>

<para>Note that GHC implements a different solution, placing syntactic
restrictions on instances to ensure termination, though you can also
turn these off, in which case a depth limit like that in Hugs is used.
</para>

</sect2>

<sect2 id="overlapping-instances">
<title>Overlapping instances</title>

<para>
With the relaxation on the form of instances discussed in the previous
section, it seems we could write
<programlisting>
  class C a where c :: a
  instance C (Bool,a) where ...
  instance C (a,Char) where ...
</programlisting>
but then in the expression <literal>c :: (Bool,Char)</literal>,
either instance could be chosen.
For this reason, overlapping instances are forbidden:
<screen>
  ERROR "Test.hs":4 - Overlapping instances for class "C"
  *** This instance   : C (a,Char)
  *** Overlaps with   : C (Bool,a)
  *** Common instance : C (Bool,Char)
</screen>
However if the
<link linkend="option-overlapping"><option>+o</option></link> option is set,
they are permitted when one of the types is a substitution instance of
the other (but not equivalent to it), as in
<programlisting>
  class C a where toString :: a -> String
  instance C [Char] where ...
  instance C a => C [a] where ...
</programlisting>
Now for the type <literal>[Char]</literal>, the first instance is used;
for any type <literal>[<replaceable>t</replaceable>]</literal>,
where <replaceable>t</replaceable> is a type distinct from
<literal>Char</literal>, the second instance is used.
Note that the context plays no part in the acceptability of the instances,
or in the choice of which to use.
</para>

<para>
The above analysis omitted one case, where the type <literal>t</literal> is
a type variable, as in
<programlisting>
  f :: C a => [a] -> String
  f xs = toString xs
</programlisting>
We cannot decide which instance to choose, so Hugs rejects this definition.
However if the
<link linkend="option-overlapping"><option>+O</option></link> option is set,
this declaration is accepted, and the more general instance is selected,
even though this will be the wrong choice if <literal>f</literal> is later
applied to a list of <literal>Char</literal>.
</para>

<para>
Hugs used to have a <option>+m</option> option
(for multi-instance resolution,
if Hugs was compiled with <literal>MULTI_INST</literal> set),
which accepted more overlapping instances by deferring the choice between them,
but it is currently broken.
</para>

<para>
Sometimes one can avoid overlapping instances.
The particular example discussed above is similar to the situation described
by the <literal>Show</literal> class in the <literal>Prelude</literal>.
However there overlapping instances are avoided by adding the method
<literal>showList</literal> to the class
</para>

</sect2>

<sect2 id="multi-param">
<title>Multiple parameter type classes</title>

<para>
In Haskell 98, type classes have a single parameter;
they may be thought of as sets of types.
In Hugs, they may have one or more parameters,
corresponding to relations between types, e.g.
<programlisting>
  class Isomorphic a b where
    from :: a -> b
    to :: b -> a
</programlisting>
</para>

</sect2>

<sect2 id="functional-dependencies">
<title>Functional dependencies</title>

<para>
Multiple parameter type classes often lead to ambiguity.
Functional dependencies (inspired by relational databases)
provide a partial solution,
and were introduced in
<citetitle pubwork="article">Type Classes with Functional Dependencies</citetitle>,
Mark P. Jones, In
<citetitle pubwork="book">Proceedings of the 9th European Symposium on Programming</citetitle>, LNCS vol. 1782, Springer 2000.
</para>

<para>
Functional dependencies are introduced by a vertical bar:
<programlisting>
  class MyClass a b c | a -> b where
</programlisting>
This says that the <literal>b</literal> parameter is determined by the
<literal>a</literal> parameter;
there cannot be two instances of <literal>MyClass</literal> with the same
first parameter and different second parameters.
The type inference system then uses this information to resolve many
ambiguities.
You can have several dependencies:
<programlisting>
  class MyClass a b c | a -> b, a -> c where
</programlisting>
This example could also be written
<programlisting>
  class MyClass a b c | a -> b c where
</programlisting>
Similarly more than one type parameter may appear to the left of the arrow:
<programlisting>
  class MyClass a b c | a b -> c where
</programlisting>
This says that the <literal>c</literal> parameter is determined by the
<literal>a</literal> and <literal>b</literal> parameters together;
there cannot be two instances of <literal>MyClass</literal> with the same
first parameter and second parameters, but different third parameters.
</para>

</sect2>

</sect1>

<sect1 id="quantified-types">
<title>Quantified types</title>

<sect2 id="rank-2-types">
<title>Rank 2 types</title>

<para>In Haskell 98, all type signatures are implicitly universally
quantified at the outer level, for example
<programlisting>
  id :: a -> a
</programlisting>
Variables bound with a <literal>let</literal> or <literal>where</literal>
may be polymorphic, as in
<programlisting>
  let f x = x in (f True, f 'a')
</programlisting>
but function arguments may not be: Haskell 98 rejects
<programlisting>
  g f = (f True, f 'a')
</programlisting>
However, with the <option>-98</option>, the function <literal>g</literal>
may be given the signature
<programlisting>
  g :: (forall a. a -> a) -> (Bool, Char)
</programlisting>
This is called a <emphasis>rank 2</emphasis> type, because a function
argument is polymorphic, as indicated by the <literal>forall</literal>
quantifier.
</para>

<para>
Now the function <literal>g</literal> may be applied to expression whose
generalized type is at least as general as that declared.
In this case the choice is limited: we can write
<screen>
  g id
  g undefined
  g (const undefined)
</screen>
or various equivalent forms
<screen>
  g (\x -&gt; x)
  g (id . id . id)
  g (id id id)
</screen>
There are a number of restrictions on such functions:
<itemizedlist>
<listitem><para>
Functions that take polymorphic arguments must be given an explicit
type signature.
</para></listitem>

<listitem><para>
In the definition of the function, polymorphic arguments must be matched,
and can only be matched by a variable or wildcard (<literal>_</literal>)
pattern.
</para></listitem>

<listitem><para>
When such functions are used, the polymorphic arguments must be supplied:
you can't just use <literal>g</literal> on its own.
</para></listitem>
</itemizedlist>
GHC, which supports arbitrary rank polymorphism,
is able to relax some of these restrictions.
</para>

<para>
Hugs reports an error if a type variable in a <literal>forall</literal>
is unused in the enclosed type.
</para>

<para>
An important application of rank 2 types is the primitive
<programlisting>
  runST :: (forall s. ST s a) -> a
</programlisting>
in the module <literal>Control.Monad.ST</literal>.
Here the type signature ensures that objects created by the state monad,
whose types all refer to the parameter <literal>s</literal>,
are unused outside the application of <literal>runST</literal>.
Thus to use this module you need the <option>-98</option> option.
Also, from the restrictions above,
it follows that <literal>runST</literal> must always
be applied to its polymorphic argument.
Hugs does not permit either of
<programlisting>
  myRunST :: (forall s. ST s a) -> a
  myRunST = runST

  f x = runST $ do
        ...
        return y
</programlisting>
(though GHC does).
Instead, you can write
<programlisting>
  myRunST :: (forall s. ST s a) -> a
  myRunST x = runST x

  f x = runST (do
        ...
        return y)
</programlisting>
</para>

</sect2>

<sect2 id="polymorphic-components">
<title>Polymorphic components</title>

<para>Similarly, components of a constructor may be polymorphic:
<programlisting>
  newtype List a = MkList (forall r. r -> (a -> r -> r) -> r)
  newtype NatTrans f g = MkNT (forall a. f a -> g a)
  data MonadT m = MkMonad {
                  my_return :: forall a. a -> m a,
                  my_bind :: forall a b. m a -> (a -> m b) -> m b
                }
</programlisting>
So that the constructors have rank 2 types:
<programlisting>
  MkList :: (forall r. r -> (a -> r -> r) -> r) -> List a
  MkNT :: (forall a. f a -> g a) -> NatTrans f g
  MkMonad :: (forall a. a -> m a) ->
             (forall a b. m a -> (a -> m b) -> m b) -> MonadT m
</programlisting>
As with functions having rank 2 types, such a constructor must be supplied
with any polymorphic arguments when it is used in an expression.
</para>

<para>
The record update syntax cannot be used with records containing
polymorphic components.
</para>

</sect2>

<sect2 id="existential-quantification">
<title>Existential quantification</title>

<para>It is also possible to have existentially quantified constructors,
somewhat confusingly also specified with <literal>forall</literal>,
but before the constructor, as in
<programlisting>
  data Accum a = forall s. MkAccum s (a -> s -> s) (s -> a)
</programlisting>
This type describes objects with a state of an abstract type
<literal>s</literal>,
together with functions to update and query the state.
The <literal>forall</literal> is somewhat motivated by the polymorphic
type of the constructor <literal>MkAccum</literal>, which is
<programlisting>
  s -> (a -> s -> s) -> (s -> a) -> Accum a
</programlisting>
because it must be able to operate on any state.
</para>

<para>
Some sample values of the <literal>Accum</literal> type are:
<programlisting>
  adder = MkAccum 0 (+) id
  averager = MkAccum (0,0)
                     (\x (t,n) -> (t+x,n+1))
                     (uncurry (/))
</programlisting>
Unfortunately, existentially quantified constructors may not contain
named fields.
You also can't use <literal>deriving</literal> with existentially quantified
types.
</para>

<para>
When we match against an existentially quantified constructor, as in
<programlisting>
  runAccum (MkAccum s add get) [] = ??
</programlisting>
we do not know the type of <literal>s</literal>,
only that <literal>add</literal> and <literal>get</literal>
take arguments of the same type as <literal>s</literal>.
So our options are limited.  One possibility is
<programlisting>
  runAccum (MkAccum s add get) [] = get s
</programlisting>
Similarly we can also write
<programlisting>
  runAccum (MkAccum s add get) (x:xs) =
      runAccum (MkAccum (add x v) add get) xs
</programlisting>
</para>

<para>
This particular application of existentials &ndash; modelling objects &ndash;
may also be done with a Haskell 98 recursive type:
<programlisting>
  data Accum a = MkAccum { add_value :: a -> Accum a, get_value :: a}
</programlisting>
but other applications do require existentials.
</para>

</sect2>

</sect1>

<sect1 id="type-annotations">
<title>Type annotations in patterns</title>

<para>
Haskell 98 allows expressions to be annotated with type signatures.
With the <option>-98</option> option,
these annotations are also allowed on patterns:
<programlisting>
  f (x::Int) = fromIntegral x :: Double
</programlisting>
Moreover type variables in pattern annotations are treated specially:
unless the type variable is already bound (by another pattern annotation),
it is universally quantified over the pattern and its scope, e.g.
<programlisting>
  snoc (xs::[a]) (x::a) = xs++[x] :: [a]
</programlisting>
Occurrences of the type variable in type signatures within this scope
are bound to this type variable.
In the above example the second and third occurrences of <literal>a</literal>
are bound by the first.
This permits locally defined variables to be given signatures in situations
where it would be impossible in Haskell 98:
<programlisting>
  sortImage :: Ord b => (a -> b) -> [a] -> [a]
  sortImage (f::a->b) = sortBy cmp
      where
          cmp :: a -> a -> Ordering
          cmp x y = compare (f x) (f y)
</programlisting>
Note that the relationship between signature declarations and pattern
annotations is asymmetrical: pattern annotations may capture type variables
in signature declarations, but not vice versa.
There is no connection between the type variables in the type signature
of <literal>sortImage</literal> and those in its definition,
but the occurrence of <literal>a</literal> in the signature of
<literal>cmp</literal> is bound by the pattern <literal>(f::a-&gt;b)</literal>.
</para>

<para>
In GHC, type variables bound by pattern annotations are existentially
quantified, and so may be instantiated.
Thus the following is accepted by GHC but not Hugs:
<programlisting>
  g (xs::[a]) = xs ++ "\n"
</programlisting>
GHC also allows <emphasis>result type signatures</emphasis>,
where a type signature is attached to the left side of a function definition,
but Hugs does not.
</para>

</sect1>

<sect1 id="implicit-parameters">
<title>Implicit parameters</title>

<para> Implicit parameters are implemented as described in
<citetitle pubwork="article">Implicit parameters: dynamic scoping with static types</citetitle>,
J Lewis, MB Shields, E Meijer, J Launchbury,
<citetitle pubwork="book">27th ACM Symposium on Principles of Programming Languages (POPL'00)</citetitle>,
Boston, Jan 2000.
Note however that the binding syntax in that paper,
using keywords <literal>dlet</literal> and <literal>with</literal>,
has been replaced by the form presented below.
</para>

<para>(Most of the following, still rather incomplete,
documentation is due to Jeff Lewis.)</para>

<para>
A variable is called <emphasis>dynamically bound</emphasis> when it is
bound by the calling context of a function and
<emphasis>statically bound</emphasis> when bound by the callee's context.
In Haskell, all variables are statically bound.
Dynamic binding of variables is a notion that goes back to Lisp,
but was later discarded in more modern incarnations, such as Scheme,
as dynamic binding can be very confusing in an untyped language.
Unfortunately typed languages,
in particular Hindley-Milner typed languages like Haskell,
only support static scoping of variables.
</para>

<para>
However, by a simple extension to the type class system of Haskell,
we can support dynamic binding.
Basically, we express the use of a dynamically bound variable
as a constraint on the type.
These constraints lead to types of the form <literal>(?x::t') => t</literal>,
which says
<quote>this function uses a dynamically-bound variable <literal>?x</literal>
of type <literal>t'</literal></quote>.
For example,
the following expresses the type of a <literal>sort</literal> function,
implicitly parameterized by a comparison function named <literal>cmp</literal>.
<programlisting>
  sort :: (?cmp :: a -> a -> Bool) => [a] -> [a]
</programlisting>
The dynamic binding constraints are just a new form of predicate
in the type class system.
</para>

<para>
An implicit parameter occurs in an expression using the special form
<literal>?x</literal>,
where <literal>x</literal> is any valid identifier
(e.g. <literal>ord ?x</literal> is a valid expression).
Use of this construct also introduces a new
dynamic-binding constraint in the type of the expression.
For example, the following definition
shows how we can define an implicitly parameterized sort function in
terms of an explicitly parameterized <literal>sortBy</literal> function:
<programlisting>
  sortBy :: (a -> a -> Bool) -> [a] -> [a]

  sort   :: (?cmp :: a -> a -> Bool) => [a] -> [a]
  sort    = sortBy ?cmp
</programlisting>
</para>

<sect2>
<title>Implicit-parameter type constraints</title>

<para>
Dynamic binding constraints behave just like other type class
constraints in that they are automatically propagated.
Thus, when a function is used,
its implicit parameters are inherited by the function that called it.
For example, our <literal>sort</literal> function might be used
to pick out the least value in a list:
<programlisting>
  least   :: (?cmp :: a -> a -> Bool) => [a] -> a
  least xs = fst (sort xs)
</programlisting>
Without lifting a finger, the <literal>?cmp</literal> parameter is
propagated to become a parameter of <literal>least</literal> as well.
With explicit parameters,
the default is that parameters must always be explicit propagated.
With implicit parameters, the default is to always propagate them.
</para>

<para>
An implicit-parameter type constraint differs from other type class
constraints in the following way:
all uses of a particular implicit parameter must have the same type.
This means that the type of <literal>(?x, ?x)</literal>
is <literal>(?x::a) => (a,a)</literal>, and not
<literal>(?x::a, ?x::b) => (a, b)</literal>, as would be the case for type
class constraints.
</para>

<para>
You can't have an implicit parameter in the context of a class or instance
declaration.  For example, both these declarations are illegal:
<programlisting>
  class (?x::Int) => C a where ...
  instance (?x::a) => Foo [a] where ...
</programlisting>
Reason: exactly which implicit parameter you pick up depends on exactly where
you invoke a function.
But the <quote>invocation</quote> of instance declarations is done behind
the scenes by the compiler,
so it's hard to figure out exactly where it is done.
The easiest thing is to outlaw the offending types.
</para>

<para>
Implicit-parameter constraints do not cause ambiguity.
For example, consider:
<programlisting>
  f :: (?x :: [a]) => Int -> Int
  f n = n + length ?x

  g :: (Read a, Show a) => String -> String
  g s = show (read s)
</programlisting>
Here, <literal>g</literal> has an ambiguous type, and is rejected,
but <literal>f</literal> is fine.
The binding for <literal>?x</literal> at <literal>f</literal>'s call site is
quite unambiguous, and fixes the type <literal>a</literal>.
</para>

</sect2>

<sect2>
<title>Implicit-parameter bindings</title>

<para>
An implicit parameter is <emphasis>bound</emphasis> using the standard
<literal>let</literal> or <literal>where</literal> binding forms.
For example, we define the <literal>min</literal> function by binding
<literal>cmp</literal>:
<programlisting><![CDATA[
  min :: [a] -> a
  min  = let ?cmp = (<=) in least
]]></programlisting>
</para>

<para>
A group of implicit-parameter bindings may occur anywhere a normal group
of Haskell bindings can occur, except at top level.
That is, they can occur in a <literal>let</literal>
(including in a list comprehension or do-notation),
or a <literal>where</literal> clause.
Note the following points:
<itemizedlist>
<listitem><para>
An implicit-parameter binding group must be a
collection of simple bindings to implicit-style variables
(no function-style bindings, and no type signatures);
these bindings are neither polymorphic or recursive.
</para></listitem>

<listitem><para>
You may not mix implicit-parameter bindings with ordinary bindings in a
single <literal>let</literal> expression;
use two nested <literal>let</literal>s instead.
(In the case of <literal>where</literal> you are stuck,
since you can't nest <literal>where</literal> clauses.)
</para></listitem>

<listitem><para>
You may put multiple implicit-parameter bindings in a single binding group;
but they are <emphasis>not</emphasis> treated as a mutually recursive group
(as ordinary <literal>let</literal> bindings are).
Instead they are treated as a non-recursive group,
simultaneously binding all the implicit parameters.
The bindings are not nested, and may be re-ordered without changing
the meaning of the program.
For example, consider:
<programlisting>
  f t = let { ?x = t; ?y = ?x+(1::Int) } in ?x + ?y
</programlisting>
The use of <literal>?x</literal> in the binding for <literal>?y</literal>
does not <quote>see</quote> the binding for <literal>?x</literal>,
so the type of <literal>f</literal> is
<programlisting>
  f :: (?x::Int) => Int -> Int
</programlisting>
</para></listitem>
</itemizedlist>
</para>

</sect2>

</sect1>

</chapter>
