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 <Option>-fglasgow-exts</Option>
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> (i.e. 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 <Function>seq</Function> 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 <Function>ST</Function> 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><Function>_ccall_</Function> and <Function>_casm_</Function>: 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 <Function>fooH</Function> unbox all of its arguments, call the C
336 function <Function>fooC</Function> and box the corresponding arguments.
340 One of the annoyances about <Function>_ccall_</Function>s is when the C types don't quite
341 match the Haskell compiler's ideas. For this, the <Function>_casm_</Function> 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 <Function>_casm_</Function> is like a <Function>printf</Function>
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 <Function>_ccall_</Function> goes
369 for <Function>_casm_</Function> as well.
373 The use of <Function>_casm_</Function> 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 <Function>_casm_</Function>, 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 <Function>_casm_</Function>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 <Function>_casm_</Function>, 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 <Function>_casm_</Function> 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 <Option>-funfold-casms-in-hi-file</Option> 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</Title>
403 <IndexTerm><Primary>Literal-literals</Primary></IndexTerm>
404 The literal-literal argument to <Function>_casm_</Function> can be made use of separately
405 from the <Function>_casm_</Function> construct itself. Indeed, we've already used it:
411 fooH :: Char -> Int -> Double -> Word -> IO Double
412 fooH c i d w = _ccall_ fooC (“stdin”::Addr) c i d w
418 The first argument that's passed to <Function>fooC</Function> is given as a literal-literal,
419 that is, a literal chunk of C code that will be inserted into the generated
420 <Filename>.hc</Filename> code at the right place.
424 A literal-literal is restricted to having a type that's an instance of
425 the <Literal>CCallable</Literal> class, see <XRef LinkEnd="ccall-gotchas">
426 for more information.
430 Notice that literal-literals are by their very nature unfriendly to
431 native code generators, so exercise judgement about whether or not to
432 make use of them in your code.
437 <Sect2 id="glasgow-foreign-headers">
438 <Title>Using function headers
442 <IndexTerm><Primary>C calls, function headers</Primary></IndexTerm>
446 When generating C (using the <Option>-fvia-C</Option> directive), one can assist the
447 C compiler in detecting type errors by using the <Command>-#include</Command> directive
448 to provide <Filename>.h</Filename> files containing function headers.
458 typedef unsigned long *StgForeignObj;
461 void initialiseEFS (StgInt size);
462 StgInt terminateEFS (void);
463 StgForeignObj emptyEFS(void);
464 StgForeignObj updateEFS (StgForeignObj a, StgInt i, StgInt x);
465 StgInt lookupEFS (StgForeignObj a, StgInt i);
471 You can find appropriate definitions for <Literal>StgInt</Literal>, <Literal>StgForeignObj</Literal>,
472 etc using <Command>gcc</Command> on your architecture by consulting
473 <Filename>ghc/includes/StgTypes.h</Filename>. The following table summarises the
474 relationship between Haskell types and C types.
481 <ColSpec Align="Left" Colsep="0">
482 <ColSpec Align="Left" Colsep="0">
485 <Entry><Emphasis>C type name</Emphasis> </Entry>
486 <Entry> <Emphasis>Haskell Type</Emphasis> </Entry>
491 <Literal>StgChar</Literal> </Entry>
492 <Entry> <Literal>Char#</Literal> </Entry>
496 <Literal>StgInt</Literal> </Entry>
497 <Entry> <Literal>Int#</Literal> </Entry>
501 <Literal>StgWord</Literal> </Entry>
502 <Entry> <Literal>Word#</Literal> </Entry>
506 <Literal>StgAddr</Literal> </Entry>
507 <Entry> <Literal>Addr#</Literal> </Entry>
511 <Literal>StgFloat</Literal> </Entry>
512 <Entry> <Literal>Float#</Literal> </Entry>
516 <Literal>StgDouble</Literal> </Entry>
517 <Entry> <Literal>Double#</Literal> </Entry>
521 <Literal>StgArray</Literal> </Entry>
522 <Entry> <Literal>Array#</Literal> </Entry>
526 <Literal>StgByteArray</Literal> </Entry>
527 <Entry> <Literal>ByteArray#</Literal> </Entry>
531 <Literal>StgArray</Literal> </Entry>
532 <Entry> <Literal>MutableArray#</Literal> </Entry>
536 <Literal>StgByteArray</Literal> </Entry>
537 <Entry> <Literal>MutableByteArray#</Literal> </Entry>
541 <Literal>StgStablePtr</Literal> </Entry>
542 <Entry> <Literal>StablePtr#</Literal> </Entry>
546 <Literal>StgForeignObj</Literal> </Entry>
547 <Entry> <Literal>ForeignObj#</Literal></Entry>
556 Note that this approach is only <Emphasis>essential</Emphasis> for returning
557 <Literal>float</Literal>s (or if <Literal>sizeof(int) != sizeof(int *)</Literal> on your
558 architecture) but is a Good Thing for anyone who cares about writing
559 solid code. You're crazy not to do it.
564 <Sect2 id="glasgow-stablePtrs">
565 <Title>Subverting automatic unboxing with “stable pointers”
569 <IndexTerm><Primary>stable pointers (Glasgow extension)</Primary></IndexTerm>
573 The arguments of a <Function>_ccall_</Function> automatically unboxed before the
574 call. There are two reasons why this is usually the Right Thing to
584 C is a strict language: it would be excessively tedious to pass
585 unevaluated arguments and require the C programmer to force their
586 evaluation before using them.
593 Boxed values are stored on the Haskell heap and may be moved
594 within the heap if a garbage collection occurs—that is, pointers
595 to boxed objects are not <Emphasis>stable</Emphasis>.
604 It is possible to subvert the unboxing process by creating a “stable
605 pointer” to a value and passing the stable pointer instead. For
606 example, to pass/return an integer lazily to C functions <Function>storeC</Function> and
607 <Function>fetchC</Function> might write:
613 storeH :: Int -> IO ()
614 storeH x = makeStablePtr x >>= \ stable_x ->
615 _ccall_ storeC stable_x
618 fetchH x = _ccall_ fetchC >>= \ stable_x ->
619 deRefStablePtr stable_x >>= \ x ->
620 freeStablePtr stable_x >>
627 The garbage collector will refrain from throwing a stable pointer away
628 until you explicitly call one of the following from C or Haskell.
634 void freeStablePointer( StgStablePtr stablePtrToToss )
635 freeStablePtr :: StablePtr a -> IO ()
641 As with the use of <Function>free</Function> in C programs, GREAT CARE SHOULD BE
642 EXERCISED to ensure these functions are called at the right time: too
643 early and you get dangling references (and, if you're lucky, an error
644 message from the runtime system); too late and you get space leaks.
648 And to force evaluation of the argument within <Function>fooC</Function>, one would
649 call one of the following C functions (according to type of argument).
655 void performIO ( StgStablePtr stableIndex /* StablePtr s (IO ()) */ );
656 StgInt enterInt ( StgStablePtr stableIndex /* StablePtr s Int */ );
657 StgFloat enterFloat ( StgStablePtr stableIndex /* StablePtr s Float */ );
663 <IndexTerm><Primary>performIO</Primary></IndexTerm>
664 <IndexTerm><Primary>enterInt</Primary></IndexTerm>
665 <IndexTerm><Primary>enterFloat</Primary></IndexTerm>
669 Nota Bene: <Function>_ccall_GC_</Function><IndexTerm><Primary>_ccall_GC_</Primary></IndexTerm> must be used if any of
670 these functions are used.
675 <Sect2 id="glasgow-foreignObjs">
676 <Title>Foreign objects: pointing outside the Haskell heap
680 <IndexTerm><Primary>foreign objects (Glasgow extension)</Primary></IndexTerm>
684 There are two types that GHC programs can use to reference
685 (heap-allocated) objects outside the Haskell world: <Literal>Addr</Literal> and
686 <Literal>ForeignObj</Literal>.
690 If you use <Literal>Addr</Literal>, it is up to you to the programmer to arrange
691 allocation and deallocation of the objects.
695 If you use <Literal>ForeignObj</Literal>, GHC's garbage collector will call upon the
696 user-supplied <Emphasis>finaliser</Emphasis> function to free the object when the
697 Haskell world no longer can access the object. (An object is
698 associated with a finaliser function when the abstract
699 Haskell type <Literal>ForeignObj</Literal> is created). The finaliser function is
700 expressed in C, and is passed as argument the object:
706 void foreignFinaliser ( StgForeignObj fo )
712 when the Haskell world can no longer access the object. Since
713 <Literal>ForeignObj</Literal>s only get released when a garbage collection occurs, we
714 provide ways of triggering a garbage collection from within C and from
721 void GarbageCollect()
728 More information on the programmers' interface to <Literal>ForeignObj</Literal> can be
729 found in the library documentation.
734 <Sect2 id="glasgow-avoiding-monads">
735 <Title>Avoiding monads
739 <IndexTerm><Primary>C calls to `pure C'</Primary></IndexTerm>
740 <IndexTerm><Primary>unsafePerformIO</Primary></IndexTerm>
744 The <Function>_ccall_</Function> construct is part of the <Literal>IO</Literal> monad because 9 out of 10
745 uses will be to call imperative functions with side effects such as
746 <Function>printf</Function>. Use of the monad ensures that these operations happen in a
747 predictable order in spite of laziness and compiler optimisations.
751 To avoid having to be in the monad to call a C function, it is
752 possible to use <Function>unsafePerformIO</Function>, which is available from the
753 <Literal>IOExts</Literal> module. There are three situations where one might like to
754 call a C function from outside the IO world:
763 Calling a function with no side-effects:
766 atan2d :: Double -> Double -> Double
767 atan2d y x = unsafePerformIO (_ccall_ atan2d y x)
769 sincosd :: Double -> (Double, Double)
770 sincosd x = unsafePerformIO $ do
771 da <- newDoubleArray (0, 1)
772 _casm_ “sincosd( %0, &((double *)%1[0]), &((double *)%1[1]) );” x da
773 s <- readDoubleArray da 0
774 c <- readDoubleArray da 1
784 Calling a set of functions which have side-effects but which can
785 be used in a purely functional manner.
787 For example, an imperative implementation of a purely functional
788 lookup-table might be accessed using the following functions.
793 update :: EFS x -> Int -> x -> EFS x
794 lookup :: EFS a -> Int -> a
796 empty = unsafePerformIO (_ccall_ emptyEFS)
798 update a i x = unsafePerformIO $
799 makeStablePtr x >>= \ stable_x ->
800 _ccall_ updateEFS a i stable_x
802 lookup a i = unsafePerformIO $
803 _ccall_ lookupEFS a i >>= \ stable_x ->
804 deRefStablePtr stable_x
808 You will almost always want to use <Literal>ForeignObj</Literal>s with this.
815 Calling a side-effecting function even though the results will
816 be unpredictable. For example the <Function>trace</Function> function is defined by:
820 trace :: String -> a -> a
823 ((_ccall_ PreTraceHook sTDERR{-msg-}):: IO ()) >>
824 fputs sTDERR string >>
825 ((_ccall_ PostTraceHook sTDERR{-msg-}):: IO ()) >>
828 sTDERR = (“stderr” :: Addr)
832 (This kind of use is not highly recommended—it is only really
833 useful in debugging code.)
843 <Sect2 id="ccall-gotchas">
844 <Title>C-calling “gotchas” checklist
848 <IndexTerm><Primary>C call dangers</Primary></IndexTerm>
849 <IndexTerm><Primary>CCallable</Primary></IndexTerm>
850 <IndexTerm><Primary>CReturnable</Primary></IndexTerm>
854 And some advice, too.
863 For modules that use <Function>_ccall_</Function>s, etc., compile with
864 <Option>-fvia-C</Option>.<IndexTerm><Primary>-fvia-C option</Primary></IndexTerm> You don't have to, but you should.
866 Also, use the <Option>-#include "prototypes.h"</Option> flag (hack) to inform the C
867 compiler of the fully-prototyped types of all the C functions you
868 call. (<XRef LinkEnd="glasgow-foreign-headers"> says more about this…)
870 This scheme is the <Emphasis>only</Emphasis> way that you will get <Emphasis>any</Emphasis>
871 typechecking of your <Function>_ccall_</Function>s. (It shouldn't be that way, but…).
872 GHC will pass the flag <Option>-Wimplicit</Option> to <Command>gcc</Command> so that you'll get warnings
873 if any <Function>_ccall_</Function>ed functions have no prototypes.
880 Try to avoid <Function>_ccall_</Function>s to C functions that take <Literal>float</Literal>
881 arguments or return <Literal>float</Literal> results. Reason: if you do, you will
882 become entangled in (ANSI?) C's rules for when arguments/results are
883 promoted to <Literal>doubles</Literal>. It's a nightmare and just not worth it.
884 Use <Literal>doubles</Literal> if possible.
886 If you do use <Literal>floats</Literal>, check and re-check that the right thing is
887 happening. Perhaps compile with <Option>-keep-hc-file-too</Option> and look at
888 the intermediate C (<Function>.hc</Function>).
895 The compiler uses two non-standard type-classes when
896 type-checking the arguments and results of <Function>_ccall_</Function>: the arguments
897 (respectively result) of <Function>_ccall_</Function> must be instances of the class
898 <Literal>CCallable</Literal> (respectively <Literal>CReturnable</Literal>). Both classes may be
899 imported from the module <Literal>CCall</Literal>, but this should only be
900 necessary if you want to define a new instance. (Neither class
901 defines any methods—their only function is to keep the
904 The type checker must be able to figure out just which of the
905 C-callable/returnable types is being used. If it can't, you have to
906 add type signatures. For example,
914 is not good enough, because the compiler can't work out what type <VarName>x</VarName>
915 is, nor what type the <Function>_ccall_</Function> returns. You have to write, say:
919 f :: Int -> IO Double
924 This table summarises the standard instances of these classes.
928 <ColSpec Align="Left" Colsep="0">
929 <ColSpec Align="Left" Colsep="0">
930 <ColSpec Align="Left" Colsep="0">
931 <ColSpec Align="Left" Colsep="0">
934 <Entry><Emphasis>Type</Emphasis> </Entry>
935 <Entry><Emphasis>CCallable</Emphasis></Entry>
936 <Entry><Emphasis>CReturnable</Emphasis> </Entry>
937 <Entry><Emphasis>Which is probably…</Emphasis> </Entry>
941 <Literal>Char</Literal> </Entry>
944 <Entry> <Literal>unsigned char</Literal> </Entry>
948 <Literal>Int</Literal> </Entry>
951 <Entry> <Literal>long int</Literal> </Entry>
955 <Literal>Word</Literal> </Entry>
958 <Entry> <Literal>unsigned long int</Literal> </Entry>
962 <Literal>Addr</Literal> </Entry>
965 <Entry> <Literal>void *</Literal> </Entry>
969 <Literal>Float</Literal> </Entry>
972 <Entry> <Literal>float</Literal> </Entry>
976 <Literal>Double</Literal> </Entry>
979 <Entry> <Literal>double</Literal> </Entry>
983 <Literal>()</Literal> </Entry>
986 <Entry> <Literal>void</Literal> </Entry>
990 <Literal>[Char]</Literal> </Entry>
993 <Entry> <Literal>char *</Literal> (null-terminated) </Entry>
997 <Literal>Array</Literal> </Entry>
1000 <Entry> <Literal>unsigned long *</Literal> </Entry>
1004 <Literal>ByteArray</Literal> </Entry>
1005 <Entry> Yes </Entry>
1007 <Entry> <Literal>unsigned long *</Literal> </Entry>
1011 <Literal>MutableArray</Literal> </Entry>
1012 <Entry> Yes </Entry>
1014 <Entry> <Literal>unsigned long *</Literal> </Entry>
1018 <Literal>MutableByteArray</Literal> </Entry>
1019 <Entry> Yes </Entry>
1021 <Entry> <Literal>unsigned long *</Literal> </Entry>
1025 <Literal>State</Literal> </Entry>
1026 <Entry> Yes </Entry>
1027 <Entry> Yes </Entry>
1028 <Entry> nothing!</Entry>
1032 <Literal>StablePtr</Literal> </Entry>
1033 <Entry> Yes </Entry>
1034 <Entry> Yes </Entry>
1035 <Entry> <Literal>unsigned long *</Literal> </Entry>
1039 <Literal>ForeignObjs</Literal> </Entry>
1040 <Entry> Yes </Entry>
1041 <Entry> Yes </Entry>
1042 <Entry> see later </Entry>
1050 Actually, the <Literal>Word</Literal> type is defined as being the same size as a
1051 pointer on the target architecture, which is <Emphasis>probably</Emphasis>
1052 <Literal>unsigned long int</Literal>.
1054 The brave and careful programmer can add their own instances of these
1055 classes for the following types:
1062 A <Emphasis>boxed-primitive</Emphasis> type may be made an instance of both
1063 <Literal>CCallable</Literal> and <Literal>CReturnable</Literal>.
1065 A boxed primitive type is any data type with a
1066 single unary constructor with a single primitive argument. For
1067 example, the following are all boxed primitive types:
1073 data XDisplay = XDisplay Addr#
1074 data EFS a = EFS# ForeignObj#
1080 instance CCallable (EFS a)
1081 instance CReturnable (EFS a)
1090 Any datatype with a single nullary constructor may be made an
1091 instance of <Literal>CReturnable</Literal>. For example:
1095 data MyVoid = MyVoid
1096 instance CReturnable MyVoid
1105 As at version 2.09, <Literal>String</Literal> (i.e., <Literal>[Char]</Literal>) is still
1106 not a <Literal>CReturnable</Literal> type.
1108 Also, the now-builtin type <Literal>PackedString</Literal> is neither
1109 <Literal>CCallable</Literal> nor <Literal>CReturnable</Literal>. (But there are functions in
1110 the PackedString interface to let you get at the necessary bits…)
1122 The code-generator will complain if you attempt to use <Literal>%r</Literal> in
1123 a <Literal>_casm_</Literal> whose result type is <Literal>IO ()</Literal>; or if you don't use <Literal>%r</Literal>
1124 <Emphasis>precisely</Emphasis> once for any other result type. These messages are
1125 supposed to be helpful and catch bugs—please tell us if they wreck
1133 If you call out to C code which may trigger the Haskell garbage
1134 collector or create new threads (examples of this later…), then you
1135 must use the <Function>_ccall_GC_</Function><IndexTerm><Primary>_ccall_GC_ primitive</Primary></IndexTerm> or
1136 <Function>_casm_GC_</Function><IndexTerm><Primary>_casm_GC_ primitive</Primary></IndexTerm> variant of C-calls. (This
1137 does not work with the native code generator—use <Option>-fvia-C</Option>.) This
1138 stuff is hairy with a capital H!
1150 <Sect1 id="multi-param-type-classes">
1151 <Title>Multi-parameter type classes
1155 This section documents GHC's implementation of multi-paramter type
1156 classes. There's lots of background in the paper <ULink
1157 URL="http://www.dcs.gla.ac.uk/~simonpj/multi.ps.gz"
1158 >Type classes: exploring the design space</ULink
1160 Jones, Mark Jones, Erik Meijer).
1164 I'd like to thank people who reported shorcomings in the GHC 3.02
1165 implementation. Our default decisions were all conservative ones, and
1166 the experience of these heroic pioneers has given useful concrete
1167 examples to support several generalisations. (These appear below as
1168 design choices not implemented in 3.02.)
1172 I've discussed these notes with Mark Jones, and I believe that Hugs
1173 will migrate towards the same design choices as I outline here.
1174 Thanks to him, and to many others who have offered very useful
1179 <Title>Types</Title>
1182 There are the following restrictions on the form of a qualified
1189 forall tv1..tvn (c1, ...,cn) => type
1195 (Here, I write the "foralls" explicitly, although the Haskell source
1196 language omits them; in Haskell 1.4, all the free type variables of an
1197 explicit source-language type signature are universally quantified,
1198 except for the class type variables in a class declaration. However,
1199 in GHC, you can give the foralls if you want. See <XRef LinkEnd="universal-quantification">).
1208 <Emphasis>Each universally quantified type variable
1209 <Literal>tvi</Literal> must be mentioned (i.e. appear free) in <Literal>type</Literal></Emphasis>.
1211 The reason for this is that a value with a type that does not obey
1212 this restriction could not be used without introducing
1213 ambiguity. Here, for example, is an illegal type:
1217 forall a. Eq a => Int
1221 When a value with this type was used, the constraint <Literal>Eq tv</Literal>
1222 would be introduced where <Literal>tv</Literal> is a fresh type variable, and
1223 (in the dictionary-translation implementation) the value would be
1224 applied to a dictionary for <Literal>Eq tv</Literal>. The difficulty is that we
1225 can never know which instance of <Literal>Eq</Literal> to use because we never
1226 get any more information about <Literal>tv</Literal>.
1233 <Emphasis>Every constraint <Literal>ci</Literal> must mention at least one of the
1234 universally quantified type variables <Literal>tvi</Literal></Emphasis>.
1236 For example, this type is OK because <Literal>C a b</Literal> mentions the
1237 universally quantified type variable <Literal>b</Literal>:
1241 forall a. C a b => burble
1245 The next type is illegal because the constraint <Literal>Eq b</Literal> does not
1246 mention <Literal>a</Literal>:
1250 forall a. Eq b => burble
1254 The reason for this restriction is milder than the other one. The
1255 excluded types are never useful or necessary (because the offending
1256 context doesn't need to be witnessed at this point; it can be floated
1257 out). Furthermore, floating them out increases sharing. Lastly,
1258 excluding them is a conservative choice; it leaves a patch of
1259 territory free in case we need it later.
1269 These restrictions apply to all types, whether declared in a type signature
1274 Unlike Haskell 1.4, constraints in types do <Emphasis>not</Emphasis> have to be of
1275 the form <Emphasis>(class type-variables)</Emphasis>. Thus, these type signatures
1282 f :: Eq (m a) => [m a] -> [m a]
1283 g :: Eq [a] => ...
1289 This choice recovers principal types, a property that Haskell 1.4 does not have.
1295 <Title>Class declarations</Title>
1303 <Emphasis>Multi-parameter type classes are permitted</Emphasis>. For example:
1307 class Collection c a where
1308 union :: c a -> c a -> c a
1319 <Emphasis>The class hierarchy must be acyclic</Emphasis>. However, the definition
1320 of "acyclic" involves only the superclass relationships. For example,
1326 op :: D b => a -> b -> b
1329 class C a => D a where { ... }
1333 Here, <Literal>C</Literal> is a superclass of <Literal>D</Literal>, but it's OK for a
1334 class operation <Literal>op</Literal> of <Literal>C</Literal> to mention <Literal>D</Literal>. (It
1335 would not be OK for <Literal>D</Literal> to be a superclass of <Literal>C</Literal>.)
1342 <Emphasis>There are no restrictions on the context in a class declaration
1343 (which introduces superclasses), except that the class hierarchy must
1344 be acyclic</Emphasis>. So these class declarations are OK:
1348 class Functor (m k) => FiniteMap m k where
1351 class (Monad m, Monad (t m)) => Transform t m where
1352 lift :: m a -> (t m) a
1361 <Emphasis>In the signature of a class operation, every constraint
1362 must mention at least one type variable that is not a class type
1363 variable</Emphasis>.
1369 class Collection c a where
1370 mapC :: Collection c b => (a->b) -> c a -> c b
1374 is OK because the constraint <Literal>(Collection a b)</Literal> mentions
1375 <Literal>b</Literal>, even though it also mentions the class variable
1376 <Literal>a</Literal>. On the other hand:
1381 op :: Eq a => (a,b) -> (a,b)
1385 is not OK because the constraint <Literal>(Eq a)</Literal> mentions on the class
1386 type variable <Literal>a</Literal>, but not <Literal>b</Literal>. However, any such
1387 example is easily fixed by moving the offending context up to the
1392 class Eq a => C a where
1393 op ::(a,b) -> (a,b)
1397 A yet more relaxed rule would allow the context of a class-op signature
1398 to mention only class type variables. However, that conflicts with
1399 Rule 1(b) for types above.
1406 <Emphasis>The type of each class operation must mention <Emphasis>all</Emphasis> of
1407 the class type variables</Emphasis>. For example:
1411 class Coll s a where
1413 insert :: s -> a -> s
1417 is not OK, because the type of <Literal>empty</Literal> doesn't mention
1418 <Literal>a</Literal>. This rule is a consequence of Rule 1(a), above, for
1419 types, and has the same motivation.
1421 Sometimes, offending class declarations exhibit misunderstandings. For
1422 example, <Literal>Coll</Literal> might be rewritten
1426 class Coll s a where
1428 insert :: s a -> a -> s a
1432 which makes the connection between the type of a collection of
1433 <Literal>a</Literal>'s (namely <Literal>(s a)</Literal>) and the element type <Literal>a</Literal>.
1434 Occasionally this really doesn't work, in which case you can split the
1442 class CollE s => Coll s a where
1443 insert :: s -> a -> s
1457 <Title>Instance declarations</Title>
1465 <Emphasis>Instance declarations may not overlap</Emphasis>. The two instance
1470 instance context1 => C type1 where ...
1471 instance context2 => C type2 where ...
1475 "overlap" if <Literal>type1</Literal> and <Literal>type2</Literal> unify
1477 However, if you give the command line option
1478 <Option>-fallow-overlapping-instances</Option><IndexTerm><Primary>-fallow-overlapping-instances
1479 option</Primary></IndexTerm> then two overlapping instance declarations are permitted
1487 EITHER <Literal>type1</Literal> and <Literal>type2</Literal> do not unify
1493 OR <Literal>type2</Literal> is a substitution instance of <Literal>type1</Literal>
1494 (but not identical to <Literal>type1</Literal>)
1507 Notice that these rules
1514 make it clear which instance decl to use
1515 (pick the most specific one that matches)
1522 do not mention the contexts <Literal>context1</Literal>, <Literal>context2</Literal>
1523 Reason: you can pick which instance decl
1524 "matches" based on the type.
1531 Regrettably, GHC doesn't guarantee to detect overlapping instance
1532 declarations if they appear in different modules. GHC can "see" the
1533 instance declarations in the transitive closure of all the modules
1534 imported by the one being compiled, so it can "see" all instance decls
1535 when it is compiling <Literal>Main</Literal>. However, it currently chooses not
1536 to look at ones that can't possibly be of use in the module currently
1537 being compiled, in the interests of efficiency. (Perhaps we should
1538 change that decision, at least for <Literal>Main</Literal>.)
1545 <Emphasis>There are no restrictions on the type in an instance
1546 <Emphasis>head</Emphasis>, except that at least one must not be a type variable</Emphasis>.
1547 The instance "head" is the bit after the "=>" in an instance decl. For
1548 example, these are OK:
1552 instance C Int a where ...
1554 instance D (Int, Int) where ...
1556 instance E [[a]] where ...
1560 Note that instance heads <Emphasis>may</Emphasis> contain repeated type variables.
1561 For example, this is OK:
1565 instance Stateful (ST s) (MutVar s) where ...
1569 The "at least one not a type variable" restriction is to ensure that
1570 context reduction terminates: each reduction step removes one type
1571 constructor. For example, the following would make the type checker
1572 loop if it wasn't excluded:
1576 instance C a => C a where ...
1580 There are two situations in which the rule is a bit of a pain. First,
1581 if one allows overlapping instance declarations then it's quite
1582 convenient to have a "default instance" declaration that applies if
1583 something more specific does not:
1592 Second, sometimes you might want to use the following to get the
1593 effect of a "class synonym":
1597 class (C1 a, C2 a, C3 a) => C a where { }
1599 instance (C1 a, C2 a, C3 a) => C a where { }
1603 This allows you to write shorter signatures:
1615 f :: (C1 a, C2 a, C3 a) => ...
1619 I'm on the lookout for a simple rule that preserves decidability while
1620 allowing these idioms. The experimental flag
1621 <Option>-fallow-undecidable-instances</Option><IndexTerm><Primary>-fallow-undecidable-instances
1622 option</Primary></IndexTerm> lifts this restriction, allowing all the types in an
1623 instance head to be type variables.
1630 <Emphasis>Unlike Haskell 1.4, instance heads may use type
1631 synonyms</Emphasis>. As always, using a type synonym is just shorthand for
1632 writing the RHS of the type synonym definition. For example:
1636 type Point = (Int,Int)
1637 instance C Point where ...
1638 instance C [Point] where ...
1642 is legal. However, if you added
1646 instance C (Int,Int) where ...
1650 as well, then the compiler will complain about the overlapping
1651 (actually, identical) instance declarations. As always, type synonyms
1652 must be fully applied. You cannot, for example, write:
1657 instance Monad P where ...
1661 This design decision is independent of all the others, and easily
1662 reversed, but it makes sense to me.
1669 <Emphasis>The types in an instance-declaration <Emphasis>context</Emphasis> must all
1670 be type variables</Emphasis>. Thus
1674 instance C a b => Eq (a,b) where ...
1682 instance C Int b => Foo b where ...
1686 is not OK. Again, the intent here is to make sure that context
1687 reduction terminates.
1689 Voluminous correspondence on the Haskell mailing list has convinced me
1690 that it's worth experimenting with a more liberal rule. If you use
1691 the flag <Option>-fallow-undecidable-instances</Option> can use arbitrary
1692 types in an instance context. Termination is ensured by having a
1693 fixed-depth recursion stack. If you exceed the stack depth you get a
1694 sort of backtrace, and the opportunity to increase the stack depth
1695 with <Option>-fcontext-stack</Option><Emphasis>N</Emphasis>.
1708 <Sect1 id="universal-quantification">
1709 <Title>Explicit universal quantification
1713 GHC now allows you to write explicitly quantified types. GHC's
1714 syntax for this now agrees with Hugs's, namely:
1720 forall a b. (Ord a, Eq b) => a -> b -> a
1726 The context is, of course, optional. You can't use <Literal>forall</Literal> as
1727 a type variable any more!
1731 Haskell type signatures are implicitly quantified. The <Literal>forall</Literal>
1732 allows us to say exactly what this means. For example:
1750 g :: forall b. (b -> b)
1756 The two are treated identically.
1760 <Title>Universally-quantified data type fields
1764 In a <Literal>data</Literal> or <Literal>newtype</Literal> declaration one can quantify
1765 the types of the constructor arguments. Here are several examples:
1771 data T a = T1 (forall b. b -> b -> b) a
1773 data MonadT m = MkMonad { return :: forall a. a -> m a,
1774 bind :: forall a b. m a -> (a -> m b) -> m b
1777 newtype Swizzle = MkSwizzle (Ord a => [a] -> [a])
1783 The constructors now have so-called <Emphasis>rank 2</Emphasis> polymorphic
1784 types, in which there is a for-all in the argument types.:
1790 T1 :: forall a. (forall b. b -> b -> b) -> a -> T a
1791 MkMonad :: forall m. (forall a. a -> m a)
1792 -> (forall a b. m a -> (a -> m b) -> m b)
1794 MkSwizzle :: (Ord a => [a] -> [a]) -> Swizzle
1800 Notice that you don't need to use a <Literal>forall</Literal> if there's an
1801 explicit context. For example in the first argument of the
1802 constructor <Function>MkSwizzle</Function>, an implicit "<Literal>forall a.</Literal>" is
1803 prefixed to the argument type. The implicit <Literal>forall</Literal>
1804 quantifies all type variables that are not already in scope, and are
1805 mentioned in the type quantified over.
1809 As for type signatures, implicit quantification happens for non-overloaded
1810 types too. So if you write this:
1813 data T a = MkT (Either a b) (b -> b)
1816 it's just as if you had written this:
1819 data T a = MkT (forall b. Either a b) (forall b. b -> b)
1822 That is, since the type variable <Literal>b</Literal> isn't in scope, it's
1823 implicitly universally quantified. (Arguably, it would be better
1824 to <Emphasis>require</Emphasis> explicit quantification on constructor arguments
1825 where that is what is wanted. Feedback welcomed.)
1831 <Title>Construction </Title>
1834 You construct values of types <Literal>T1, MonadT, Swizzle</Literal> by applying
1835 the constructor to suitable values, just as usual. For example,
1841 (T1 (\xy->x) 3) :: T Int
1843 (MkSwizzle sort) :: Swizzle
1844 (MkSwizzle reverse) :: Swizzle
1849 Nothing -> Nothing
1851 MkMonad r b) :: MonadT Maybe
1857 The type of the argument can, as usual, be more general than the type
1858 required, as <Literal>(MkSwizzle reverse)</Literal> shows. (<Function>reverse</Function>
1859 does not need the <Literal>Ord</Literal> constraint.)
1865 <Title>Pattern matching</Title>
1868 When you use pattern matching, the bound variables may now have
1869 polymorphic types. For example:
1875 f :: T a -> a -> (a, Char)
1876 f (T1 f k) x = (f k x, f 'c' 'd')
1878 g :: (Ord a, Ord b) => Swizzle -> [a] -> (a -> b) -> [b]
1879 g (MkSwizzle s) xs f = s (map f (s xs))
1881 h :: MonadT m -> [m a] -> m [a]
1882 h m [] = return m []
1883 h m (x:xs) = bind m x $ \y ->
1884 bind m (h m xs) $ \ys ->
1891 In the function <Function>h</Function> we use the record selectors <Literal>return</Literal>
1892 and <Literal>bind</Literal> to extract the polymorphic bind and return functions
1893 from the <Literal>MonadT</Literal> data structure, rather than using pattern
1898 You cannot pattern-match against an argument that is polymorphic.
1902 newtype TIM s a = TIM (ST s (Maybe a))
1904 runTIM :: (forall s. TIM s a) -> Maybe a
1905 runTIM (TIM m) = runST m
1911 Here the pattern-match fails, because you can't pattern-match against
1912 an argument of type <Literal>(forall s. TIM s a)</Literal>. Instead you
1913 must bind the variable and pattern match in the right hand side:
1916 runTIM :: (forall s. TIM s a) -> Maybe a
1917 runTIM tm = case tm of { TIM m -> runST m }
1920 The <Literal>tm</Literal> on the right hand side is (invisibly) instantiated, like
1921 any polymorphic value at its occurrence site, and now you can pattern-match
1928 <Title>The partial-application restriction</Title>
1931 There is really only one way in which data structures with polymorphic
1932 components might surprise you: you must not partially apply them.
1933 For example, this is illegal:
1939 map MkSwizzle [sort, reverse]
1945 The restriction is this: <Emphasis>every subexpression of the program must
1946 have a type that has no for-alls, except that in a function
1947 application (f e1…en) the partial applications are not subject to
1948 this rule</Emphasis>. The restriction makes type inference feasible.
1952 In the illegal example, the sub-expression <Literal>MkSwizzle</Literal> has the
1953 polymorphic type <Literal>(Ord b => [b] -> [b]) -> Swizzle</Literal> and is not
1954 a sub-expression of an enclosing application. On the other hand, this
1961 map (T1 (\a b -> a)) [1,2,3]
1967 even though it involves a partial application of <Function>T1</Function>, because
1968 the sub-expression <Literal>T1 (\a b -> a)</Literal> has type <Literal>Int -> T
1975 <Title>Type signatures
1979 Once you have data constructors with universally-quantified fields, or
1980 constants such as <Constant>runST</Constant> that have rank-2 types, it isn't long
1981 before you discover that you need more! Consider:
1987 mkTs f x y = [T1 f x, T1 f y]
1993 <Function>mkTs</Function> is a fuction that constructs some values of type
1994 <Literal>T</Literal>, using some pieces passed to it. The trouble is that since
1995 <Literal>f</Literal> is a function argument, Haskell assumes that it is
1996 monomorphic, so we'll get a type error when applying <Function>T1</Function> to
1997 it. This is a rather silly example, but the problem really bites in
1998 practice. Lots of people trip over the fact that you can't make
1999 "wrappers functions" for <Constant>runST</Constant> for exactly the same reason.
2000 In short, it is impossible to build abstractions around functions with
2005 The solution is fairly clear. We provide the ability to give a rank-2
2006 type signature for <Emphasis>ordinary</Emphasis> functions (not only data
2007 constructors), thus:
2013 mkTs :: (forall b. b -> b -> b) -> a -> [T a]
2014 mkTs f x y = [T1 f x, T1 f y]
2020 This type signature tells the compiler to attribute <Literal>f</Literal> with
2021 the polymorphic type <Literal>(forall b. b -> b -> b)</Literal> when type
2022 checking the body of <Function>mkTs</Function>, so now the application of
2023 <Function>T1</Function> is fine.
2027 There are two restrictions:
2036 You can only define a rank 2 type, specified by the following
2041 rank2type ::= [forall tyvars .] [context =>] funty
2042 funty ::= ([forall tyvars .] [context =>] ty) -> funty
2044 ty ::= ...current Haskell monotype syntax...
2048 Informally, the universal quantification must all be right at the beginning,
2049 or at the top level of a function argument.
2056 There is a restriction on the definition of a function whose
2057 type signature is a rank-2 type: the polymorphic arguments must be
2058 matched on the left hand side of the "<Literal>=</Literal>" sign. You can't
2059 define <Function>mkTs</Function> like this:
2063 mkTs :: (forall b. b -> b -> b) -> a -> [T a]
2064 mkTs = \ f x y -> [T1 f x, T1 f y]
2069 The same partial-application rule applies to ordinary functions with
2070 rank-2 types as applied to data constructors.
2083 <Title>Type synonyms and hoisting
2087 GHC also allows you to write a <Literal>forall</Literal> in a type synonym, thus:
2089 type Discard a = forall b. a -> b -> a
2094 However, it is often convenient to use these sort of synonyms at the right hand
2095 end of an arrow, thus:
2097 type Discard a = forall b. a -> b -> a
2099 g :: Int -> Discard Int
2102 Simply expanding the type synonym would give
2104 g :: Int -> (forall b. Int -> b -> Int)
2106 but GHC "hoists" the <Literal>forall</Literal> to give the isomorphic type
2108 g :: forall b. Int -> Int -> b -> Int
2110 In general, the rule is this: <Emphasis>to determine the type specified by any explicit
2111 user-written type (e.g. in a type signature), GHC expands type synonyms and then repeatedly
2112 performs the transformation:</Emphasis>
2114 <Emphasis>type1</Emphasis> -> forall a. <Emphasis>type2</Emphasis>
2116 forall a. <Emphasis>type1</Emphasis> -> <Emphasis>type2</Emphasis>
2118 (In fact, GHC tries to retain as much synonym information as possible for use in
2119 error messages, but that is a usability issue.) This rule applies, of course, whether
2120 or not the <Literal>forall</Literal> comes from a synonym. For example, here is another
2121 valid way to write <Literal>g</Literal>'s type signature:
2123 g :: Int -> Int -> forall b. b -> Int
2130 <Sect1 id="existential-quantification">
2131 <Title>Existentially quantified data constructors
2135 The idea of using existential quantification in data type declarations
2136 was suggested by Laufer (I believe, thought doubtless someone will
2137 correct me), and implemented in Hope+. It's been in Lennart
2138 Augustsson's <Command>hbc</Command> Haskell compiler for several years, and
2139 proved very useful. Here's the idea. Consider the declaration:
2145 data Foo = forall a. MkFoo a (a -> Bool)
2152 The data type <Literal>Foo</Literal> has two constructors with types:
2158 MkFoo :: forall a. a -> (a -> Bool) -> Foo
2165 Notice that the type variable <Literal>a</Literal> in the type of <Function>MkFoo</Function>
2166 does not appear in the data type itself, which is plain <Literal>Foo</Literal>.
2167 For example, the following expression is fine:
2173 [MkFoo 3 even, MkFoo 'c' isUpper] :: [Foo]
2179 Here, <Literal>(MkFoo 3 even)</Literal> packages an integer with a function
2180 <Function>even</Function> that maps an integer to <Literal>Bool</Literal>; and <Function>MkFoo 'c'
2181 isUpper</Function> packages a character with a compatible function. These
2182 two things are each of type <Literal>Foo</Literal> and can be put in a list.
2186 What can we do with a value of type <Literal>Foo</Literal>?. In particular,
2187 what happens when we pattern-match on <Function>MkFoo</Function>?
2193 f (MkFoo val fn) = ???
2199 Since all we know about <Literal>val</Literal> and <Function>fn</Function> is that they
2200 are compatible, the only (useful) thing we can do with them is to
2201 apply <Function>fn</Function> to <Literal>val</Literal> to get a boolean. For example:
2207 f :: Foo -> Bool
2208 f (MkFoo val fn) = fn val
2214 What this allows us to do is to package heterogenous values
2215 together with a bunch of functions that manipulate them, and then treat
2216 that collection of packages in a uniform manner. You can express
2217 quite a bit of object-oriented-like programming this way.
2220 <Sect2 id="existential">
2221 <Title>Why existential?
2225 What has this to do with <Emphasis>existential</Emphasis> quantification?
2226 Simply that <Function>MkFoo</Function> has the (nearly) isomorphic type
2232 MkFoo :: (exists a . (a, a -> Bool)) -> Foo
2238 But Haskell programmers can safely think of the ordinary
2239 <Emphasis>universally</Emphasis> quantified type given above, thereby avoiding
2240 adding a new existential quantification construct.
2246 <Title>Type classes</Title>
2249 An easy extension (implemented in <Command>hbc</Command>) is to allow
2250 arbitrary contexts before the constructor. For example:
2256 data Baz = forall a. Eq a => Baz1 a a
2257 | forall b. Show b => Baz2 b (b -> b)
2263 The two constructors have the types you'd expect:
2269 Baz1 :: forall a. Eq a => a -> a -> Baz
2270 Baz2 :: forall b. Show b => b -> (b -> b) -> Baz
2276 But when pattern matching on <Function>Baz1</Function> the matched values can be compared
2277 for equality, and when pattern matching on <Function>Baz2</Function> the first matched
2278 value can be converted to a string (as well as applying the function to it).
2279 So this program is legal:
2285 f :: Baz -> String
2286 f (Baz1 p q) | p == q = "Yes"
2288 f (Baz1 v fn) = show (fn v)
2294 Operationally, in a dictionary-passing implementation, the
2295 constructors <Function>Baz1</Function> and <Function>Baz2</Function> must store the
2296 dictionaries for <Literal>Eq</Literal> and <Literal>Show</Literal> respectively, and
2297 extract it on pattern matching.
2301 Notice the way that the syntax fits smoothly with that used for
2302 universal quantification earlier.
2308 <Title>Restrictions</Title>
2311 There are several restrictions on the ways in which existentially-quantified
2312 constructors can be use.
2321 When pattern matching, each pattern match introduces a new,
2322 distinct, type for each existential type variable. These types cannot
2323 be unified with any other type, nor can they escape from the scope of
2324 the pattern match. For example, these fragments are incorrect:
2332 Here, the type bound by <Function>MkFoo</Function> "escapes", because <Literal>a</Literal>
2333 is the result of <Function>f1</Function>. One way to see why this is wrong is to
2334 ask what type <Function>f1</Function> has:
2338 f1 :: Foo -> a -- Weird!
2342 What is this "<Literal>a</Literal>" in the result type? Clearly we don't mean
2347 f1 :: forall a. Foo -> a -- Wrong!
2351 The original program is just plain wrong. Here's another sort of error
2355 f2 (Baz1 a b) (Baz1 p q) = a==q
2359 It's ok to say <Literal>a==b</Literal> or <Literal>p==q</Literal>, but
2360 <Literal>a==q</Literal> is wrong because it equates the two distinct types arising
2361 from the two <Function>Baz1</Function> constructors.
2369 You can't pattern-match on an existentially quantified
2370 constructor in a <Literal>let</Literal> or <Literal>where</Literal> group of
2371 bindings. So this is illegal:
2375 f3 x = a==b where { Baz1 a b = x }
2379 You can only pattern-match
2380 on an existentially-quantified constructor in a <Literal>case</Literal> expression or
2381 in the patterns of a function definition.
2383 The reason for this restriction is really an implementation one.
2384 Type-checking binding groups is already a nightmare without
2385 existentials complicating the picture. Also an existential pattern
2386 binding at the top level of a module doesn't make sense, because it's
2387 not clear how to prevent the existentially-quantified type "escaping".
2388 So for now, there's a simple-to-state restriction. We'll see how
2396 You can't use existential quantification for <Literal>newtype</Literal>
2397 declarations. So this is illegal:
2401 newtype T = forall a. Ord a => MkT a
2405 Reason: a value of type <Literal>T</Literal> must be represented as a pair
2406 of a dictionary for <Literal>Ord t</Literal> and a value of type <Literal>t</Literal>.
2407 That contradicts the idea that <Literal>newtype</Literal> should have no
2408 concrete representation. You can get just the same efficiency and effect
2409 by using <Literal>data</Literal> instead of <Literal>newtype</Literal>. If there is no
2410 overloading involved, then there is more of a case for allowing
2411 an existentially-quantified <Literal>newtype</Literal>, because the <Literal>data</Literal>
2412 because the <Literal>data</Literal> version does carry an implementation cost,
2413 but single-field existentially quantified constructors aren't much
2414 use. So the simple restriction (no existential stuff on <Literal>newtype</Literal>)
2415 stands, unless there are convincing reasons to change it.
2423 You can't use <Literal>deriving</Literal> to define instances of a
2424 data type with existentially quantified data constructors.
2426 Reason: in most cases it would not make sense. For example:#
2429 data T = forall a. MkT [a] deriving( Eq )
2432 To derive <Literal>Eq</Literal> in the standard way we would need to have equality
2433 between the single component of two <Function>MkT</Function> constructors:
2437 (MkT a) == (MkT b) = ???
2440 But <VarName>a</VarName> and <VarName>b</VarName> have distinct types, and so can't be compared.
2441 It's just about possible to imagine examples in which the derived instance
2442 would make sense, but it seems altogether simpler simply to prohibit such
2443 declarations. Define your own instances!
2455 <Sect1 id="sec-assertions">
2457 <IndexTerm><Primary>Assertions</Primary></IndexTerm>
2461 If you want to make use of assertions in your standard Haskell code, you
2462 could define a function like the following:
2468 assert :: Bool -> a -> a
2469 assert False x = error "assertion failed!"
2476 which works, but gives you back a less than useful error message --
2477 an assertion failed, but which and where?
2481 One way out is to define an extended <Function>assert</Function> function which also
2482 takes a descriptive string to include in the error message and
2483 perhaps combine this with the use of a pre-processor which inserts
2484 the source location where <Function>assert</Function> was used.
2488 Ghc offers a helping hand here, doing all of this for you. For every
2489 use of <Function>assert</Function> in the user's source:
2495 kelvinToC :: Double -> Double
2496 kelvinToC k = assert (k &gt;= 0.0) (k+273.15)
2502 Ghc will rewrite this to also include the source location where the
2509 assert pred val ==> assertError "Main.hs|15" pred val
2515 The rewrite is only performed by the compiler when it spots
2516 applications of <Function>Exception.assert</Function>, so you can still define and
2517 use your own versions of <Function>assert</Function>, should you so wish. If not,
2518 import <Literal>Exception</Literal> to make use <Function>assert</Function> in your code.
2522 To have the compiler ignore uses of assert, use the compiler option
2523 <Option>-fignore-asserts</Option>. <IndexTerm><Primary>-fignore-asserts option</Primary></IndexTerm> That is,
2524 expressions of the form <Literal>assert pred e</Literal> will be rewritten to <Literal>e</Literal>.
2528 Assertion failures can be caught, see the documentation for the
2529 Hugs/GHC Exception library for information of how.
2534 <Sect1 id="scoped-type-variables">
2535 <Title>Scoped Type Variables
2539 A <Emphasis>pattern type signature</Emphasis> can introduce a <Emphasis>scoped type
2540 variable</Emphasis>. For example
2546 f (xs::[a]) = ys ++ ys
2555 The pattern <Literal>(xs::[a])</Literal> includes a type signature for <VarName>xs</VarName>.
2556 This brings the type variable <Literal>a</Literal> into scope; it scopes over
2557 all the patterns and right hand sides for this equation for <Function>f</Function>.
2558 In particular, it is in scope at the type signature for <VarName>y</VarName>.
2562 At ordinary type signatures, such as that for <VarName>ys</VarName>, any type variables
2563 mentioned in the type signature <Emphasis>that are not in scope</Emphasis> are
2564 implicitly universally quantified. (If there are no type variables in
2565 scope, all type variables mentioned in the signature are universally
2566 quantified, which is just as in Haskell 98.) In this case, since <VarName>a</VarName>
2567 is in scope, it is not universally quantified, so the type of <VarName>ys</VarName> is
2568 the same as that of <VarName>xs</VarName>. In Haskell 98 it is not possible to declare
2569 a type for <VarName>ys</VarName>; a major benefit of scoped type variables is that
2570 it becomes possible to do so.
2574 Scoped type variables are implemented in both GHC and Hugs. Where the
2575 implementations differ from the specification below, those differences
2580 So much for the basic idea. Here are the details.
2584 <Title>Scope and implicit quantification</Title>
2592 All the type variables mentioned in the patterns for a single
2593 function definition equation, that are not already in scope,
2594 are brought into scope by the patterns. We describe this set as
2595 the <Emphasis>type variables bound by the equation</Emphasis>.
2602 The type variables thus brought into scope may be mentioned
2603 in ordinary type signatures or pattern type signatures anywhere within
2611 In ordinary type signatures, any type variable mentioned in the
2612 signature that is in scope is <Emphasis>not</Emphasis> universally quantified.
2619 Ordinary type signatures do not bring any new type variables
2620 into scope (except in the type signature itself!). So this is illegal:
2629 It's illegal because <VarName>a</VarName> is not in scope in the body of <Function>f</Function>,
2630 so the ordinary signature <Literal>x::a</Literal> is equivalent to <Literal>x::forall a.a</Literal>;
2631 and that is an incorrect typing.
2638 There is no implicit universal quantification on pattern type
2639 signatures, nor may one write an explicit <Literal>forall</Literal> type in a pattern
2640 type signature. The pattern type signature is a monotype.
2648 The type variables in the head of a <Literal>class</Literal> or <Literal>instance</Literal> declaration
2649 scope over the methods defined in the <Literal>where</Literal> part. For example:
2663 (Not implemented in Hugs yet, Dec 98).
2674 <Title>Polymorphism</Title>
2682 Pattern type signatures are completely orthogonal to ordinary, separate
2683 type signatures. The two can be used independently or together. There is
2684 no scoping associated with the names of the type variables in a separate type signature.
2689 f (xs::[b]) = reverse xs
2698 The function must be polymorphic in the type variables
2699 bound by all its equations. Operationally, the type variables bound
2700 by one equation must not:
2707 Be unified with a type (such as <Literal>Int</Literal>, or <Literal>[a]</Literal>).
2713 Be unified with a type variable free in the environment.
2719 Be unified with each other. (They may unify with the type variables
2720 bound by another equation for the same function, of course.)
2727 For example, the following all fail to type check:
2731 f (x::a) (y::b) = [x,y] -- a unifies with b
2733 g (x::a) = x + 1::Int -- a unifies with Int
2735 h x = let k (y::a) = [x,y] -- a is free in the
2736 in k x -- environment
2738 k (x::a) True = ... -- a unifies with Int
2739 k (x::Int) False = ...
2742 w (x::a) = x -- a unifies with [b]
2751 The pattern-bound type variable may, however, be constrained
2752 by the context of the principal type, thus:
2756 f (x::a) (y::a) = x+y*2
2760 gets the inferred type: <Literal>forall a. Num a => a -> a -> a</Literal>.
2771 <Title>Result type signatures</Title>
2779 The result type of a function can be given a signature,
2784 f (x::a) :: [a] = [x,x,x]
2788 The final <Literal>:: [a]</Literal> after all the patterns gives a signature to the
2789 result type. Sometimes this is the only way of naming the type variable
2794 f :: Int -> [a] -> [a]
2795 f n :: ([a] -> [a]) = let g (x::a, y::a) = (y,x)
2796 in \xs -> map g (reverse xs `zip` xs)
2808 Result type signatures are not yet implemented in Hugs.
2814 <Title>Pattern signatures on other constructs</Title>
2822 A pattern type signature can be on an arbitrary sub-pattern, not
2827 f ((x,y)::(a,b)) = (y,x) :: (b,a)
2836 Pattern type signatures, including the result part, can be used
2837 in lambda abstractions:
2841 (\ (x::a, y) :: a -> x)
2845 Type variables bound by these patterns must be polymorphic in
2846 the sense defined above.
2851 f1 (x::c) = f1 x -- ok
2852 f2 = \(x::c) -> f2 x -- not ok
2856 Here, <Function>f1</Function> is OK, but <Function>f2</Function> is not, because <VarName>c</VarName> gets unified
2857 with a type variable free in the environment, in this
2858 case, the type of <Function>f2</Function>, which is in the environment when
2859 the lambda abstraction is checked.
2866 Pattern type signatures, including the result part, can be used
2867 in <Literal>case</Literal> expressions:
2871 case e of { (x::a, y) :: a -> x }
2875 The pattern-bound type variables must, as usual,
2876 be polymorphic in the following sense: each case alternative,
2877 considered as a lambda abstraction, must be polymorphic.
2882 case (True,False) of { (x::a, y) -> x }
2886 Even though the context is that of a pair of booleans,
2887 the alternative itself is polymorphic. Of course, it is
2892 case (True,False) of { (x::Bool, y) -> x }
2901 To avoid ambiguity, the type after the “<Literal>::</Literal>” in a result
2902 pattern signature on a lambda or <Literal>case</Literal> must be atomic (i.e. a single
2903 token or a parenthesised type of some sort). To see why,
2904 consider how one would parse this:
2908 \ x :: a -> b -> x
2917 Pattern type signatures that bind new type variables
2918 may not be used in pattern bindings at all.
2923 f x = let (y, z::a) = x in ...
2927 But these are OK, because they do not bind fresh type variables:
2931 f1 x = let (y, z::Int) = x in ...
2932 f2 (x::(Int,a)) = let (y, z::a) = x in ...
2936 However a single variable is considered a degenerate function binding,
2937 rather than a degerate pattern binding, so this is permitted, even
2938 though it binds a type variable:
2942 f :: (b->b) = \(x::b) -> x
2951 Such degnerate function bindings do not fall under the monomorphism
2958 g :: a -> a -> Bool = \x y. x==y
2964 Here <Function>g</Function> has type <Literal>forall a. Eq a => a -> a -> Bool</Literal>, just as if
2965 <Function>g</Function> had a separate type signature. Lacking a type signature, <Function>g</Function>
2966 would get a monomorphic type.
2972 <Title>Existentials</Title>
2980 Pattern type signatures can bind existential type variables.
2985 data T = forall a. MkT [a]
2988 f (MkT [t::a]) = MkT t3
3005 <Sect1 id="pragmas">
3010 GHC supports several pragmas, or instructions to the compiler placed
3011 in the source code. Pragmas don't affect the meaning of the program,
3012 but they might affect the efficiency of the generated code.
3015 <Sect2 id="inline-pragma">
3016 <Title>INLINE pragma
3018 <IndexTerm><Primary>INLINE pragma</Primary></IndexTerm>
3019 <IndexTerm><Primary>pragma, INLINE</Primary></IndexTerm></Title>
3022 GHC (with <Option>-O</Option>, as always) tries to inline (or “unfold”)
3023 functions/values that are “small enough,” thus avoiding the call
3024 overhead and possibly exposing other more-wonderful optimisations.
3028 You will probably see these unfoldings (in Core syntax) in your
3033 Normally, if GHC decides a function is “too expensive” to inline, it
3034 will not do so, nor will it export that unfolding for other modules to
3039 The sledgehammer you can bring to bear is the
3040 <Literal>INLINE</Literal><IndexTerm><Primary>INLINE pragma</Primary></IndexTerm> pragma, used thusly:
3043 key_function :: Int -> String -> (Bool, Double)
3045 #ifdef __GLASGOW_HASKELL__
3046 {-# INLINE key_function #-}
3050 (You don't need to do the C pre-processor carry-on unless you're going
3051 to stick the code through HBC—it doesn't like <Literal>INLINE</Literal> pragmas.)
3055 The major effect of an <Literal>INLINE</Literal> pragma is to declare a function's
3056 “cost” to be very low. The normal unfolding machinery will then be
3057 very keen to inline it.
3061 An <Literal>INLINE</Literal> pragma for a function can be put anywhere its type
3062 signature could be put.
3066 <Literal>INLINE</Literal> pragmas are a particularly good idea for the
3067 <Literal>then</Literal>/<Literal>return</Literal> (or <Literal>bind</Literal>/<Literal>unit</Literal>) functions in a monad.
3068 For example, in GHC's own <Literal>UniqueSupply</Literal> monad code, we have:
3071 #ifdef __GLASGOW_HASKELL__
3072 {-# INLINE thenUs #-}
3073 {-# INLINE returnUs #-}
3081 <Sect2 id="noinline-pragma">
3082 <Title>NOINLINE pragma
3086 <IndexTerm><Primary>NOINLINE pragma</Primary></IndexTerm>
3087 <IndexTerm><Primary>pragma, NOINLINE</Primary></IndexTerm>
3091 The <Literal>NOINLINE</Literal> pragma does exactly what you'd expect: it stops the
3092 named function from being inlined by the compiler. You shouldn't ever
3093 need to do this, unless you're very cautious about code size.
3098 <Sect2 id="specialize-pragma">
3099 <Title>SPECIALIZE pragma
3103 <IndexTerm><Primary>SPECIALIZE pragma</Primary></IndexTerm>
3104 <IndexTerm><Primary>pragma, SPECIALIZE</Primary></IndexTerm>
3105 <IndexTerm><Primary>overloading, death to</Primary></IndexTerm>
3109 (UK spelling also accepted.) For key overloaded functions, you can
3110 create extra versions (NB: more code space) specialised to particular
3111 types. Thus, if you have an overloaded function:
3117 hammeredLookup :: Ord key => [(key, value)] -> key -> value
3123 If it is heavily used on lists with <Literal>Widget</Literal> keys, you could
3124 specialise it as follows:
3127 {-# SPECIALIZE hammeredLookup :: [(Widget, value)] -> Widget -> value #-}
3133 To get very fancy, you can also specify a named function to use for
3134 the specialised value, by adding <Literal>= blah</Literal>, as in:
3137 {-# SPECIALIZE hammeredLookup :: ...as before... = blah #-}
3140 It's <Emphasis>Your Responsibility</Emphasis> to make sure that <Function>blah</Function> really
3141 behaves as a specialised version of <Function>hammeredLookup</Function>!!!
3145 NOTE: the <Literal>=blah</Literal> feature isn't implemented in GHC 4.xx.
3149 An example in which the <Literal>= blah</Literal> form will Win Big:
3152 toDouble :: Real a => a -> Double
3153 toDouble = fromRational . toRational
3155 {-# SPECIALIZE toDouble :: Int -> Double = i2d #-}
3156 i2d (I# i) = D# (int2Double# i) -- uses Glasgow prim-op directly
3159 The <Function>i2d</Function> function is virtually one machine instruction; the
3160 default conversion—via an intermediate <Literal>Rational</Literal>—is obscenely
3161 expensive by comparison.
3165 By using the US spelling, your <Literal>SPECIALIZE</Literal> pragma will work with
3166 HBC, too. Note that HBC doesn't support the <Literal>= blah</Literal> form.
3170 A <Literal>SPECIALIZE</Literal> pragma for a function can be put anywhere its type
3171 signature could be put.
3176 <Sect2 id="specialize-instance-pragma">
3177 <Title>SPECIALIZE instance pragma
3181 <IndexTerm><Primary>SPECIALIZE pragma</Primary></IndexTerm>
3182 <IndexTerm><Primary>overloading, death to</Primary></IndexTerm>
3183 Same idea, except for instance declarations. For example:
3186 instance (Eq a) => Eq (Foo a) where { ... usual stuff ... }
3188 {-# SPECIALIZE instance Eq (Foo [(Int, Bar)] #-}
3191 Compatible with HBC, by the way.
3196 <Sect2 id="line-pragma">
3201 <IndexTerm><Primary>LINE pragma</Primary></IndexTerm>
3202 <IndexTerm><Primary>pragma, LINE</Primary></IndexTerm>
3206 This pragma is similar to C's <Literal>#line</Literal> pragma, and is mainly for use in
3207 automatically generated Haskell code. It lets you specify the line
3208 number and filename of the original code; for example
3214 {-# LINE 42 "Foo.vhs" #-}
3220 if you'd generated the current file from something called <Filename>Foo.vhs</Filename>
3221 and this line corresponds to line 42 in the original. GHC will adjust
3222 its error messages to refer to the line/file named in the <Literal>LINE</Literal>
3229 <Title>RULES pragma</Title>
3232 The RULES pragma lets you specify rewrite rules. It is described in
3233 <XRef LinkEnd="rewrite-rules">.
3240 <Sect1 id="rewrite-rules">
3241 <Title>Rewrite rules
3243 <IndexTerm><Primary>RULES pagma</Primary></IndexTerm>
3244 <IndexTerm><Primary>pragma, RULES</Primary></IndexTerm>
3245 <IndexTerm><Primary>rewrite rules</Primary></IndexTerm></Title>
3248 The programmer can specify rewrite rules as part of the source program
3249 (in a pragma). GHC applies these rewrite rules wherever it can.
3257 "map/map" forall f g xs. map f (map g xs) = map (f.g) xs
3264 <Title>Syntax</Title>
3267 From a syntactic point of view:
3273 Each rule has a name, enclosed in double quotes. The name itself has
3274 no significance at all. It is only used when reporting how many times the rule fired.
3280 There may be zero or more rules in a <Literal>RULES</Literal> pragma.
3286 Layout applies in a <Literal>RULES</Literal> pragma. Currently no new indentation level
3287 is set, so you must lay out your rules starting in the same column as the
3288 enclosing definitions.
3294 Each variable mentioned in a rule must either be in scope (e.g. <Function>map</Function>),
3295 or bound by the <Literal>forall</Literal> (e.g. <Function>f</Function>, <Function>g</Function>, <Function>xs</Function>). The variables bound by
3296 the <Literal>forall</Literal> are called the <Emphasis>pattern</Emphasis> variables. They are separated
3297 by spaces, just like in a type <Literal>forall</Literal>.
3303 A pattern variable may optionally have a type signature.
3304 If the type of the pattern variable is polymorphic, it <Emphasis>must</Emphasis> have a type signature.
3305 For example, here is the <Literal>foldr/build</Literal> rule:
3308 "fold/build" forall k z (g::forall b. (a->b->b) -> b -> b) .
3309 foldr k z (build g) = g k z
3312 Since <Function>g</Function> has a polymorphic type, it must have a type signature.
3319 The left hand side of a rule must consist of a top-level variable applied
3320 to arbitrary expressions. For example, this is <Emphasis>not</Emphasis> OK:
3323 "wrong1" forall e1 e2. case True of { True -> e1; False -> e2 } = e1
3324 "wrong2" forall f. f True = True
3327 In <Literal>"wrong1"</Literal>, the LHS is not an application; in <Literal>"wrong1"</Literal>, the LHS has a pattern variable
3334 A rule does not need to be in the same module as (any of) the
3335 variables it mentions, though of course they need to be in scope.
3341 Rules are automatically exported from a module, just as instance declarations are.
3352 <Title>Semantics</Title>
3355 From a semantic point of view:
3361 Rules are only applied if you use the <Option>-O</Option> flag.
3367 Rules are regarded as left-to-right rewrite rules.
3368 When GHC finds an expression that is a substitution instance of the LHS
3369 of a rule, it replaces the expression by the (appropriately-substituted) RHS.
3370 By "a substitution instance" we mean that the LHS can be made equal to the
3371 expression by substituting for the pattern variables.
3378 The LHS and RHS of a rule are typechecked, and must have the
3386 GHC makes absolutely no attempt to verify that the LHS and RHS
3387 of a rule have the same meaning. That is undecideable in general, and
3388 infeasible in most interesting cases. The responsibility is entirely the programmer's!
3395 GHC makes no attempt to make sure that the rules are confluent or
3396 terminating. For example:
3399 "loop" forall x,y. f x y = f y x
3402 This rule will cause the compiler to go into an infinite loop.
3409 If more than one rule matches a call, GHC will choose one arbitrarily to apply.
3415 GHC currently uses a very simple, syntactic, matching algorithm
3416 for matching a rule LHS with an expression. It seeks a substitution
3417 which makes the LHS and expression syntactically equal modulo alpha
3418 conversion. The pattern (rule), but not the expression, is eta-expanded if
3419 necessary. (Eta-expanding the epression can lead to laziness bugs.)
3420 But not beta conversion (that's called higher-order matching).
3424 Matching is carried out on GHC's intermediate language, which includes
3425 type abstractions and applications. So a rule only matches if the
3426 types match too. See <XRef LinkEnd="rule-spec"> below.
3432 GHC keeps trying to apply the rules as it optimises the program.
3433 For example, consider:
3442 The expression <Literal>s (t xs)</Literal> does not match the rule <Literal>"map/map"</Literal>, but GHC
3443 will substitute for <VarName>s</VarName> and <VarName>t</VarName>, giving an expression which does match.
3444 If <VarName>s</VarName> or <VarName>t</VarName> was (a) used more than once, and (b) large or a redex, then it would
3445 not be substituted, and the rule would not fire.
3452 In the earlier phases of compilation, GHC inlines <Emphasis>nothing
3453 that appears on the LHS of a rule</Emphasis>, because once you have substituted
3454 for something you can't match against it (given the simple minded
3455 matching). So if you write the rule
3458 "map/map" forall f,g. map f . map g = map (f.g)
3461 this <Emphasis>won't</Emphasis> match the expression <Literal>map f (map g xs)</Literal>.
3462 It will only match something written with explicit use of ".".
3463 Well, not quite. It <Emphasis>will</Emphasis> match the expression
3469 where <Function>wibble</Function> is defined:
3472 wibble f g = map f . map g
3475 because <Function>wibble</Function> will be inlined (it's small).
3477 Later on in compilation, GHC starts inlining even things on the
3478 LHS of rules, but still leaves the rules enabled. This inlining
3479 policy is controlled by the per-simplification-pass flag <Option>-finline-phase</Option><Emphasis>n</Emphasis>.
3486 All rules are implicitly exported from the module, and are therefore
3487 in force in any module that imports the module that defined the rule, directly
3488 or indirectly. (That is, if A imports B, which imports C, then C's rules are
3489 in force when compiling A.) The situation is very similar to that for instance
3501 <Title>List fusion</Title>
3504 The RULES mechanism is used to implement fusion (deforestation) of common list functions.
3505 If a "good consumer" consumes an intermediate list constructed by a "good producer", the
3506 intermediate list should be eliminated entirely.
3510 The following are good producers:
3522 Enumerations of <Literal>Int</Literal> and <Literal>Char</Literal> (e.g. <Literal>['a'..'z']</Literal>).
3528 Explicit lists (e.g. <Literal>[True, False]</Literal>)
3534 The cons constructor (e.g <Literal>3:4:[]</Literal>)
3540 <Function>++</Function>
3546 <Function>map</Function>
3552 <Function>filter</Function>
3558 <Function>iterate</Function>, <Function>repeat</Function>
3564 <Function>zip</Function>, <Function>zipWith</Function>
3573 The following are good consumers:
3585 <Function>array</Function> (on its second argument)
3591 <Function>length</Function>
3597 <Function>++</Function> (on its first argument)
3603 <Function>map</Function>
3609 <Function>filter</Function>
3615 <Function>concat</Function>
3621 <Function>unzip</Function>, <Function>unzip2</Function>, <Function>unzip3</Function>, <Function>unzip4</Function>
3627 <Function>zip</Function>, <Function>zipWith</Function> (but on one argument only; if both are good producers, <Function>zip</Function>
3628 will fuse with one but not the other)
3634 <Function>partition</Function>
3640 <Function>head</Function>
3646 <Function>and</Function>, <Function>or</Function>, <Function>any</Function>, <Function>all</Function>
3652 <Function>sequence_</Function>
3658 <Function>msum</Function>
3664 <Function>sortBy</Function>
3673 So, for example, the following should generate no intermediate lists:
3676 array (1,10) [(i,i*i) | i <- map (+ 1) [0..9]]
3682 This list could readily be extended; if there are Prelude functions that you use
3683 a lot which are not included, please tell us.
3687 If you want to write your own good consumers or producers, look at the
3688 Prelude definitions of the above functions to see how to do so.
3693 <Sect2 id="rule-spec">
3694 <Title>Specialisation
3698 Rewrite rules can be used to get the same effect as a feature
3699 present in earlier version of GHC:
3702 {-# SPECIALIZE fromIntegral :: Int8 -> Int16 = int8ToInt16 #-}
3705 This told GHC to use <Function>int8ToInt16</Function> instead of <Function>fromIntegral</Function> whenever
3706 the latter was called with type <Literal>Int8 -> Int16</Literal>. That is, rather than
3707 specialising the original definition of <Function>fromIntegral</Function> the programmer is
3708 promising that it is safe to use <Function>int8ToInt16</Function> instead.
3712 This feature is no longer in GHC. But rewrite rules let you do the
3717 "fromIntegral/Int8/Int16" fromIntegral = int8ToInt16
3721 This slightly odd-looking rule instructs GHC to replace <Function>fromIntegral</Function>
3722 by <Function>int8ToInt16</Function> <Emphasis>whenever the types match</Emphasis>. Speaking more operationally,
3723 GHC adds the type and dictionary applications to get the typed rule
3726 forall (d1::Integral Int8) (d2::Num Int16) .
3727 fromIntegral Int8 Int16 d1 d2 = int8ToInt16
3731 this rule does not need to be in the same file as fromIntegral,
3732 unlike the <Literal>SPECIALISE</Literal> pragmas which currently do (so that they
3733 have an original definition available to specialise).
3739 <Title>Controlling what's going on</Title>
3747 Use <Option>-ddump-rules</Option> to see what transformation rules GHC is using.
3753 Use <Option>-ddump-simpl-stats</Option> to see what rules are being fired.
3754 If you add <Option>-dppr-debug</Option> you get a more detailed listing.
3760 The defintion of (say) <Function>build</Function> in <FileName>PrelBase.lhs</FileName> looks llike this:
3763 build :: forall a. (forall b. (a -> b -> b) -> b -> b) -> [a]
3764 {-# INLINE build #-}
3768 Notice the <Literal>INLINE</Literal>! That prevents <Literal>(:)</Literal> from being inlined when compiling
3769 <Literal>PrelBase</Literal>, so that an importing module will “see” the <Literal>(:)</Literal>, and can
3770 match it on the LHS of a rule. <Literal>INLINE</Literal> prevents any inlining happening
3771 in the RHS of the <Literal>INLINE</Literal> thing. I regret the delicacy of this.
3778 In <Filename>ghc/lib/std/PrelBase.lhs</Filename> look at the rules for <Function>map</Function> to
3779 see how to write rules that will do fusion and yet give an efficient
3780 program even if fusion doesn't happen. More rules in <Filename>PrelList.lhs</Filename>.