2 <IndexTerm><Primary>language, GHC</Primary></IndexTerm>
3 <IndexTerm><Primary>extensions, GHC</Primary></IndexTerm>
4 As with all known Haskell systems, GHC implements some extensions to
5 the language. To use them, you'll need to give a <Literal>-fglasgow-exts</Literal>
6 <IndexTerm><Primary>-fglasgow-exts option</Primary></IndexTerm> option.
10 Virtually all of the Glasgow extensions serve to give you access to
11 the underlying facilities with which we implement Haskell. Thus, you
12 can get at the Raw Iron, if you are willing to write some non-standard
13 code at a more primitive level. You need not be ``stuck'' on
14 performance because of the implementation costs of Haskell's
15 ``high-level'' features—you can always code ``under'' them. In an
16 extreme case, you can write all your time-critical code in C, and then
17 just glue it together with Haskell!
21 Executive summary of our extensions:
28 <Term>Unboxed types and primitive operations:</Term>
31 You can get right down to the raw machine types and operations;
32 included in this are ``primitive arrays'' (direct access to Big Wads
33 of Bytes). Please see <XRef LinkEnd="glasgow-unboxed"> and following.
39 <Term>Multi-parameter type classes:</Term>
42 GHC's type system supports extended type classes with multiple
43 parameters. Please see <XRef LinkEnd="multi-param-type-classes">.
49 <Term>Local universal quantification:</Term>
52 GHC's type system supports explicit universal quantification in
53 constructor fields and function arguments. This is useful for things
54 like defining <Literal>runST</Literal> from the state-thread world. See <XRef LinkEnd="universal-quantification">.
60 <Term>Extistentially quantification in data types:</Term>
63 Some or all of the type variables in a datatype declaration may be
64 <Emphasis>existentially quantified</Emphasis>. More details in <XRef LinkEnd="existential-quantification">.
70 <Term>Scoped type variables:</Term>
73 Scoped type variables enable the programmer to supply type signatures
74 for some nested declarations, where this would not be legal in Haskell
75 98. Details in <XRef LinkEnd="scoped-type-variables">.
81 <Term>Calling out to C:</Term>
84 Just what it sounds like. We provide <Emphasis>lots</Emphasis> of rope that you
85 can dangle around your neck. Please see <XRef LinkEnd="glasgow-ccalls">.
94 Pragmas are special instructions to the compiler placed in the source
95 file. The pragmas GHC supports are described in <XRef LinkEnd="pragmas">.
101 <Term>Rewrite rules:</Term>
104 The programmer can specify rewrite rules as part of the source program
105 (in a pragma). GHC applies these rewrite rules wherever it can.
106 Details in <XRef LinkEnd="rewrite-rules">.
114 Before you get too carried away working at the lowest level (e.g.,
115 sloshing <Literal>MutableByteArray#</Literal>s around your program), you may wish to
116 check if there are system libraries that provide a ``Haskellised
117 veneer'' over the features you want. See <XRef LinkEnd="ghc-prelude">.
120 <Sect1 id="glasgow-unboxed">
125 <IndexTerm><Primary>Unboxed types (Glasgow extension)</Primary></IndexTerm>
129 These types correspond to the ``raw machine'' types you would use in
130 C: <Literal>Int#</Literal> (long int), <Literal>Double#</Literal> (double), <Literal>Addr#</Literal> (void *), etc. The
131 <Emphasis>primitive operations</Emphasis> (PrimOps) on these types are what you
132 might expect; e.g., <Literal>(+#)</Literal> is addition on <Literal>Int#</Literal>s, and is the
133 machine-addition that we all know and love—usually one instruction.
137 There are some restrictions on the use of unboxed types, the main one
138 being that you can't pass an unboxed value to a polymorphic function
139 or store one in a polymorphic data type. This rules out things like
140 <Literal>[Int#]</Literal> (ie. lists of unboxed integers). The reason for this
141 restriction is that polymorphic arguments and constructor fields are
142 assumed to be pointers: if an unboxed integer is stored in one of
143 these, the garbage collector would attempt to follow it, leading to
144 unpredictable space leaks. Or a <Literal>seq</Literal> operation on the polymorphic
145 component may attempt to dereference the pointer, with disastrous
146 results. Even worse, the unboxed value might be larger than a pointer
147 (<Literal>Double#</Literal> for instance).
151 Nevertheless, A numerically-intensive program using unboxed types can
152 go a <Emphasis>lot</Emphasis> faster than its ``standard'' counterpart—we saw a
153 threefold speedup on one example.
157 Please see <XRef LinkEnd="ghc-libs-ghc"> for the details of unboxed types and the
163 <Sect1 id="glasgow-ST-monad">
164 <Title>Primitive state-transformer monad
168 <IndexTerm><Primary>state transformers (Glasgow extensions)</Primary></IndexTerm>
169 <IndexTerm><Primary>ST monad (Glasgow extension)</Primary></IndexTerm>
173 This monad underlies our implementation of arrays, mutable and
174 immutable, and our implementation of I/O, including ``C calls''.
178 The <Literal>ST</Literal> library, which provides access to the <Literal>ST</Literal> monad, is a
179 GHC/Hugs extension library and is described in the separate <ULink
181 >GHC/Hugs Extension Libraries</ULink
187 <Sect1 id="glasgow-prim-arrays">
188 <Title>Primitive arrays, mutable and otherwise
192 <IndexTerm><Primary>primitive arrays (Glasgow extension)</Primary></IndexTerm>
193 <IndexTerm><Primary>arrays, primitive (Glasgow extension)</Primary></IndexTerm>
197 GHC knows about quite a few flavours of Large Swathes of Bytes.
201 First, GHC distinguishes between primitive arrays of (boxed) Haskell
202 objects (type <Literal>Array# obj</Literal>) and primitive arrays of bytes (type
203 <Literal>ByteArray#</Literal>).
207 Second, it distinguishes between…
211 <Term>Immutable:</Term>
214 Arrays that do not change (as with ``standard'' Haskell arrays); you
215 can only read from them. Obviously, they do not need the care and
216 attention of the state-transformer monad.
221 <Term>Mutable:</Term>
224 Arrays that may be changed or ``mutated.'' All the operations on them
225 live within the state-transformer monad and the updates happen
226 <Emphasis>in-place</Emphasis>.
231 <Term>``Static'' (in C land):</Term>
234 A C routine may pass an <Literal>Addr#</Literal> pointer back into Haskell land. There
235 are then primitive operations with which you may merrily grab values
236 over in C land, by indexing off the ``static'' pointer.
241 <Term>``Stable'' pointers:</Term>
244 If, for some reason, you wish to hand a Haskell pointer (i.e.,
245 <Emphasis>not</Emphasis> an unboxed value) to a C routine, you first make the
246 pointer ``stable,'' so that the garbage collector won't forget that it
247 exists. That is, GHC provides a safe way to pass Haskell pointers to
252 Please see <XRef LinkEnd="glasgow-stablePtrs"> for more details.
257 <Term>``Foreign objects'':</Term>
260 A ``foreign object'' is a safe way to pass an external object (a
261 C-allocated pointer, say) to Haskell and have Haskell do the Right
262 Thing when it no longer references the object. So, for example, C
263 could pass a large bitmap over to Haskell and say ``please free this
264 memory when you're done with it.''
268 Please see <XRef LinkEnd="glasgow-foreignObjs"> for more details.
276 The libraries section gives more details on all these ``primitive
277 array'' types and the operations on them, <XRef LinkEnd="ghc-prelude">. Some of these extensions
278 are also supported by Hugs, and the supporting libraries are described
281 >GHC/Hugs Extension Libraries</ULink
288 <Sect1 id="glasgow-ccalls">
289 <Title>Calling C directly from Haskell
293 <IndexTerm><Primary>C calls (Glasgow extension)</Primary></IndexTerm>
294 <IndexTerm><Primary>_ccall_ (Glasgow extension)</Primary></IndexTerm>
295 <IndexTerm><Primary>_casm_ (Glasgow extension)</Primary></IndexTerm>
299 GOOD ADVICE: Because this stuff is not Entirely Stable as far as names
300 and things go, you would be well-advised to keep your C-callery
301 corraled in a few modules, rather than sprinkled all over your code.
302 It will then be quite easy to update later on.
305 <Sect2 id="ccall-intro">
306 <Title><Literal>_ccall_</Literal> and <Literal>_casm_</Literal>: an introduction
310 The simplest way to use a simple C function
316 double fooC( FILE *in, char c, int i, double d, unsigned int u )
322 is to provide a Haskell wrapper:
328 fooH :: Char -> Int -> Double -> Word -> IO Double
329 fooH c i d w = _ccall_ fooC (``stdin''::Addr) c i d w
335 The function <Literal>fooH</Literal> will unbox all of its arguments, call the C
336 function <Literal>fooC</Literal> and box the corresponding arguments.
340 One of the annoyances about <Literal>_ccall_</Literal>s is when the C types don't quite
341 match the Haskell compiler's ideas. For this, the <Literal>_casm_</Literal> variant
342 may be just the ticket (NB: <Emphasis>no chance</Emphasis> of such code going
343 through a native-code generator):
353 = _casm_ ``%r = getenv((char *) %0);'' name >>= \ litstring ->
355 if (litstring == nullAddr) then
356 Left ("Fail:oldGetEnv:"++name)
358 Right (unpackCString litstring)
365 The first literal-literal argument to a <Literal>_casm_</Literal> is like a <Literal>printf</Literal>
366 format: <Literal>%r</Literal> is replaced with the ``result,'' <Literal>%0</Literal>--<Literal>%n-1</Literal> are
367 replaced with the 1st--nth arguments. As you can see above, it is an
368 easy way to do simple C casting. Everything said about <Literal>_ccall_</Literal> goes
369 for <Literal>_casm_</Literal> as well.
373 The use of <Literal>_casm_</Literal> in your code does pose a problem to the compiler
374 when it comes to generating an interface file for a freshly compiled
375 module. Included in an interface file is the unfolding (if any) of a
376 declaration. However, if a declaration's unfolding happens to contain
377 a <Literal>_casm_</Literal>, its unfolding will <Emphasis>not</Emphasis> be emitted into the interface
378 file even if it qualifies by all the other criteria. The reason why
379 the compiler prevents this from happening is that unfolding <Literal>_casm_</Literal>s
380 into an interface file unduly constrains how code that import your
381 module have to be compiled. If an imported declaration is unfolded and
382 it contains a <Literal>_casm_</Literal>, you now have to be using a compiler backend
383 capable of dealing with it (i.e., the C compiler backend). If you are
384 using the C compiler backend, the unfolded <Literal>_casm_</Literal> may still cause you
385 problems since the C code snippet it contains may mention CPP symbols
386 that were in scope when compiling the original module are not when
387 compiling the importing module.
391 If you're willing to put up with the drawbacks of doing cross-module
392 inlining of C code (GHC - A Better C Compiler :-), the option
393 <Literal>-funfold-casms-in-hi-file</Literal> will turn off the default behaviour.
394 <IndexTerm><Primary>-funfold-casms-in-hi-file option</Primary></IndexTerm>
399 <Sect2 id="glasgow-literal-literals">
400 <Title>Literal-literals
404 <IndexTerm><Primary>Literal-literals</Primary></IndexTerm>
408 The literal-literal argument to <Literal>_casm_</Literal> can be made use of separately
409 from the <Literal>_casm_</Literal> construct itself. Indeed, we've already used it:
415 fooH :: Char -> Int -> Double -> Word -> IO Double
416 fooH c i d w = _ccall_ fooC (``stdin''::Addr) c i d w
422 The first argument that's passed to <Literal>fooC</Literal> is given as a literal-literal,
423 that is, a literal chunk of C code that will be inserted into the generated
424 <Literal>.hc</Literal> code at the right place.
428 A literal-literal is restricted to having a type that's an instance of
429 the <Literal>CCallable</Literal> class, see <XRef LinkEnd="ccall-gotchas">
430 for more information.
434 Notice that literal-literals are by their very nature unfriendly to
435 native code generators, so exercise judgement about whether or not to
436 make use of them in your code.
441 <Sect2 id="glasgow-foreign-headers">
442 <Title>Using function headers
446 <IndexTerm><Primary>C calls, function headers</Primary></IndexTerm>
450 When generating C (using the <Literal>-fvia-C</Literal> directive), one can assist the
451 C compiler in detecting type errors by using the <Literal>-#include</Literal> directive
452 to provide <Literal>.h</Literal> files containing function headers.
462 typedef unsigned long *StgForeignObj;
465 void initialiseEFS (StgInt size);
466 StgInt terminateEFS (void);
467 StgForeignObj emptyEFS(void);
468 StgForeignObj updateEFS (StgForeignObj a, StgInt i, StgInt x);
469 StgInt lookupEFS (StgForeignObj a, StgInt i);
475 You can find appropriate definitions for <Literal>StgInt</Literal>, <Literal>StgForeignObj</Literal>,
476 etc using <Literal>gcc</Literal> on your architecture by consulting
477 <Literal>ghc/includes/StgTypes.h</Literal>. The following table summarises the
478 relationship between Haskell types and C types.
485 <ColSpec Align="Left" Colsep="0">
486 <ColSpec Align="Left" Colsep="0">
489 <Entry><Emphasis>C type name</Emphasis> </Entry>
490 <Entry> <Emphasis>Haskell Type</Emphasis> </Entry>
495 <Literal>StgChar</Literal> </Entry>
496 <Entry> <Literal>Char#</Literal> </Entry>
500 <Literal>StgInt</Literal> </Entry>
501 <Entry> <Literal>Int#</Literal> </Entry>
505 <Literal>StgWord</Literal> </Entry>
506 <Entry> <Literal>Word#</Literal> </Entry>
510 <Literal>StgAddr</Literal> </Entry>
511 <Entry> <Literal>Addr#</Literal> </Entry>
515 <Literal>StgFloat</Literal> </Entry>
516 <Entry> <Literal>Float#</Literal> </Entry>
520 <Literal>StgDouble</Literal> </Entry>
521 <Entry> <Literal>Double#</Literal> </Entry>
525 <Literal>StgArray</Literal> </Entry>
526 <Entry> <Literal>Array#</Literal> </Entry>
530 <Literal>StgByteArray</Literal> </Entry>
531 <Entry> <Literal>ByteArray#</Literal> </Entry>
535 <Literal>StgArray</Literal> </Entry>
536 <Entry> <Literal>MutableArray#</Literal> </Entry>
540 <Literal>StgByteArray</Literal> </Entry>
541 <Entry> <Literal>MutableByteArray#</Literal> </Entry>
545 <Literal>StgStablePtr</Literal> </Entry>
546 <Entry> <Literal>StablePtr#</Literal> </Entry>
550 <Literal>StgForeignObj</Literal> </Entry>
551 <Entry> <Literal>ForeignObj#</Literal></Entry>
560 Note that this approach is only <Emphasis>essential</Emphasis> for returning
561 <Literal>float</Literal>s (or if <Literal>sizeof(int) != sizeof(int *)</Literal> on your
562 architecture) but is a Good Thing for anyone who cares about writing
563 solid code. You're crazy not to do it.
568 <Sect2 id="glasgow-stablePtrs">
569 <Title>Subverting automatic unboxing with ``stable pointers''
573 <IndexTerm><Primary>stable pointers (Glasgow extension)</Primary></IndexTerm>
577 The arguments of a <Literal>_ccall_</Literal> are automatically unboxed before the
578 call. There are two reasons why this is usually the Right Thing to
588 C is a strict language: it would be excessively tedious to pass
589 unevaluated arguments and require the C programmer to force their
590 evaluation before using them.
597 Boxed values are stored on the Haskell heap and may be moved
598 within the heap if a garbage collection occurs—that is, pointers
599 to boxed objects are not <Emphasis>stable</Emphasis>.
608 It is possible to subvert the unboxing process by creating a ``stable
609 pointer'' to a value and passing the stable pointer instead. For
610 example, to pass/return an integer lazily to C functions <Literal>storeC</Literal> and
611 <Literal>fetchC</Literal>, one might write:
617 storeH :: Int -> IO ()
618 storeH x = makeStablePtr x >>= \ stable_x ->
619 _ccall_ storeC stable_x
622 fetchH x = _ccall_ fetchC >>= \ stable_x ->
623 deRefStablePtr stable_x >>= \ x ->
624 freeStablePtr stable_x >>
631 The garbage collector will refrain from throwing a stable pointer away
632 until you explicitly call one of the following from C or Haskell.
638 void freeStablePointer( StgStablePtr stablePtrToToss )
639 freeStablePtr :: StablePtr a -> IO ()
645 As with the use of <Literal>free</Literal> in C programs, GREAT CARE SHOULD BE
646 EXERCISED to ensure these functions are called at the right time: too
647 early and you get dangling references (and, if you're lucky, an error
648 message from the runtime system); too late and you get space leaks.
652 And to force evaluation of the argument within <Literal>fooC</Literal>, one would
653 call one of the following C functions (according to type of argument).
659 void performIO ( StgStablePtr stableIndex /* StablePtr s (IO ()) */ );
660 StgInt enterInt ( StgStablePtr stableIndex /* StablePtr s Int */ );
661 StgFloat enterFloat ( StgStablePtr stableIndex /* StablePtr s Float */ );
667 <IndexTerm><Primary>performIO</Primary></IndexTerm>
668 <IndexTerm><Primary>enterInt</Primary></IndexTerm>
669 <IndexTerm><Primary>enterFloat</Primary></IndexTerm>
673 Nota Bene: <Literal>_ccall_GC_</Literal><IndexTerm><Primary>_ccall_GC_</Primary></IndexTerm> must be used if any of
674 these functions are used.
679 <Sect2 id="glasgow-foreignObjs">
680 <Title>Foreign objects: pointing outside the Haskell heap
684 <IndexTerm><Primary>foreign objects (Glasgow extension)</Primary></IndexTerm>
688 There are two types that <Literal>ghc</Literal> programs can use to reference
689 (heap-allocated) objects outside the Haskell world: <Literal>Addr</Literal> and
690 <Literal>ForeignObj</Literal>.
694 If you use <Literal>Addr</Literal>, it is up to you to the programmer to arrange
695 allocation and deallocation of the objects.
699 If you use <Literal>ForeignObj</Literal>, <Literal>ghc</Literal>'s garbage collector will call upon the
700 user-supplied <Emphasis>finaliser</Emphasis> function to free the object when the
701 Haskell world no longer can access the object. (An object is
702 associated with a finaliser function when the abstract
703 Haskell type <Literal>ForeignObj</Literal> is created). The finaliser function is
704 expressed in C, and is passed as argument the object:
710 void foreignFinaliser ( StgForeignObj fo )
716 when the Haskell world can no longer access the object. Since
717 <Literal>ForeignObj</Literal>s only get released when a garbage collection occurs, we
718 provide ways of triggering a garbage collection from within C and from
725 void GarbageCollect()
732 More information on the programmers' interface to <Literal>ForeignObj</Literal> can be
733 found in the library documentation.
738 <Sect2 id="glasgow-avoiding-monads">
739 <Title>Avoiding monads
743 <IndexTerm><Primary>C calls to `pure C'</Primary></IndexTerm>
744 <IndexTerm><Primary>unsafePerformIO</Primary></IndexTerm>
748 The <Literal>_ccall_</Literal> construct is part of the <Literal>IO</Literal> monad because 9 out of 10
749 uses will be to call imperative functions with side effects such as
750 <Literal>printf</Literal>. Use of the monad ensures that these operations happen in a
751 predictable order in spite of laziness and compiler optimisations.
755 To avoid having to be in the monad to call a C function, it is
756 possible to use <Literal>unsafePerformIO</Literal>, which is available from the
757 <Literal>IOExts</Literal> module. There are three situations where one might like to
758 call a C function from outside the IO world:
767 Calling a function with no side-effects:
770 atan2d :: Double -> Double -> Double
771 atan2d y x = unsafePerformIO (_ccall_ atan2d y x)
773 sincosd :: Double -> (Double, Double)
774 sincosd x = unsafePerformIO $ do
775 da <- newDoubleArray (0, 1)
776 _casm_ ``sincosd( %0, &((double *)%1[0]), &((double *)%1[1]) );'' x da
777 s <- readDoubleArray da 0
778 c <- readDoubleArray da 1
788 Calling a set of functions which have side-effects but which can
789 be used in a purely functional manner.
791 For example, an imperative implementation of a purely functional
792 lookup-table might be accessed using the following functions.
797 update :: EFS x -> Int -> x -> EFS x
798 lookup :: EFS a -> Int -> a
800 empty = unsafePerformIO (_ccall_ emptyEFS)
802 update a i x = unsafePerformIO $
803 makeStablePtr x >>= \ stable_x ->
804 _ccall_ updateEFS a i stable_x
806 lookup a i = unsafePerformIO $
807 _ccall_ lookupEFS a i >>= \ stable_x ->
808 deRefStablePtr stable_x
812 You will almost always want to use <Literal>ForeignObj</Literal>s with this.
819 Calling a side-effecting function even though the results will
820 be unpredictable. For example the <Literal>trace</Literal> function is defined by:
824 trace :: String -> a -> a
827 ((_ccall_ PreTraceHook sTDERR{-msg-}):: IO ()) >>
828 fputs sTDERR string >>
829 ((_ccall_ PostTraceHook sTDERR{-msg-}):: IO ()) >>
832 sTDERR = (``stderr'' :: Addr)
836 (This kind of use is not highly recommended—it is only really
837 useful in debugging code.)
847 <Sect2 id="ccall-gotchas">
848 <Title>C-calling ``gotchas'' checklist
852 <IndexTerm><Primary>C call dangers</Primary></IndexTerm>
853 <IndexTerm><Primary>CCallable</Primary></IndexTerm>
854 <IndexTerm><Primary>CReturnable</Primary></IndexTerm>
858 And some advice, too.
867 For modules that use <Literal>_ccall_</Literal>s, etc., compile with
868 <Literal>-fvia-C</Literal>.<IndexTerm><Primary>-fvia-C option</Primary></IndexTerm> You don't have to, but you should.
870 Also, use the <Literal>-#include "prototypes.h"</Literal> flag (hack) to inform the C
871 compiler of the fully-prototyped types of all the C functions you
872 call. (<XRef LinkEnd="glasgow-foreign-headers"> says more about this…)
874 This scheme is the <Emphasis>only</Emphasis> way that you will get <Emphasis>any</Emphasis>
875 typechecking of your <Literal>_ccall_</Literal>s. (It shouldn't be that way, but…).
876 GHC will pass the flag <Literal>-Wimplicit</Literal> to gcc so that you'll get warnings
877 if any <Literal>_ccall_</Literal>ed functions have no prototypes.
884 Try to avoid <Literal>_ccall_</Literal>s to C functions that take <Literal>float</Literal>
885 arguments or return <Literal>float</Literal> results. Reason: if you do, you will
886 become entangled in (ANSI?) C's rules for when arguments/results are
887 promoted to <Literal>doubles</Literal>. It's a nightmare and just not worth it.
888 Use <Literal>doubles</Literal> if possible.
890 If you do use <Literal>floats</Literal>, check and re-check that the right thing is
891 happening. Perhaps compile with <Literal>-keep-hc-file-too</Literal> and look at
892 the intermediate C (<Literal>.hc</Literal> file).
899 The compiler uses two non-standard type-classes when
900 type-checking the arguments and results of <Literal>_ccall_</Literal>: the arguments
901 (respectively result) of <Literal>_ccall_</Literal> must be instances of the class
902 <Literal>CCallable</Literal> (respectively <Literal>CReturnable</Literal>). Both classes may be
903 imported from the module <Literal>CCall</Literal>, but this should only be
904 necessary if you want to define a new instance. (Neither class
905 defines any methods—their only function is to keep the
908 The type checker must be able to figure out just which of the
909 C-callable/returnable types is being used. If it can't, you have to
910 add type signatures. For example,
918 is not good enough, because the compiler can't work out what type <Literal>x</Literal>
919 is, nor what type the <Literal>_ccall_</Literal> returns. You have to write, say:
923 f :: Int -> IO Double
928 This table summarises the standard instances of these classes.
932 <ColSpec Align="Left" Colsep="0">
933 <ColSpec Align="Left" Colsep="0">
934 <ColSpec Align="Left" Colsep="0">
935 <ColSpec Align="Left" Colsep="0">
938 <Entry><Emphasis>Type</Emphasis> </Entry>
939 <Entry><Emphasis>CCallable</Emphasis></Entry>
940 <Entry><Emphasis>CReturnable</Emphasis> </Entry>
941 <Entry><Emphasis>Which is probably…</Emphasis> </Entry>
945 <Literal>Char</Literal> </Entry>
948 <Entry> <Literal>unsigned char</Literal> </Entry>
952 <Literal>Int</Literal> </Entry>
955 <Entry> <Literal>long int</Literal> </Entry>
959 <Literal>Word</Literal> </Entry>
962 <Entry> <Literal>unsigned long int</Literal> </Entry>
966 <Literal>Addr</Literal> </Entry>
969 <Entry> <Literal>void *</Literal> </Entry>
973 <Literal>Float</Literal> </Entry>
976 <Entry> <Literal>float</Literal> </Entry>
980 <Literal>Double</Literal> </Entry>
983 <Entry> <Literal>double</Literal> </Entry>
987 <Literal>()</Literal> </Entry>
990 <Entry> <Literal>void</Literal> </Entry>
994 <Literal>[Char]</Literal> </Entry>
997 <Entry> <Literal>char *</Literal> (null-terminated) </Entry>
1001 <Literal>Array</Literal> </Entry>
1002 <Entry> Yes </Entry>
1004 <Entry> <Literal>unsigned long *</Literal> </Entry>
1008 <Literal>ByteArray</Literal> </Entry>
1009 <Entry> Yes </Entry>
1011 <Entry> <Literal>unsigned long *</Literal> </Entry>
1015 <Literal>MutableArray</Literal> </Entry>
1016 <Entry> Yes </Entry>
1018 <Entry> <Literal>unsigned long *</Literal> </Entry>
1022 <Literal>MutableByteArray</Literal> </Entry>
1023 <Entry> Yes </Entry>
1025 <Entry> <Literal>unsigned long *</Literal> </Entry>
1029 <Literal>State</Literal> </Entry>
1030 <Entry> Yes </Entry>
1031 <Entry> Yes </Entry>
1032 <Entry> nothing!</Entry>
1036 <Literal>StablePtr</Literal> </Entry>
1037 <Entry> Yes </Entry>
1038 <Entry> Yes </Entry>
1039 <Entry> <Literal>unsigned long *</Literal> </Entry>
1043 <Literal>ForeignObjs</Literal> </Entry>
1044 <Entry> Yes </Entry>
1045 <Entry> Yes </Entry>
1046 <Entry> see later </Entry>
1054 Actually, the <Literal>Word</Literal> type is defined as being the same size as a
1055 pointer on the target architecture, which is <Emphasis>probably</Emphasis>
1056 <Literal>unsigned long int</Literal>.
1058 The brave and careful programmer can add their own instances of these
1059 classes for the following types:
1066 A <Emphasis>boxed-primitive</Emphasis> type may be made an instance of both
1067 <Literal>CCallable</Literal> and <Literal>CReturnable</Literal>.
1069 A boxed primitive type is any data type with a
1070 single unary constructor with a single primitive argument. For
1071 example, the following are all boxed primitive types:
1077 data XDisplay = XDisplay Addr#
1078 data EFS a = EFS# ForeignObj#
1084 instance CCallable (EFS a)
1085 instance CReturnable (EFS a)
1094 Any datatype with a single nullary constructor may be made an
1095 instance of <Literal>CReturnable</Literal>. For example:
1099 data MyVoid = MyVoid
1100 instance CReturnable MyVoid
1109 As at version 2.09, <Literal>String</Literal> (i.e., <Literal>[Char]</Literal>) is still
1110 not a <Literal>CReturnable</Literal> type.
1112 Also, the now-builtin type <Literal>PackedString</Literal> is neither
1113 <Literal>CCallable</Literal> nor <Literal>CReturnable</Literal>. (But there are functions in
1114 the PackedString interface to let you get at the necessary bits…)
1126 The code-generator will complain if you attempt to use <Literal>%r</Literal> in
1127 a <Literal>_casm_</Literal> whose result type is <Literal>IO ()</Literal>; or if you don't use <Literal>%r</Literal>
1128 <Emphasis>precisely</Emphasis> once for any other result type. These messages are
1129 supposed to be helpful and catch bugs—please tell us if they wreck
1137 If you call out to C code which may trigger the Haskell garbage
1138 collector or create new threads (examples of this later…), then you
1139 must use the <Literal>_ccall_GC_</Literal><IndexTerm><Primary>_ccall_GC_ primitive</Primary></IndexTerm> or
1140 <Literal>_casm_GC_</Literal><IndexTerm><Primary>_casm_GC_ primitive</Primary></IndexTerm> variant of C-calls. (This
1141 does not work with the native code generator - use <Literal>\fvia-C</Literal>.) This
1142 stuff is hairy with a capital H!
1154 <Sect1 id="multi-param-type-classes">
1155 <Title>Multi-parameter type classes
1159 This section documents GHC's implementation of multi-paramter type
1160 classes. There's lots of background in the paper <ULink
1161 URL="http://www.dcs.gla.ac.uk/~simonpj/multi.ps.gz"
1162 >Type classes: exploring the design space</ULink
1164 Jones, Mark Jones, Erik Meijer).
1168 I'd like to thank people who reported shorcomings in the GHC 3.02
1169 implementation. Our default decisions were all conservative ones, and
1170 the experience of these heroic pioneers has given useful concrete
1171 examples to support several generalisations. (These appear below as
1172 design choices not implemented in 3.02.)
1176 I've discussed these notes with Mark Jones, and I believe that Hugs
1177 will migrate towards the same design choices as I outline here.
1178 Thanks to him, and to many others who have offered very useful
1183 <Title>Types</Title>
1186 There are the following restrictions on the form of a qualified
1193 forall tv1..tvn (c1, ...,cn) => type
1199 (Here, I write the "foralls" explicitly, although the Haskell source
1200 language omits them; in Haskell 1.4, all the free type variables of an
1201 explicit source-language type signature are universally quantified,
1202 except for the class type variables in a class declaration. However,
1203 in GHC, you can give the foralls if you want. See <XRef LinkEnd="universal-quantification">).
1212 <Emphasis>Each universally quantified type variable
1213 <Literal>tvi</Literal> must be mentioned (i.e. appear free) in <Literal>type</Literal></Emphasis>.
1215 The reason for this is that a value with a type that does not obey
1216 this restriction could not be used without introducing
1217 ambiguity. Here, for example, is an illegal type:
1221 forall a. Eq a => Int
1225 When a value with this type was used, the constraint <Literal>Eq tv</Literal>
1226 would be introduced where <Literal>tv</Literal> is a fresh type variable, and
1227 (in the dictionary-translation implementation) the value would be
1228 applied to a dictionary for <Literal>Eq tv</Literal>. The difficulty is that we
1229 can never know which instance of <Literal>Eq</Literal> to use because we never
1230 get any more information about <Literal>tv</Literal>.
1237 <Emphasis>Every constraint <Literal>ci</Literal> must mention at least one of the
1238 universally quantified type variables <Literal>tvi</Literal></Emphasis>.
1240 For example, this type is OK because <Literal>C a b</Literal> mentions the
1241 universally quantified type variable <Literal>b</Literal>:
1245 forall a. C a b => burble
1249 The next type is illegal because the constraint <Literal>Eq b</Literal> does not
1250 mention <Literal>a</Literal>:
1254 forall a. Eq b => burble
1258 The reason for this restriction is milder than the other one. The
1259 excluded types are never useful or necessary (because the offending
1260 context doesn't need to be witnessed at this point; it can be floated
1261 out). Furthermore, floating them out increases sharing. Lastly,
1262 excluding them is a conservative choice; it leaves a patch of
1263 territory free in case we need it later.
1273 These restrictions apply to all types, whether declared in a type signature
1278 Unlike Haskell 1.4, constraints in types do <Emphasis>not</Emphasis> have to be of
1279 the form <Emphasis>(class type-variables)</Emphasis>. Thus, these type signatures
1286 f :: Eq (m a) => [m a] -> [m a]
1287 g :: Eq [a] => ...
1293 This choice recovers principal types, a property that Haskell 1.4 does not have.
1299 <Title>Class declarations</Title>
1307 <Emphasis>Multi-parameter type classes are permitted</Emphasis>. For example:
1311 class Collection c a where
1312 union :: c a -> c a -> c a
1323 <Emphasis>The class hierarchy must be acyclic</Emphasis>. However, the definition
1324 of "acyclic" involves only the superclass relationships. For example,
1330 op :: D b => a -> b -> b
1333 class C a => D a where { ... }
1337 Here, <Literal>C</Literal> is a superclass of <Literal>D</Literal>, but it's OK for a
1338 class operation <Literal>op</Literal> of <Literal>C</Literal> to mention <Literal>D</Literal>. (It
1339 would not be OK for <Literal>D</Literal> to be a superclass of <Literal>C</Literal>.)
1346 <Emphasis>There are no restrictions on the context in a class declaration
1347 (which introduces superclasses), except that the class hierarchy must
1348 be acyclic</Emphasis>. So these class declarations are OK:
1352 class Functor (m k) => FiniteMap m k where
1355 class (Monad m, Monad (t m)) => Transform t m where
1356 lift :: m a -> (t m) a
1365 <Emphasis>In the signature of a class operation, every constraint
1366 must mention at least one type variable that is not a class type
1367 variable</Emphasis>.
1373 class Collection c a where
1374 mapC :: Collection c b => (a->b) -> c a -> c b
1378 is OK because the constraint <Literal>(Collection a b)</Literal> mentions
1379 <Literal>b</Literal>, even though it also mentions the class variable
1380 <Literal>a</Literal>. On the other hand:
1385 op :: Eq a => (a,b) -> (a,b)
1389 is not OK because the constraint <Literal>(Eq a)</Literal> mentions on the class
1390 type variable <Literal>a</Literal>, but not <Literal>b</Literal>. However, any such
1391 example is easily fixed by moving the offending context up to the
1396 class Eq a => C a where
1397 op ::(a,b) -> (a,b)
1401 A yet more relaxed rule would allow the context of a class-op signature
1402 to mention only class type variables. However, that conflicts with
1403 Rule 1(b) for types above.
1410 <Emphasis>The type of each class operation must mention <Emphasis>all</Emphasis> of
1411 the class type variables</Emphasis>. For example:
1415 class Coll s a where
1417 insert :: s -> a -> s
1421 is not OK, because the type of <Literal>empty</Literal> doesn't mention
1422 <Literal>a</Literal>. This rule is a consequence of Rule 1(a), above, for
1423 types, and has the same motivation.
1425 Sometimes, offending class declarations exhibit misunderstandings. For
1426 example, <Literal>Coll</Literal> might be rewritten
1430 class Coll s a where
1432 insert :: s a -> a -> s a
1436 which makes the connection between the type of a collection of
1437 <Literal>a</Literal>'s (namely <Literal>(s a)</Literal>) and the element type <Literal>a</Literal>.
1438 Occasionally this really doesn't work, in which case you can split the
1446 class CollE s => Coll s a where
1447 insert :: s -> a -> s
1461 <Title>Instance declarations</Title>
1469 <Emphasis>Instance declarations may not overlap</Emphasis>. The two instance
1474 instance context1 => C type1 where ...
1475 instance context2 => C type2 where ...
1479 "overlap" if <Literal>type1</Literal> and <Literal>type2</Literal> unify
1481 However, if you give the command line option
1482 <Literal>-fallow-overlapping-instances</Literal><IndexTerm><Primary>-fallow-overlapping-instances
1483 option</Primary></IndexTerm> then two overlapping instance declarations are permitted
1491 EITHER <Literal>type1</Literal> and <Literal>type2</Literal> do not unify
1497 OR <Literal>type2</Literal> is a substitution instance of <Literal>type1</Literal>
1498 (but not identical to <Literal>type1</Literal>)
1511 Notice that these rules
1518 make it clear which instance decl to use
1519 (pick the most specific one that matches)
1526 do not mention the contexts <Literal>context1</Literal>, <Literal>context2</Literal>
1527 Reason: you can pick which instance decl
1528 "matches" based on the type.
1535 Regrettably, GHC doesn't guarantee to detect overlapping instance
1536 declarations if they appear in different modules. GHC can "see" the
1537 instance declarations in the transitive closure of all the modules
1538 imported by the one being compiled, so it can "see" all instance decls
1539 when it is compiling <Literal>Main</Literal>. However, it currently chooses not
1540 to look at ones that can't possibly be of use in the module currently
1541 being compiled, in the interests of efficiency. (Perhaps we should
1542 change that decision, at least for <Literal>Main</Literal>.)
1549 <Emphasis>There are no restrictions on the type in an instance
1550 <Emphasis>head</Emphasis>, except that at least one must not be a type variable</Emphasis>.
1551 The instance "head" is the bit after the "=>" in an instance decl. For
1552 example, these are OK:
1556 instance C Int a where ...
1558 instance D (Int, Int) where ...
1560 instance E [[a]] where ...
1564 Note that instance heads <Emphasis>may</Emphasis> contain repeated type variables.
1565 For example, this is OK:
1569 instance Stateful (ST s) (MutVar s) where ...
1573 The "at least one not a type variable" restriction is to ensure that
1574 context reduction terminates: each reduction step removes one type
1575 constructor. For example, the following would make the type checker
1576 loop if it wasn't excluded:
1580 instance C a => C a where ...
1584 There are two situations in which the rule is a bit of a pain. First,
1585 if one allows overlapping instance declarations then it's quite
1586 convenient to have a "default instance" declaration that applies if
1587 something more specific does not:
1596 Second, sometimes you might want to use the following to get the
1597 effect of a "class synonym":
1601 class (C1 a, C2 a, C3 a) => C a where { }
1603 instance (C1 a, C2 a, C3 a) => C a where { }
1607 This allows you to write shorter signatures:
1619 f :: (C1 a, C2 a, C3 a) => ...
1623 I'm on the lookout for a simple rule that preserves decidability while
1624 allowing these idioms. The experimental flag
1625 <Literal>-fallow-undecidable-instances</Literal><IndexTerm><Primary>-fallow-undecidable-instances
1626 option</Primary></IndexTerm> lifts this restriction, allowing all the types in an
1627 instance head to be type variables.
1634 <Emphasis>Unlike Haskell 1.4, instance heads may use type
1635 synonyms</Emphasis>. As always, using a type synonym is just shorthand for
1636 writing the RHS of the type synonym definition. For example:
1640 type Point = (Int,Int)
1641 instance C Point where ...
1642 instance C [Point] where ...
1646 is legal. However, if you added
1650 instance C (Int,Int) where ...
1654 as well, then the compiler will complain about the overlapping
1655 (actually, identical) instance declarations. As always, type synonyms
1656 must be fully applied. You cannot, for example, write:
1661 instance Monad P where ...
1665 This design decision is independent of all the others, and easily
1666 reversed, but it makes sense to me.
1673 <Emphasis>The types in an instance-declaration <Emphasis>context</Emphasis> must all
1674 be type variables</Emphasis>. Thus
1678 instance C a b => Eq (a,b) where ...
1686 instance C Int b => Foo b where ...
1690 is not OK. Again, the intent here is to make sure that context
1691 reduction terminates.
1693 Voluminous correspondence on the Haskell mailing list has convinced me
1694 that it's worth experimenting with a more liberal rule. If you use
1695 the flag <Literal>-fallow-undecidable-instances</Literal> you can use arbitrary
1696 types in an instance context. Termination is ensured by having a
1697 fixed-depth recursion stack. If you exceed the stack depth you get a
1698 sort of backtrace, and the opportunity to increase the stack depth
1699 with <Literal>-fcontext-stack</Literal><Emphasis>N</Emphasis>.
1712 <Sect1 id="universal-quantification">
1713 <Title>Explicit universal quantification
1717 GHC now allows you to write explicitly quantified types. GHC's
1718 syntax for this now agrees with Hugs's, namely:
1724 forall a b. (Ord a, Eq b) => a -> b -> a
1730 The context is, of course, optional. You can't use <Literal>forall</Literal> as
1731 a type variable any more!
1735 Haskell type signatures are implicitly quantified. The <Literal>forall</Literal>
1736 allows us to say exactly what this means. For example:
1754 g :: forall b. (b -> b)
1760 The two are treated identically.
1764 <Title>Universally-quantified data type fields
1768 In a <Literal>data</Literal> or <Literal>newtype</Literal> declaration one can quantify
1769 the types of the constructor arguments. Here are several examples:
1775 data T a = T1 (forall b. b -> b -> b) a
1777 data MonadT m = MkMonad { return :: forall a. a -> m a,
1778 bind :: forall a b. m a -> (a -> m b) -> m b
1781 newtype Swizzle = MkSwizzle (Ord a => [a] -> [a])
1787 The constructors now have so-called <Emphasis>rank 2</Emphasis> polymorphic
1788 types, in which there is a for-all in the argument types.:
1794 T1 :: forall a. (forall b. b -> b -> b) -> a -> T1 a
1795 MkMonad :: forall m. (forall a. a -> m a)
1796 -> (forall a b. m a -> (a -> m b) -> m b)
1798 MkSwizzle :: (Ord a => [a] -> [a]) -> Swizzle
1804 Notice that you don't need to use a <Literal>forall</Literal> if there's an
1805 explicit context. For example in the first argument of the
1806 constructor <Literal>MkSwizzle</Literal>, an implicit "<Literal>forall a.</Literal>" is
1807 prefixed to the argument type. The implicit <Literal>forall</Literal>
1808 quantifies all type variables that are not already in scope, and are
1809 mentioned in the type quantified over.
1813 As for type signatures, implicit quantification happens for non-overloaded
1814 types too. So if you write this:
1817 data T a = MkT (Either a b) (b -> b)
1820 it's just as if you had written this:
1823 data T a = MkT (forall b. Either a b) (forall b. b -> b)
1826 That is, since the type variable <Literal>b</Literal> isn't in scope, it's
1827 implicitly universally quantified. (Arguably, it would be better
1828 to <Emphasis>require</Emphasis> explicit quantification on constructor arguments
1829 where that is what is wanted. Feedback welcomed.)
1835 <Title>Construction </Title>
1838 You construct values of types <Literal>T1, MonadT, Swizzle</Literal> by applying
1839 the constructor to suitable values, just as usual. For example,
1845 (T1 (\xy->x) 3) :: T Int
1847 (MkSwizzle sort) :: Swizzle
1848 (MkSwizzle reverse) :: Swizzle
1853 Nothing -> Nothing
1855 MkMonad r b) :: MonadT Maybe
1861 The type of the argument can, as usual, be more general than the type
1862 required, as <Literal>(MkSwizzle reverse)</Literal> shows. (<Literal>reverse</Literal>
1863 does not need the <Literal>Ord</Literal> constraint.)
1869 <Title>Pattern matching</Title>
1872 When you use pattern matching, the bound variables may now have
1873 polymorphic types. For example:
1879 f :: T a -> a -> (a, Char)
1880 f (T1 f k) x = (f k x, f 'c' 'd')
1882 g :: (Ord a, Ord b) => Swizzle -> [a] -> (a -> b) -> [b]
1883 g (MkSwizzle s) xs f = s (map f (s xs))
1885 h :: MonadT m -> [m a] -> m [a]
1886 h m [] = return m []
1887 h m (x:xs) = bind m x $ \y ->
1888 bind m (h m xs) $ \ys ->
1895 In the function <Literal>h</Literal> we use the record selectors <Literal>return</Literal>
1896 and <Literal>bind</Literal> to extract the polymorphic bind and return functions
1897 from the <Literal>MonadT</Literal> data structure, rather than using pattern
1902 You cannot pattern-match against an argument that is polymorphic.
1906 newtype TIM s a = TIM (ST s (Maybe a))
1908 runTIM :: (forall s. TIM s a) -> Maybe a
1909 runTIM (TIM m) = runST m
1915 Here the pattern-match fails, because you can't pattern-match against
1916 an argument of type <Literal>(forall s. TIM s a)</Literal>. Instead you
1917 must bind the variable and pattern match in the right hand side:
1920 runTIM :: (forall s. TIM s a) -> Maybe a
1921 runTIM tm = case tm of { TIM m -> runST m }
1924 The <Literal>tm</Literal> on the right hand side is (invisibly) instantiated, like
1925 any polymorphic value at its occurrence site, and now you can pattern-match
1932 <Title>The partial-application restriction</Title>
1935 There is really only one way in which data structures with polymorphic
1936 components might surprise you: you must not partially apply them.
1937 For example, this is illegal:
1943 map MkSwizzle [sort, reverse]
1949 The restriction is this: <Emphasis>every subexpression of the program must
1950 have a type that has no for-alls, except that in a function
1951 application (f e1…en) the partial applications are not subject to
1952 this rule</Emphasis>. The restriction makes type inference feasible.
1956 In the illegal example, the sub-expression <Literal>MkSwizzle</Literal> has the
1957 polymorphic type <Literal>(Ord b => [b] -> [b]) -> Swizzle</Literal> and is not
1958 a sub-expression of an enclosing application. On the other hand, this
1965 map (T1 (\a b -> a)) [1,2,3]
1971 even though it involves a partial application of <Literal>T1</Literal>, because
1972 the sub-expression <Literal>T1 (\a b -> a)</Literal> has type <Literal>Int -> T
1979 <Title>Type signatures
1983 Once you have data constructors with universally-quantified fields, or
1984 constants such as <Literal>runST</Literal> that have rank-2 types, it isn't long
1985 before you discover that you need more! Consider:
1991 mkTs f x y = [T1 f x, T1 f y]
1997 <Literal>mkTs</Literal> is a fuction that constructs some values of type
1998 <Literal>T</Literal>, using some pieces passed to it. The trouble is that since
1999 <Literal>f</Literal> is a function argument, Haskell assumes that it is
2000 monomorphic, so we'll get a type error when applying <Literal>T1</Literal> to
2001 it. This is a rather silly example, but the problem really bites in
2002 practice. Lots of people trip over the fact that you can't make
2003 "wrappers functions" for <Literal>runST</Literal> for exactly the same reason.
2004 In short, it is impossible to build abstractions around functions with
2009 The solution is fairly clear. We provide the ability to give a rank-2
2010 type signature for <Emphasis>ordinary</Emphasis> functions (not only data
2011 constructors), thus:
2017 mkTs :: (forall b. b -> b -> b) -> a -> [T a]
2018 mkTs f x y = [T1 f x, T1 f y]
2024 This type signature tells the compiler to attribute <Literal>f</Literal> with
2025 the polymorphic type <Literal>(forall b. b -> b -> b)</Literal> when type
2026 checking the body of <Literal>mkTs</Literal>, so now the application of
2027 <Literal>T1</Literal> is fine.
2031 There are two restrictions:
2040 You can only define a rank 2 type, specified by the following
2045 rank2type ::= [forall tyvars .] [context =>] funty
2046 funty ::= ([forall tyvars .] [context =>] ty) -> funty
2048 ty ::= ...current Haskell monotype syntax...
2052 Informally, the universal quantification must all be right at the beginning,
2053 or at the top level of a function argument.
2060 There is a restriction on the definition of a function whose
2061 type signature is a rank-2 type: the polymorphic arguments must be
2062 matched on the left hand side of the "<Literal>=</Literal>" sign. You can't
2063 define <Literal>mkTs</Literal> like this:
2067 mkTs :: (forall b. b -> b -> b) -> a -> [T a]
2068 mkTs = \ f x y -> [T1 f x, T1 f y]
2073 The same partial-application rule applies to ordinary functions with
2074 rank-2 types as applied to data constructors.
2087 <Sect1 id="existential-quantification">
2088 <Title>Existentially quantified data constructors
2092 The idea of using existential quantification in data type declarations
2093 was suggested by Laufer (I believe, thought doubtless someone will
2094 correct me), and implemented in Hope+. It's been in Lennart
2095 Augustsson's <Literal>hbc</Literal> Haskell compiler for several years, and
2096 proved very useful. Here's the idea. Consider the declaration:
2102 data Foo = forall a. MkFoo a (a -> Bool)
2109 The data type <Literal>Foo</Literal> has two constructors with types:
2115 MkFoo :: forall a. a -> (a -> Bool) -> Foo
2122 Notice that the type variable <Literal>a</Literal> in the type of <Literal>MkFoo</Literal>
2123 does not appear in the data type itself, which is plain <Literal>Foo</Literal>.
2124 For example, the following expression is fine:
2130 [MkFoo 3 even, MkFoo 'c' isUpper] :: [Foo]
2136 Here, <Literal>(MkFoo 3 even)</Literal> packages an integer with a function
2137 <Literal>even</Literal> that maps an integer to <Literal>Bool</Literal>; and <Literal>MkFoo 'c'
2138 isUpper</Literal> packages a character with a compatible function. These
2139 two things are each of type <Literal>Foo</Literal> and can be put in a list.
2143 What can we do with a value of type <Literal>Foo</Literal>?. In particular,
2144 what happens when we pattern-match on <Literal>MkFoo</Literal>?
2150 f (MkFoo val fn) = ???
2156 Since all we know about <Literal>val</Literal> and <Literal>fn</Literal> is that they
2157 are compatible, the only (useful) thing we can do with them is to
2158 apply <Literal>fn</Literal> to <Literal>val</Literal> to get a boolean. For example:
2164 f :: Foo -> Bool
2165 f (MkFoo val fn) = fn val
2171 What this allows us to do is to package heterogenous values
2172 together with a bunch of functions that manipulate them, and then treat
2173 that collection of packages in a uniform manner. You can express
2174 quite a bit of object-oriented-like programming this way.
2177 <Sect2 id="existential">
2178 <Title>Why existential?
2182 What has this to do with <Emphasis>existential</Emphasis> quantification?
2183 Simply that <Literal>MkFoo</Literal> has the (nearly) isomorphic type
2189 MkFoo :: (exists a . (a, a -> Bool)) -> Foo
2195 But Haskell programmers can safely think of the ordinary
2196 <Emphasis>universally</Emphasis> quantified type given above, thereby avoiding
2197 adding a new existential quantification construct.
2203 <Title>Type classes</Title>
2206 An easy extension (implemented in <Literal>hbc</Literal>) is to allow
2207 arbitrary contexts before the constructor. For example:
2213 data Baz = forall a. Eq a => Baz1 a a
2214 | forall b. Show b => Baz2 b (b -> b)
2220 The two constructors have the types you'd expect:
2226 Baz1 :: forall a. Eq a => a -> a -> Baz
2227 Baz2 :: forall b. Show b => b -> (b -> b) -> Baz
2233 But when pattern matching on <Literal>Baz1</Literal> the matched values can be compared
2234 for equality, and when pattern matching on <Literal>Baz2</Literal> the first matched
2235 value can be converted to a string (as well as applying the function to it).
2236 So this program is legal:
2242 f :: Baz -> String
2243 f (Baz1 p q) | p == q = "Yes"
2245 f (Baz1 v fn) = show (fn v)
2251 Operationally, in a dictionary-passing implementation, the
2252 constructors <Literal>Baz1</Literal> and <Literal>Baz2</Literal> must store the
2253 dictionaries for <Literal>Eq</Literal> and <Literal>Show</Literal> respectively, and
2254 extract it on pattern matching.
2258 Notice the way that the syntax fits smoothly with that used for
2259 universal quantification earlier.
2265 <Title>Restrictions</Title>
2268 There are several restrictions on the ways in which existentially-quantified
2269 constructors can be use.
2278 When pattern matching, each pattern match introduces a new,
2279 distinct, type for each existential type variable. These types cannot
2280 be unified with any other type, nor can they escape from the scope of
2281 the pattern match. For example, these fragments are incorrect:
2289 Here, the type bound by <Literal>MkFoo</Literal> "escapes", because <Literal>a</Literal>
2290 is the result of <Literal>f1</Literal>. One way to see why this is wrong is to
2291 ask what type <Literal>f1</Literal> has:
2295 f1 :: Foo -> a -- Weird!
2299 What is this "<Literal>a</Literal>" in the result type? Clearly we don't mean
2304 f1 :: forall a. Foo -> a -- Wrong!
2308 The original program is just plain wrong. Here's another sort of error
2312 f2 (Baz1 a b) (Baz1 p q) = a==q
2316 It's ok to say <Literal>a==b</Literal> or <Literal>p==q</Literal>, but
2317 <Literal>a==q</Literal> is wrong because it equates the two distinct types arising
2318 from the two <Literal>Baz1</Literal> constructors.
2326 You can't pattern-match on an existentially quantified
2327 constructor in a <Literal>let</Literal> or <Literal>where</Literal> group of
2328 bindings. So this is illegal:
2332 f3 x = a==b where { Baz1 a b = x }
2336 You can only pattern-match
2337 on an existentially-quantified constructor in a <Literal>case</Literal> expression or
2338 in the patterns of a function definition.
2340 The reason for this restriction is really an implementation one.
2341 Type-checking binding groups is already a nightmare without
2342 existentials complicating the picture. Also an existential pattern
2343 binding at the top level of a module doesn't make sense, because it's
2344 not clear how to prevent the existentially-quantified type "escaping".
2345 So for now, there's a simple-to-state restriction. We'll see how
2353 You can't use existential quantification for <Literal>newtype</Literal>
2354 declarations. So this is illegal:
2358 newtype T = forall a. Ord a => MkT a
2362 Reason: a value of type <Literal>T</Literal> must be represented as a pair
2363 of a dictionary for <Literal>Ord t</Literal> and a value of type <Literal>t</Literal>.
2364 That contradicts the idea that <Literal>newtype</Literal> should have no
2365 concrete representation. You can get just the same efficiency and effect
2366 by using <Literal>data</Literal> instead of <Literal>newtype</Literal>. If there is no
2367 overloading involved, then there is more of a case for allowing
2368 an existentially-quantified <Literal>newtype</Literal>, because the <Literal>data</Literal>
2369 because the <Literal>data</Literal> version does carry an implementation cost,
2370 but single-field existentially quantified constructors aren't much
2371 use. So the simple restriction (no existential stuff on <Literal>newtype</Literal>)
2372 stands, unless there are convincing reasons to change it.
2380 You can't use <Literal>deriving</Literal> to define instances of a
2381 data type with existentially quantified data constructors.
2383 Reason: in most cases it would not make sense. For example:#
2386 data T = forall a. MkT [a] deriving( Eq )
2389 To derive <Literal>Eq</Literal> in the standard way we would need to have equality
2390 between the single component of two <Literal>MkT</Literal> constructors:
2394 (MkT a) == (MkT b) = ???
2397 But <Literal>a</Literal> and <Literal>b</Literal> have distinct types, and so can't be compared.
2398 It's just about possible to imagine examples in which the derived instance
2399 would make sense, but it seems altogether simpler simply to prohibit such
2400 declarations. Define your own instances!
2412 <Sect1 id="sec-assertions">
2414 <IndexTerm><Primary>Assertions</Primary></IndexTerm>
2418 If you want to make use of assertions in your standard Haskell code, you
2419 could define a function like the following:
2425 assert :: Bool -> a -> a
2426 assert False x = error "assertion failed!"
2433 which works, but gives you back a less than useful error message --
2434 an assertion failed, but which and where?
2438 One way out is to define an extended <Literal>assert</Literal> function which also
2439 takes a descriptive string to include in the error message and
2440 perhaps combine this with the use of a pre-processor which inserts
2441 the source location where <Literal>assert</Literal> was used.
2445 Ghc offers a helping hand here, doing all of this for you. For every
2446 use of <Literal>assert</Literal> in the user's source:
2452 kelvinToC :: Double -> Double
2453 kelvinToC k = assert (k &gt;= 0.0) (k+273.15)
2459 Ghc will rewrite this to also include the source location where the
2466 assert pred val ==> assertError "Main.hs|15" pred val
2472 The rewrite is only performed by the compiler when it spots
2473 applications of <Literal>Exception.assert</Literal>, so you can still define and
2474 use your own versions of <Literal>assert</Literal>, should you so wish. If not,
2475 import <Literal>Exception</Literal> to make use <Literal>assert</Literal> in your code.
2479 To have the compiler ignore uses of assert, use the compiler option
2480 <Literal>-fignore-asserts</Literal>. <IndexTerm><Primary>-fignore-asserts option</Primary></IndexTerm> That is,
2481 expressions of the form <Literal>assert pred e</Literal> will be rewritten to <Literal>e</Literal>.
2485 Assertion failures can be caught, see the documentation for the
2486 Hugs/GHC Exception library for information of how.
2491 <Sect1 id="scoped-type-variables">
2492 <Title>Scoped Type Variables
2496 A <Emphasis>pattern type signature</Emphasis> can introduce a <Emphasis>scoped type
2497 variable</Emphasis>. For example
2503 f (xs::[a]) = ys ++ ys
2512 The pattern <Literal>(xs::[a])</Literal> includes a type signature for <Literal>xs</Literal>.
2513 This brings the type variable <Literal>a</Literal> into scope; it scopes over
2514 all the patterns and right hand sides for this equation for <Literal>f</Literal>.
2515 In particular, it is in scope at the type signature for <Literal>y</Literal>.
2519 At ordinary type signatures, such as that for <Literal>ys</Literal>, any type variables
2520 mentioned in the type signature <Emphasis>that are not in scope</Emphasis> are
2521 implicitly universally quantified. (If there are no type variables in
2522 scope, all type variables mentioned in the signature are universally
2523 quantified, which is just as in Haskell 98.) In this case, since <Literal>a</Literal>
2524 is in scope, it is not universally quantified, so the type of <Literal>ys</Literal> is
2525 the same as that of <Literal>xs</Literal>. In Haskell 98 it is not possible to declare
2526 a type for <Literal>ys</Literal>; a major benefit of scoped type variables is that
2527 it becomes possible to do so.
2531 Scoped type variables are implemented in both GHC and Hugs. Where the
2532 implementations differ from the specification below, those differences
2537 So much for the basic idea. Here are the details.
2541 <Title>Scope and implicit quantification</Title>
2549 All the type variables mentioned in the patterns for a single
2550 function definition equation, that are not already in scope,
2551 are brought into scope by the patterns. We describe this set as
2552 the <Emphasis>type variables bound by the equation</Emphasis>.
2559 The type variables thus brought into scope may be mentioned
2560 in ordinary type signatures or pattern type signatures anywhere within
2568 In ordinary type signatures, any type variable mentioned in the
2569 signature that is in scope is <Emphasis>not</Emphasis> universally quantified.
2576 Ordinary type signatures do not bring any new type variables
2577 into scope (except in the type signature itself!). So this is illegal:
2586 It's illegal because <Literal>a</Literal> is not in scope in the body of <Literal>f</Literal>,
2587 so the ordinary signature <Literal>x::a</Literal> is equivalent to <Literal>x::forall a.a</Literal>;
2588 and that is an incorrect typing.
2595 There is no implicit universal quantification on pattern type
2596 signatures, nor may one write an explicit <Literal>forall</Literal> type in a pattern
2597 type signature. The pattern type signature is a monotype.
2605 The type variables in the head of a <Literal>class</Literal> or <Literal>instance</Literal> declaration
2606 scope over the methods defined in the <Literal>where</Literal> part. For example:
2620 (Not implemented in Hugs yet, Dec 98).
2631 <Title>Polymorphism</Title>
2639 Pattern type signatures are completely orthogonal to ordinary, separate
2640 type signatures. The two can be used independently or together. There is
2641 no scoping associated with the names of the type variables in a separate type signature.
2646 f (xs::[b]) = reverse xs
2655 The function must be polymorphic in the type variables
2656 bound by all its equations. Operationally, the type variables bound
2657 by one equation must not:
2664 Be unified with a type (such as <Literal>Int</Literal>, or <Literal>[a]</Literal>).
2670 Be unified with a type variable free in the environment.
2676 Be unified with each other. (They may unify with the type variables
2677 bound by another equation for the same function, of course.)
2684 For example, the following all fail to type check:
2688 f (x::a) (y::b) = [x,y] -- a unifies with b
2690 g (x::a) = x + 1::Int -- a unifies with Int
2692 h x = let k (y::a) = [x,y] -- a is free in the
2693 in k x -- environment
2695 k (x::a) True = ... -- a unifies with Int
2696 k (x::Int) False = ...
2699 w (x::a) = x -- a unifies with [b]
2708 The pattern-bound type variable may, however, be constrained
2709 by the context of the principal type, thus:
2713 f (x::a) (y::a) = x+y*2
2717 gets the inferred type: <Literal>forall a. Num a => a -> a -> a</Literal>.
2728 <Title>Result type signatures</Title>
2736 The result type of a function can be given a signature,
2741 f (x::a) :: [a] = [x,x,x]
2745 The final <Literal>":: [a]"</Literal> after all the patterns gives a signature to the
2746 result type. Sometimes this is the only way of naming the type variable
2751 f :: Int -> [a] -> [a]
2752 f n :: ([a] -> [a]) = let g (x::a, y::a) = (y,x)
2753 in \xs -> map g (reverse xs `zip` xs)
2765 Result type signatures are not yet implemented in Hugs.
2771 <Title>Pattern signatures on other constructs</Title>
2779 A pattern type signature can be on an arbitrary sub-pattern, not
2784 f ((x,y)::(a,b)) = (y,x) :: (b,a)
2793 Pattern type signatures, including the result part, can be used
2794 in lambda abstractions:
2798 (\ (x::a, y) :: a -> x)
2802 Type variables bound by these patterns must be polymorphic in
2803 the sense defined above.
2808 f1 (x::c) = f1 x -- ok
2809 f2 = \(x::c) -> f2 x -- not ok
2813 Here, <Literal>f1</Literal> is OK, but <Literal>f2</Literal> is not, because <Literal>c</Literal> gets unified
2814 with a type variable free in the environment, in this
2815 case, the type of <Literal>f2</Literal>, which is in the environment when
2816 the lambda abstraction is checked.
2823 Pattern type signatures, including the result part, can be used
2824 in <Literal>case</Literal> expressions:
2828 case e of { (x::a, y) :: a -> x }
2832 The pattern-bound type variables must, as usual,
2833 be polymorphic in the following sense: each case alternative,
2834 considered as a lambda abstraction, must be polymorphic.
2839 case (True,False) of { (x::a, y) -> x }
2843 Even though the context is that of a pair of booleans,
2844 the alternative itself is polymorphic. Of course, it is
2849 case (True,False) of { (x::Bool, y) -> x }
2858 To avoid ambiguity, the type after the ``<Literal>::</Literal>'' in a result
2859 pattern signature on a lambda or <Literal>case</Literal> must be atomic (i.e. a single
2860 token or a parenthesised type of some sort). To see why,
2861 consider how one would parse this:
2865 \ x :: a -> b -> x
2874 Pattern type signatures that bind new type variables
2875 may not be used in pattern bindings at all.
2880 f x = let (y, z::a) = x in ...
2884 But these are OK, because they do not bind fresh type variables:
2888 f1 x = let (y, z::Int) = x in ...
2889 f2 (x::(Int,a)) = let (y, z::a) = x in ...
2893 However a single variable is considered a degenerate function binding,
2894 rather than a degerate pattern binding, so this is permitted, even
2895 though it binds a type variable:
2899 f :: (b->b) = \(x::b) -> x
2908 Such degnerate function bindings do not fall under the monomorphism
2915 g :: a -> a -> Bool = \x y. x==y
2921 Here <Literal>g</Literal> has type <Literal>forall a. Eq a => a -> a -> Bool</Literal>, just as if
2922 <Literal>g</Literal> had a separate type signature. Lacking a type signature, <Literal>g</Literal>
2923 would get a monomorphic type.
2929 <Title>Existentials</Title>
2937 Pattern type signatures can bind existential type variables.
2942 data T = forall a. MkT [a]
2945 f (MkT [t::a]) = MkT t3
2962 <Sect1 id="pragmas">
2967 GHC supports several pragmas, or instructions to the compiler placed
2968 in the source code. Pragmas don't affect the meaning of the program,
2969 but they might affect the efficiency of the generated code.
2972 <Sect2 id="inline-pragma">
2973 <Title>INLINE pragma
2975 <IndexTerm><Primary>INLINE pragma</Primary></IndexTerm>
2976 <IndexTerm><Primary>pragma, INLINE</Primary></IndexTerm></Title>
2979 GHC (with <Literal>-O</Literal>, as always) tries to inline (or ``unfold'')
2980 functions/values that are ``small enough,'' thus avoiding the call
2981 overhead and possibly exposing other more-wonderful optimisations.
2985 You will probably see these unfoldings (in Core syntax) in your
2990 Normally, if GHC decides a function is ``too expensive'' to inline, it
2991 will not do so, nor will it export that unfolding for other modules to
2996 The sledgehammer you can bring to bear is the
2997 <Literal>INLINE</Literal><IndexTerm><Primary>INLINE pragma</Primary></IndexTerm> pragma, used thusly:
3000 key_function :: Int -> String -> (Bool, Double)
3002 #ifdef __GLASGOW_HASKELL__
3003 {-# INLINE key_function #-}
3007 (You don't need to do the C pre-processor carry-on unless you're going
3008 to stick the code through HBC—it doesn't like <Literal>INLINE</Literal> pragmas.)
3012 The major effect of an <Literal>INLINE</Literal> pragma is to declare a function's
3013 ``cost'' to be very low. The normal unfolding machinery will then be
3014 very keen to inline it.
3018 An <Literal>INLINE</Literal> pragma for a function can be put anywhere its type
3019 signature could be put.
3023 <Literal>INLINE</Literal> pragmas are a particularly good idea for the
3024 <Literal>then</Literal>/<Literal>return</Literal> (or <Literal>bind</Literal>/<Literal>unit</Literal>) functions in a monad.
3025 For example, in GHC's own <Literal>UniqueSupply</Literal> monad code, we have:
3028 #ifdef __GLASGOW_HASKELL__
3029 {-# INLINE thenUs #-}
3030 {-# INLINE returnUs #-}
3038 <Sect2 id="noinline-pragma">
3039 <Title>NOINLINE pragma
3043 <IndexTerm><Primary>NOINLINE pragma</Primary></IndexTerm>
3044 <IndexTerm><Primary>pragma, NOINLINE</Primary></IndexTerm>
3048 The <Literal>NOINLINE</Literal> pragma does exactly what you'd expect: it stops the
3049 named function from being inlined by the compiler. You shouldn't ever
3050 need to do this, unless you're very cautious about code size.
3055 <Sect2 id="specialize-pragma">
3056 <Title>SPECIALIZE pragma
3060 <IndexTerm><Primary>SPECIALIZE pragma</Primary></IndexTerm>
3061 <IndexTerm><Primary>pragma, SPECIALIZE</Primary></IndexTerm>
3062 <IndexTerm><Primary>overloading, death to</Primary></IndexTerm>
3066 (UK spelling also accepted.) For key overloaded functions, you can
3067 create extra versions (NB: more code space) specialised to particular
3068 types. Thus, if you have an overloaded function:
3074 hammeredLookup :: Ord key => [(key, value)] -> key -> value
3080 If it is heavily used on lists with <Literal>Widget</Literal> keys, you could
3081 specialise it as follows:
3084 {-# SPECIALIZE hammeredLookup :: [(Widget, value)] -> Widget -> value #-}
3090 To get very fancy, you can also specify a named function to use for
3091 the specialised value, by adding <Literal>= blah</Literal>, as in:
3094 {-# SPECIALIZE hammeredLookup :: ...as before... = blah #-}
3097 It's <Emphasis>Your Responsibility</Emphasis> to make sure that <Literal>blah</Literal> really
3098 behaves as a specialised version of <Literal>hammeredLookup</Literal>!!!
3102 NOTE: the <Literal>=blah</Literal> feature isn't implemented in GHC 4.xx.
3106 An example in which the <Literal>= blah</Literal> form will Win Big:
3109 toDouble :: Real a => a -> Double
3110 toDouble = fromRational . toRational
3112 {-# SPECIALIZE toDouble :: Int -> Double = i2d #-}
3113 i2d (I# i) = D# (int2Double# i) -- uses Glasgow prim-op directly
3116 The <Literal>i2d</Literal> function is virtually one machine instruction; the
3117 default conversion—via an intermediate <Literal>Rational</Literal>—is obscenely
3118 expensive by comparison.
3122 By using the US spelling, your <Literal>SPECIALIZE</Literal> pragma will work with
3123 HBC, too. Note that HBC doesn't support the <Literal>= blah</Literal> form.
3127 A <Literal>SPECIALIZE</Literal> pragma for a function can be put anywhere its type
3128 signature could be put.
3133 <Sect2 id="specialize-instance-pragma">
3134 <Title>SPECIALIZE instance pragma
3138 <IndexTerm><Primary>SPECIALIZE pragma</Primary></IndexTerm>
3139 <IndexTerm><Primary>overloading, death to</Primary></IndexTerm>
3140 Same idea, except for instance declarations. For example:
3143 instance (Eq a) => Eq (Foo a) where { ... usual stuff ... }
3145 {-# SPECIALIZE instance Eq (Foo [(Int, Bar)] #-}
3148 Compatible with HBC, by the way.
3153 <Sect2 id="line-pragma">
3158 <IndexTerm><Primary>LINE pragma</Primary></IndexTerm>
3159 <IndexTerm><Primary>pragma, LINE</Primary></IndexTerm>
3163 This pragma is similar to C's <Literal>#line</Literal> pragma, and is mainly for use in
3164 automatically generated Haskell code. It lets you specify the line
3165 number and filename of the original code; for example
3171 {-# LINE 42 "Foo.vhs" #-}
3177 if you'd generated the current file from something called <Literal>Foo.vhs</Literal>
3178 and this line corresponds to line 42 in the original. GHC will adjust
3179 its error messages to refer to the line/file named in the <Literal>LINE</Literal>
3186 <Title>RULES pragma</Title>
3189 The RULES pragma lets you specify rewrite rules. It is described in
3190 <XRef LinkEnd="rewrite-rules">.
3197 <Sect1 id="rewrite-rules">
3198 <Title>Rewrite rules
3200 <IndexTerm><Primary>RULES pagma</Primary></IndexTerm>
3201 <IndexTerm><Primary>pragma, RULES</Primary></IndexTerm>
3202 <IndexTerm><Primary>rewrite rules</Primary></IndexTerm></Title>
3205 The programmer can specify rewrite rules as part of the source program
3206 (in a pragma). GHC applies these rewrite rules wherever it can.
3214 "map/map" forall f g xs. map f (map g xs) = map (f.g) xs
3221 <Title>Syntax</Title>
3224 From a syntactic point of view:
3230 Each rule has a name, enclosed in double quotes. The name itself has
3231 no significance at all. It is only used when reporting how many times the rule fired.
3237 There may be zero or more rules in a <Literal>RULES</Literal> pragma.
3243 Layout applies in a <Literal>RULES</Literal> pragma. Currently no new indentation level
3244 is set, so you must lay out your rules starting in the same column as the
3245 enclosing definitions.
3251 Each variable mentioned in a rule must either be in scope (e.g. <Literal>map</Literal>),
3252 or bound by the <Literal>forall</Literal> (e.g. <Literal>f</Literal>, <Literal>g</Literal>, <Literal>xs</Literal>). The variables bound by
3253 the <Literal>forall</Literal> are called the <Emphasis>pattern</Emphasis> variables. They are separated
3254 by spaces, just like in a type <Literal>forall</Literal>.
3260 A pattern variable may optionally have a type signature.
3261 If the type of the pattern variable is polymorphic, it <Emphasis>must</Emphasis> have a type signature.
3262 For example, here is the <Literal>foldr/build</Literal> rule:
3265 "fold/build" forall k z (g::forall b. (a->b->b) -> b -> b) .
3266 foldr k z (build g) = g k z
3269 Since <Literal>g</Literal> has a polymorphic type, it must have a type signature.
3276 The left hand side of a rule must consist of a top-level variable applied
3277 to arbitrary expressions. For example, this is <Emphasis>not</Emphasis> OK:
3280 "wrong1" forall e1 e2. case True of { True -> e1; False -> e2 } = e1
3281 "wrong2" forall f. f True = True
3284 In <Literal>"wrong1"</Literal>, the LHS is not an application; in <Literal>"wrong1"</Literal>, the LHS has a pattern variable
3291 A rule does not need to be in the same module as (any of) the
3292 variables it mentions, though of course they need to be in scope.
3298 Rules are automatically exported from a module, just as instance declarations are.
3309 <Title>Semantics</Title>
3312 From a semantic point of view:
3318 Rules are only applied if you use the <Literal>-O</Literal> flag.
3325 Rules are regarded as left-to-right rewrite rules.
3326 When GHC finds an expression that is a substitution instance of the LHS
3327 of a rule, it replaces the expression by the (appropriately-substituted) RHS.
3328 By "a substitution instance" we mean that the LHS can be made equal to the
3329 expression by substituting for the pattern variables.
3336 The LHS and RHS of a rule are typechecked, and must have the
3344 GHC makes absolutely no attempt to verify that the LHS and RHS
3345 of a rule have the same meaning. That is undecideable in general, and
3346 infeasible in most interesting cases. The responsibility is entirely the programmer's!
3353 GHC makes no attempt to make sure that the rules are confluent or
3354 terminating. For example:
3357 "loop" forall x,y. f x y = f y x
3360 This rule will cause the compiler to go into an infinite loop.
3367 If more than one rule matches a call, GHC will choose one arbitrarily to apply.
3373 GHC currently uses a very simple, syntactic, matching algorithm
3374 for matching a rule LHS with an expression. It seeks a substitution
3375 which makes the LHS and expression syntactically equal modulo alpha
3376 conversion. The pattern (rule), but not the expression, is eta-expanded if
3377 necessary. (Eta-expanding the epression can lead to laziness bugs.)
3378 But not beta conversion (that's called higher-order matching).
3382 Matching is carried out on GHC's intermediate language, which includes
3383 type abstractions and applications. So a rule only matches if the
3384 types match too. See <XRef LinkEnd="rule-spec"> below.
3390 GHC keeps trying to apply the rules as it optimises the program.
3391 For example, consider:
3400 The expression <Literal>s (t xs)</Literal> does not match the rule <Literal>"map/map"</Literal>, but GHC
3401 will substitute for <Literal>s</Literal> and <Literal>t</Literal>, giving an expression which does match.
3402 If <Literal>s</Literal> or <Literal>t</Literal> was (a) used more than once, and (b) large or a redex, then it would
3403 not be substituted, and the rule would not fire.
3410 In the earlier phases of compilation, GHC inlines <Emphasis>nothing
3411 that appears on the LHS of a rule</Emphasis>, because once you have substituted
3412 for something you can't match against it (given the simple minded
3413 matching). So if you write the rule
3416 "map/map" forall f,g. map f . map g = map (f.g)
3419 this <Emphasis>won't</Emphasis> match the expression <Literal>map f (map g xs)</Literal>.
3420 It will only match something written with explicit use of ".".
3421 Well, not quite. It <Emphasis>will</Emphasis> match the expression
3427 where <Literal>wibble</Literal> is defined:
3430 wibble f g = map f . map g
3433 because <Literal>wibble</Literal> will be inlined (it's small).
3435 Later on in compilation, GHC starts inlining even things on the
3436 LHS of rules, but still leaves the rules enabled. This inlining
3437 policy is controlled by the per-simplification-pass flag <Literal>-finline-phase</Literal>n.
3444 All rules are implicitly exported from the module, and are therefore
3445 in force in any module that imports the module that defined the rule, directly
3446 or indirectly. (That is, if A imports B, which imports C, then C's rules are
3447 in force when compiling A.) The situation is very similar to that for instance
3459 <Title>List fusion</Title>
3462 The RULES mechanism is used to implement fusion (deforestation) of common list functions.
3463 If a "good consumer" consumes an intermediate list constructed by a "good producer", the
3464 intermediate list should be eliminated entirely.
3468 The following are good producers:
3480 Enumerations of <Literal>Int</Literal> and <Literal>Char</Literal> (e.g. <Literal>['a'..'z']</Literal>).
3486 Explicit lists (e.g. <Literal>[True, False]</Literal>)
3492 The cons constructor (e.g <Literal>3:4:[]</Literal>)
3498 <Literal>++</Literal>
3504 <Literal>map</Literal>
3510 <Literal>filter</Literal>
3516 <Literal>iterate</Literal>, <Literal>repeat</Literal>
3522 <Literal>zip</Literal>, <Literal>zipWith</Literal>
3531 The following are good consumers:
3543 <Literal>array</Literal> (on its second argument)
3549 <Literal>length</Literal>
3555 <Literal>++</Literal> (on its first argument)
3561 <Literal>map</Literal>
3567 <Literal>filter</Literal>
3573 <Literal>concat</Literal>
3579 <Literal>unzip</Literal>, <Literal>unzip2</Literal>, <Literal>unzip3</Literal>, <Literal>unzip4</Literal>
3585 <Literal>zip</Literal>, <Literal>zipWith</Literal> (but on one argument only; if both are good producers, <Literal>zip</Literal>
3586 will fuse with one but not the other)
3592 <Literal>partition</Literal>
3598 <Literal>head</Literal>
3604 <Literal>and</Literal>, <Literal>or</Literal>, <Literal>any</Literal>, <Literal>all</Literal>
3610 <Literal>sequence_</Literal>
3616 <Literal>msum</Literal>
3622 <Literal>sortBy</Literal>
3631 So, for example, the following should generate no intermediate lists:
3634 array (1,10) [(i,i*i) | i <- map (+ 1) [0..9]]
3640 This list could readily be extended; if there are Prelude functions that you use
3641 a lot which are not included, please tell us.
3645 If you want to write your own good consumers or producers, look at the
3646 Prelude definitions of the above functions to see how to do so.
3651 <Sect2 id="rule-spec">
3652 <Title>Specialisation
3656 Rewrite rules can be used to get the same effect as a feature
3657 present in earlier version of GHC:
3660 {-# SPECIALIZE fromIntegral :: Int8 -> Int16 = int8ToInt16 #-}
3663 This told GHC to use <Literal>int8ToInt16</Literal> instead of <Literal>fromIntegral</Literal> whenever
3664 the latter was called with type <Literal>Int8 -> Int16</Literal>. That is, rather than
3665 specialising the original definition of <Literal>fromIntegral</Literal> the programmer is
3666 promising that it is safe to use <Literal>int8ToInt16</Literal> instead.
3670 This feature is no longer in GHC. But rewrite rules let you do the
3675 "fromIntegral/Int8/Int16" fromIntegral = int8ToInt16
3679 This slightly odd-looking rule instructs GHC to replace <Literal>fromIntegral</Literal>
3680 by <Literal>int8ToInt16</Literal> <Emphasis>whenever the types match</Emphasis>. Speaking more operationally,
3681 GHC adds the type and dictionary applications to get the typed rule
3684 forall (d1::Integral Int8) (d2::Num Int16) .
3685 fromIntegral Int8 Int16 d1 d2 = int8ToInt16
3689 this rule does not need to be in the same file as fromIntegral,
3690 unlike the <Literal>SPECIALISE</Literal> pragmas which currently do (so that they
3691 have an original definition available to specialise).
3697 <Title>Controlling what's going on</Title>
3705 Use <Literal>-ddump-rules</Literal> to see what transformation rules GHC is using.
3711 Use <Literal>-ddump-simpl-stats</Literal> to see what rules are being fired.
3712 If you add <Literal>-dppr-debug</Literal> you get a more detailed listing.
3718 The defintion of (say) <Literal>build</Literal> in <Literal>PrelBase.lhs</Literal> looks llike this:
3721 build :: forall a. (forall b. (a -> b -> b) -> b -> b) -> [a]
3722 {-# INLINE build #-}
3726 Notice the <Literal>INLINE</Literal>! That prevents <Literal>(:)</Literal> from being inlined when compiling
3727 <Literal>PrelBase</Literal>, so that an importing module will ``see'' the <Literal>(:)</Literal>, and can
3728 match it on the LHS of a rule. <Literal>INLINE</Literal> prevents any inlining happening
3729 in the RHS of the <Literal>INLINE</Literal> thing. I regret the delicacy of this.
3736 In <Literal>ghc/lib/std/PrelBase.lhs</Literal> look at the rules for <Literal>map</Literal> to
3737 see how to write rules that will do fusion and yet give an efficient
3738 program even if fusion doesn't happen. More rules in <Literal>PrelList.lhs</Literal>.