[project @ 2000-10-05 15:33:03 by simonpj]
[ghc-hetmet.git] / ghc / docs / users_guide / glasgow_exts.sgml
1 <Para>
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.
7 </Para>
8
9 <Para>
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 &ldquo;stuck&rdquo; on
14 performance because of the implementation costs of Haskell's
15 &ldquo;high-level&rdquo; features&mdash;you can always code &ldquo;under&rdquo; them.  In an extreme case, you can write all your time-critical code in C, and then just glue it together with Haskell!
16 </Para>
17
18 <Para>
19 Executive summary of our extensions:
20 </Para>
21
22 <Para>
23 <VariableList>
24
25 <VarListEntry>
26 <Term>Unboxed types and primitive operations:</Term>
27 <ListItem>
28 <Para>
29 You can get right down to the raw machine types and operations;
30 included in this are &ldquo;primitive arrays&rdquo; (direct access to Big Wads
31 of Bytes).  Please see <XRef LinkEnd="glasgow-unboxed"> and following.
32 </Para>
33 </ListItem>
34 </VarListEntry>
35
36 <VarListEntry>
37 <Term>Multi-parameter type classes:</Term>
38 <ListItem>
39 <Para>
40 GHC's type system supports extended type classes with multiple
41 parameters.  Please see <XRef LinkEnd="multi-param-type-classes">.
42 </Para>
43 </ListItem>
44 </VarListEntry>
45
46 <VarListEntry>
47 <Term>Local universal quantification:</Term>
48 <ListItem>
49 <Para>
50 GHC's type system supports explicit universal quantification in
51 constructor fields and function arguments.  This is useful for things
52 like defining <Literal>runST</Literal> from the state-thread world.  See <XRef LinkEnd="universal-quantification">.
53 </Para>
54 </ListItem>
55 </VarListEntry>
56
57 <VarListEntry>
58 <Term>Extistentially quantification in data types:</Term>
59 <ListItem>
60 <Para>
61 Some or all of the type variables in a datatype declaration may be
62 <Emphasis>existentially quantified</Emphasis>.  More details in <XRef LinkEnd="existential-quantification">.
63 </Para>
64 </ListItem>
65 </VarListEntry>
66
67 <VarListEntry>
68 <Term>Scoped type variables:</Term>
69 <ListItem>
70 <Para>
71 Scoped type variables enable the programmer to supply type signatures
72 for some nested declarations, where this would not be legal in Haskell
73 98.  Details in <XRef LinkEnd="scoped-type-variables">.
74 </Para>
75 </ListItem>
76 </VarListEntry>
77
78 <VarListEntry>
79 <Term>Pattern guards</Term>
80 <ListItem>
81 <Para>
82 Instead of being a boolean expression, a guard is a list of qualifiers, exactly as in a list comprehension. See <XRef LinkEnd="pattern-guards">.
83 </Para>
84 </ListItem>
85 </VarListEntry>
86
87 <VarListEntry>
88 <Term>Foreign calling:</Term>
89 <ListItem>
90 <Para>
91 Just what it sounds like.  We provide <Emphasis>lots</Emphasis> of rope that you
92 can dangle around your neck.  Please see <XRef LinkEnd="ffi">.
93 </Para>
94 </ListItem>
95 </VarListEntry>
96
97 <VarListEntry>
98 <Term>Pragmas</Term>
99 <ListItem>
100 <Para>
101 Pragmas are special instructions to the compiler placed in the source
102 file.  The pragmas GHC supports are described in <XRef LinkEnd="pragmas">.
103 </Para>
104 </ListItem>
105 </VarListEntry>
106
107 <VarListEntry>
108 <Term>Rewrite rules:</Term>
109 <ListItem>
110 <Para>
111 The programmer can specify rewrite rules as part of the source program
112 (in a pragma).  GHC applies these rewrite rules wherever it can.
113 Details in <XRef LinkEnd="rewrite-rules">.
114 </Para>
115 </ListItem>
116 </VarListEntry>
117
118 <VarListEntry>
119 <Term>Generic classes:</Term>
120 <ListItem>
121 <Para>
122 Generic class declarations allow you to define a class
123 whose methods say how to work over an arbitrary data type.
124 Then it's really easy to make any new type into an instance of
125 the class.  This generalises the rather ad-hoc "deriving" feature
126 of Haskell 98.
127 Details in <XRef LinkEnd="generic-classes">.
128 </Para>
129 </ListItem>
130 </VarListEntry>
131 </VariableList>
132 </Para>
133
134 <Para>
135 Before you get too carried away working at the lowest level (e.g.,
136 sloshing <Literal>MutableByteArray&num;</Literal>s around your
137 program), you may wish to check if there are libraries that provide a
138 &ldquo;Haskellised veneer&rdquo; over the features you want.  See
139 <xref linkend="book-hslibs">.
140 </Para>
141
142 <Sect1 id="primitives">
143 <Title>Unboxed types and primitive operations
144 </Title>
145 <IndexTerm><Primary>PrelGHC module</Primary></IndexTerm>
146
147 <Para>
148 This module defines all the types which are primitive in Glasgow
149 Haskell, and the operations provided for them.
150 </Para>
151
152 <Sect2 id="glasgow-unboxed">
153 <Title>Unboxed types
154 </Title>
155
156 <Para>
157 <IndexTerm><Primary>Unboxed types (Glasgow extension)</Primary></IndexTerm>
158 </Para>
159
160 <para>Most types in GHC are <firstterm>boxed</firstterm>, which means
161 that values of that type are represented by a pointer to a heap
162 object.  The representation of a Haskell <literal>Int</literal>, for
163 example, is a two-word heap object.  An <firstterm>unboxed</firstterm>
164 type, however, is represented by the value itself, no pointers or heap
165 allocation are involved.
166 </para>
167
168 <Para>
169 Unboxed types correspond to the &ldquo;raw machine&rdquo; types you
170 would use in C: <Literal>Int&num;</Literal> (long int),
171 <Literal>Double&num;</Literal> (double), <Literal>Addr&num;</Literal>
172 (void *), etc.  The <Emphasis>primitive operations</Emphasis>
173 (PrimOps) on these types are what you might expect; e.g.,
174 <Literal>(+&num;)</Literal> is addition on
175 <Literal>Int&num;</Literal>s, and is the machine-addition that we all
176 know and love&mdash;usually one instruction.
177 </Para>
178
179 <Para>
180 Primitive (unboxed) types cannot be defined in Haskell, and are
181 therefore built into the language and compiler.  Primitive types are
182 always unlifted; that is, a value of a primitive type cannot be
183 bottom.  We use the convention that primitive types, values, and
184 operations have a <Literal>&num;</Literal> suffix.
185 </Para>
186
187 <Para>
188 Primitive values are often represented by a simple bit-pattern, such
189 as <Literal>Int&num;</Literal>, <Literal>Float&num;</Literal>,
190 <Literal>Double&num;</Literal>.  But this is not necessarily the case:
191 a primitive value might be represented by a pointer to a
192 heap-allocated object.  Examples include
193 <Literal>Array&num;</Literal>, the type of primitive arrays.  A
194 primitive array is heap-allocated because it is too big a value to fit
195 in a register, and would be too expensive to copy around; in a sense,
196 it is accidental that it is represented by a pointer.  If a pointer
197 represents a primitive value, then it really does point to that value:
198 no unevaluated thunks, no indirections&hellip;nothing can be at the
199 other end of the pointer than the primitive value.
200 </Para>
201
202 <Para>
203 There are some restrictions on the use of primitive types, the main
204 one being that you can't pass a primitive value to a polymorphic
205 function or store one in a polymorphic data type.  This rules out
206 things like <Literal>[Int&num;]</Literal> (i.e. lists of primitive
207 integers).  The reason for this restriction is that polymorphic
208 arguments and constructor fields are assumed to be pointers: if an
209 unboxed integer is stored in one of these, the garbage collector would
210 attempt to follow it, leading to unpredictable space leaks.  Or a
211 <Function>seq</Function> operation on the polymorphic component may
212 attempt to dereference the pointer, with disastrous results.  Even
213 worse, the unboxed value might be larger than a pointer
214 (<Literal>Double&num;</Literal> for instance).
215 </Para>
216
217 <Para>
218 Nevertheless, A numerically-intensive program using unboxed types can
219 go a <Emphasis>lot</Emphasis> faster than its &ldquo;standard&rdquo;
220 counterpart&mdash;we saw a threefold speedup on one example.
221 </Para>
222
223 </sect2>
224
225 <Sect2 id="unboxed-tuples">
226 <Title>Unboxed Tuples
227 </Title>
228
229 <Para>
230 Unboxed tuples aren't really exported by <Literal>PrelGHC</Literal>,
231 they're available by default with <Option>-fglasgow-exts</Option>.  An
232 unboxed tuple looks like this:
233 </Para>
234
235 <Para>
236
237 <ProgramListing>
238 (# e_1, ..., e_n #)
239 </ProgramListing>
240
241 </Para>
242
243 <Para>
244 where <Literal>e&lowbar;1..e&lowbar;n</Literal> are expressions of any
245 type (primitive or non-primitive).  The type of an unboxed tuple looks
246 the same.
247 </Para>
248
249 <Para>
250 Unboxed tuples are used for functions that need to return multiple
251 values, but they avoid the heap allocation normally associated with
252 using fully-fledged tuples.  When an unboxed tuple is returned, the
253 components are put directly into registers or on the stack; the
254 unboxed tuple itself does not have a composite representation.  Many
255 of the primitive operations listed in this section return unboxed
256 tuples.
257 </Para>
258
259 <Para>
260 There are some pretty stringent restrictions on the use of unboxed tuples:
261 </Para>
262
263 <Para>
264
265 <ItemizedList>
266 <ListItem>
267
268 <Para>
269  Unboxed tuple types are subject to the same restrictions as
270 other unboxed types; i.e. they may not be stored in polymorphic data
271 structures or passed to polymorphic functions.
272
273 </Para>
274 </ListItem>
275 <ListItem>
276
277 <Para>
278  Unboxed tuples may only be constructed as the direct result of
279 a function, and may only be deconstructed with a <Literal>case</Literal> expression.
280 eg. the following are valid:
281
282
283 <ProgramListing>
284 f x y = (# x+1, y-1 #)
285 g x = case f x x of { (# a, b #) -&#62; a + b }
286 </ProgramListing>
287
288
289 but the following are invalid:
290
291
292 <ProgramListing>
293 f x y = g (# x, y #)
294 g (# x, y #) = x + y
295 </ProgramListing>
296
297
298 </Para>
299 </ListItem>
300 <ListItem>
301
302 <Para>
303  No variable can have an unboxed tuple type.  This is illegal:
304
305
306 <ProgramListing>
307 f :: (# Int, Int #) -&#62; (# Int, Int #)
308 f x = x
309 </ProgramListing>
310
311
312 because <VarName>x</VarName> has an unboxed tuple type.
313
314 </Para>
315 </ListItem>
316
317 </ItemizedList>
318
319 </Para>
320
321 <Para>
322 Note: we may relax some of these restrictions in the future.
323 </Para>
324
325 <Para>
326 The <Literal>IO</Literal> and <Literal>ST</Literal> monads use unboxed tuples to avoid unnecessary
327 allocation during sequences of operations.
328 </Para>
329
330 </Sect2>
331
332 <Sect2>
333 <Title>Character and numeric types</Title>
334
335 <Para>
336 <IndexTerm><Primary>character types, primitive</Primary></IndexTerm>
337 <IndexTerm><Primary>numeric types, primitive</Primary></IndexTerm>
338 <IndexTerm><Primary>integer types, primitive</Primary></IndexTerm>
339 <IndexTerm><Primary>floating point types, primitive</Primary></IndexTerm>
340 There are the following obvious primitive types:
341 </Para>
342
343 <Para>
344
345 <ProgramListing>
346 type Char#
347 type Int#
348 type Word#
349 type Addr#
350 type Float#
351 type Double#
352 type Int64#
353 type Word64#
354 </ProgramListing>
355
356 <IndexTerm><Primary><literal>Char&num;</literal></Primary></IndexTerm>
357 <IndexTerm><Primary><literal>Int&num;</literal></Primary></IndexTerm>
358 <IndexTerm><Primary><literal>Word&num;</literal></Primary></IndexTerm>
359 <IndexTerm><Primary><literal>Addr&num;</literal></Primary></IndexTerm>
360 <IndexTerm><Primary><literal>Float&num;</literal></Primary></IndexTerm>
361 <IndexTerm><Primary><literal>Double&num;</literal></Primary></IndexTerm>
362 <IndexTerm><Primary><literal>Int64&num;</literal></Primary></IndexTerm>
363 <IndexTerm><Primary><literal>Word64&num;</literal></Primary></IndexTerm>
364 </Para>
365
366 <Para>
367 If you really want to know their exact equivalents in C, see
368 <Filename>ghc/includes/StgTypes.h</Filename> in the GHC source tree.
369 </Para>
370
371 <Para>
372 Literals for these types may be written as follows:
373 </Para>
374
375 <Para>
376
377 <ProgramListing>
378 1#              an Int#
379 1.2#            a Float#
380 1.34##          a Double#
381 'a'#            a Char#; for weird characters, use e.g. '\o&#60;octal&#62;'#
382 "a"#            an Addr# (a `char *'); only characters '\0'..'\255' allowed
383 </ProgramListing>
384
385 <IndexTerm><Primary>literals, primitive</Primary></IndexTerm>
386 <IndexTerm><Primary>constants, primitive</Primary></IndexTerm>
387 <IndexTerm><Primary>numbers, primitive</Primary></IndexTerm>
388 </Para>
389
390 </Sect2>
391
392 <Sect2>
393 <Title>Comparison operations</Title>
394
395 <Para>
396 <IndexTerm><Primary>comparisons, primitive</Primary></IndexTerm>
397 <IndexTerm><Primary>operators, comparison</Primary></IndexTerm>
398 </Para>
399
400 <Para>
401
402 <ProgramListing>
403 {&#62;,&#62;=,==,/=,&#60;,&#60;=}# :: Int# -&#62; Int# -&#62; Bool
404
405 {gt,ge,eq,ne,lt,le}Char# :: Char# -&#62; Char# -&#62; Bool
406     -- ditto for Word# and Addr#
407 </ProgramListing>
408
409 <IndexTerm><Primary><literal>&#62;&num;</literal></Primary></IndexTerm>
410 <IndexTerm><Primary><literal>&#62;=&num;</literal></Primary></IndexTerm>
411 <IndexTerm><Primary><literal>==&num;</literal></Primary></IndexTerm>
412 <IndexTerm><Primary><literal>/=&num;</literal></Primary></IndexTerm>
413 <IndexTerm><Primary><literal>&#60;&num;</literal></Primary></IndexTerm>
414 <IndexTerm><Primary><literal>&#60;=&num;</literal></Primary></IndexTerm>
415 <IndexTerm><Primary><literal>gt&lcub;Char,Word,Addr&rcub;&num;</literal></Primary></IndexTerm>
416 <IndexTerm><Primary><literal>ge&lcub;Char,Word,Addr&rcub;&num;</literal></Primary></IndexTerm>
417 <IndexTerm><Primary><literal>eq&lcub;Char,Word,Addr&rcub;&num;</literal></Primary></IndexTerm>
418 <IndexTerm><Primary><literal>ne&lcub;Char,Word,Addr&rcub;&num;</literal></Primary></IndexTerm>
419 <IndexTerm><Primary><literal>lt&lcub;Char,Word,Addr&rcub;&num;</literal></Primary></IndexTerm>
420 <IndexTerm><Primary><literal>le&lcub;Char,Word,Addr&rcub;&num;</literal></Primary></IndexTerm>
421 </Para>
422
423 </Sect2>
424
425 <Sect2>
426 <Title>Primitive-character operations</Title>
427
428 <Para>
429 <IndexTerm><Primary>characters, primitive operations</Primary></IndexTerm>
430 <IndexTerm><Primary>operators, primitive character</Primary></IndexTerm>
431 </Para>
432
433 <Para>
434
435 <ProgramListing>
436 ord# :: Char# -&#62; Int#
437 chr# :: Int# -&#62; Char#
438 </ProgramListing>
439
440 <IndexTerm><Primary><literal>ord&num;</literal></Primary></IndexTerm>
441 <IndexTerm><Primary><literal>chr&num;</literal></Primary></IndexTerm>
442 </Para>
443
444 </Sect2>
445
446 <Sect2>
447 <Title>Primitive-<Literal>Int</Literal> operations</Title>
448
449 <Para>
450 <IndexTerm><Primary>integers, primitive operations</Primary></IndexTerm>
451 <IndexTerm><Primary>operators, primitive integer</Primary></IndexTerm>
452 </Para>
453
454 <Para>
455
456 <ProgramListing>
457 {+,-,*,quotInt,remInt,gcdInt}# :: Int# -&#62; Int# -&#62; Int#
458 negateInt# :: Int# -&#62; Int#
459
460 iShiftL#, iShiftRA#, iShiftRL# :: Int# -&#62; Int# -&#62; Int#
461         -- shift left, right arithmetic, right logical
462
463 addIntC#, subIntC#, mulIntC# :: Int# -> Int# -> (# Int#, Int# #)
464         -- add, subtract, multiply with carry
465 </ProgramListing>
466
467 <IndexTerm><Primary><literal>+&num;</literal></Primary></IndexTerm>
468 <IndexTerm><Primary><literal>-&num;</literal></Primary></IndexTerm>
469 <IndexTerm><Primary><literal>*&num;</literal></Primary></IndexTerm>
470 <IndexTerm><Primary><literal>quotInt&num;</literal></Primary></IndexTerm>
471 <IndexTerm><Primary><literal>remInt&num;</literal></Primary></IndexTerm>
472 <IndexTerm><Primary><literal>gcdInt&num;</literal></Primary></IndexTerm>
473 <IndexTerm><Primary><literal>iShiftL&num;</literal></Primary></IndexTerm>
474 <IndexTerm><Primary><literal>iShiftRA&num;</literal></Primary></IndexTerm>
475 <IndexTerm><Primary><literal>iShiftRL&num;</literal></Primary></IndexTerm>
476 <IndexTerm><Primary><literal>addIntC&num;</literal></Primary></IndexTerm>
477 <IndexTerm><Primary><literal>subIntC&num;</literal></Primary></IndexTerm>
478 <IndexTerm><Primary><literal>mulIntC&num;</literal></Primary></IndexTerm>
479 <IndexTerm><Primary>shift operations, integer</Primary></IndexTerm>
480 </Para>
481
482 <Para>
483 <Emphasis>Note:</Emphasis> No error/overflow checking!
484 </Para>
485
486 </Sect2>
487
488 <Sect2>
489 <Title>Primitive-<Literal>Double</Literal> and <Literal>Float</Literal> operations</Title>
490
491 <Para>
492 <IndexTerm><Primary>floating point numbers, primitive</Primary></IndexTerm>
493 <IndexTerm><Primary>operators, primitive floating point</Primary></IndexTerm>
494 </Para>
495
496 <Para>
497
498 <ProgramListing>
499 {+,-,*,/}##         :: Double# -&#62; Double# -&#62; Double#
500 {&#60;,&#60;=,==,/=,&#62;=,&#62;}## :: Double# -&#62; Double# -&#62; Bool
501 negateDouble#       :: Double# -&#62; Double#
502 double2Int#         :: Double# -&#62; Int#
503 int2Double#         :: Int#    -&#62; Double#
504
505 {plus,minux,times,divide}Float# :: Float# -&#62; Float# -&#62; Float#
506 {gt,ge,eq,ne,lt,le}Float# :: Float# -&#62; Float# -&#62; Bool
507 negateFloat#        :: Float# -&#62; Float#
508 float2Int#          :: Float# -&#62; Int#
509 int2Float#          :: Int#   -&#62; Float#
510 </ProgramListing>
511
512 </Para>
513
514 <Para>
515 <IndexTerm><Primary><literal>+&num;&num;</literal></Primary></IndexTerm>
516 <IndexTerm><Primary><literal>-&num;&num;</literal></Primary></IndexTerm>
517 <IndexTerm><Primary><literal>*&num;&num;</literal></Primary></IndexTerm>
518 <IndexTerm><Primary><literal>/&num;&num;</literal></Primary></IndexTerm>
519 <IndexTerm><Primary><literal>&#60;&num;&num;</literal></Primary></IndexTerm>
520 <IndexTerm><Primary><literal>&#60;=&num;&num;</literal></Primary></IndexTerm>
521 <IndexTerm><Primary><literal>==&num;&num;</literal></Primary></IndexTerm>
522 <IndexTerm><Primary><literal>=/&num;&num;</literal></Primary></IndexTerm>
523 <IndexTerm><Primary><literal>&#62;=&num;&num;</literal></Primary></IndexTerm>
524 <IndexTerm><Primary><literal>&#62;&num;&num;</literal></Primary></IndexTerm>
525 <IndexTerm><Primary><literal>negateDouble&num;</literal></Primary></IndexTerm>
526 <IndexTerm><Primary><literal>double2Int&num;</literal></Primary></IndexTerm>
527 <IndexTerm><Primary><literal>int2Double&num;</literal></Primary></IndexTerm>
528 </Para>
529
530 <Para>
531 <IndexTerm><Primary><literal>plusFloat&num;</literal></Primary></IndexTerm>
532 <IndexTerm><Primary><literal>minusFloat&num;</literal></Primary></IndexTerm>
533 <IndexTerm><Primary><literal>timesFloat&num;</literal></Primary></IndexTerm>
534 <IndexTerm><Primary><literal>divideFloat&num;</literal></Primary></IndexTerm>
535 <IndexTerm><Primary><literal>gtFloat&num;</literal></Primary></IndexTerm>
536 <IndexTerm><Primary><literal>geFloat&num;</literal></Primary></IndexTerm>
537 <IndexTerm><Primary><literal>eqFloat&num;</literal></Primary></IndexTerm>
538 <IndexTerm><Primary><literal>neFloat&num;</literal></Primary></IndexTerm>
539 <IndexTerm><Primary><literal>ltFloat&num;</literal></Primary></IndexTerm>
540 <IndexTerm><Primary><literal>leFloat&num;</literal></Primary></IndexTerm>
541 <IndexTerm><Primary><literal>negateFloat&num;</literal></Primary></IndexTerm>
542 <IndexTerm><Primary><literal>float2Int&num;</literal></Primary></IndexTerm>
543 <IndexTerm><Primary><literal>int2Float&num;</literal></Primary></IndexTerm>
544 </Para>
545
546 <Para>
547 And a full complement of trigonometric functions:
548 </Para>
549
550 <Para>
551
552 <ProgramListing>
553 expDouble#      :: Double# -&#62; Double#
554 logDouble#      :: Double# -&#62; Double#
555 sqrtDouble#     :: Double# -&#62; Double#
556 sinDouble#      :: Double# -&#62; Double#
557 cosDouble#      :: Double# -&#62; Double#
558 tanDouble#      :: Double# -&#62; Double#
559 asinDouble#     :: Double# -&#62; Double#
560 acosDouble#     :: Double# -&#62; Double#
561 atanDouble#     :: Double# -&#62; Double#
562 sinhDouble#     :: Double# -&#62; Double#
563 coshDouble#     :: Double# -&#62; Double#
564 tanhDouble#     :: Double# -&#62; Double#
565 powerDouble#    :: Double# -&#62; Double# -&#62; Double#
566 </ProgramListing>
567
568 <IndexTerm><Primary>trigonometric functions, primitive</Primary></IndexTerm>
569 </Para>
570
571 <Para>
572 similarly for <Literal>Float&num;</Literal>.
573 </Para>
574
575 <Para>
576 There are two coercion functions for <Literal>Float&num;</Literal>/<Literal>Double&num;</Literal>:
577 </Para>
578
579 <Para>
580
581 <ProgramListing>
582 float2Double#   :: Float# -&#62; Double#
583 double2Float#   :: Double# -&#62; Float#
584 </ProgramListing>
585
586 <IndexTerm><Primary><literal>float2Double&num;</literal></Primary></IndexTerm>
587 <IndexTerm><Primary><literal>double2Float&num;</literal></Primary></IndexTerm>
588 </Para>
589
590 <Para>
591 The primitive version of <Function>decodeDouble</Function>
592 (<Function>encodeDouble</Function> is implemented as an external C
593 function):
594 </Para>
595
596 <Para>
597
598 <ProgramListing>
599 decodeDouble#   :: Double# -&#62; PrelNum.ReturnIntAndGMP
600 </ProgramListing>
601
602 <IndexTerm><Primary><literal>encodeDouble&num;</literal></Primary></IndexTerm>
603 <IndexTerm><Primary><literal>decodeDouble&num;</literal></Primary></IndexTerm>
604 </Para>
605
606 <Para>
607 (And the same for <Literal>Float&num;</Literal>s.)
608 </Para>
609
610 </Sect2>
611
612 <Sect2 id="integer-operations">
613 <Title>Operations on/for <Literal>Integers</Literal> (interface to GMP)
614 </Title>
615
616 <Para>
617 <IndexTerm><Primary>arbitrary precision integers</Primary></IndexTerm>
618 <IndexTerm><Primary>Integer, operations on</Primary></IndexTerm>
619 </Para>
620
621 <Para>
622 We implement <Literal>Integers</Literal> (arbitrary-precision
623 integers) using the GNU multiple-precision (GMP) package (version
624 2.0.2).
625 </Para>
626
627 <Para>
628 The data type for <Literal>Integer</Literal> is either a small
629 integer, represented by an <Literal>Int</Literal>, or a large integer
630 represented using the pieces required by GMP's
631 <Literal>MP&lowbar;INT</Literal> in <Filename>gmp.h</Filename> (see
632 <Filename>gmp.info</Filename> in
633 <Filename>ghc/includes/runtime/gmp</Filename>).  It comes out as:
634 </Para>
635
636 <Para>
637
638 <ProgramListing>
639 data Integer = S# Int#             -- small integers
640              | J# Int# ByteArray#  -- large integers
641 </ProgramListing>
642
643 <IndexTerm><Primary>Integer type</Primary></IndexTerm> The primitive
644 ops to support large <Literal>Integers</Literal> use the
645 &ldquo;pieces&rdquo; of the representation, and are as follows:
646 </Para>
647
648 <Para>
649
650 <ProgramListing>
651 negateInteger#  :: Int# -&#62; ByteArray# -&#62; Integer
652
653 {plus,minus,times}Integer#, gcdInteger#, 
654   quotInteger#, remInteger#, divExactInteger#
655         :: Int# -> ByteArray#
656         -> Int# -> ByteArray#
657         -> (# Int#, ByteArray# #)
658
659 cmpInteger# 
660         :: Int# -> ByteArray#
661         -> Int# -> ByteArray#
662         -> Int# -- -1 for &#60;; 0 for ==; +1 for >
663
664 cmpIntegerInt# 
665         :: Int# -> ByteArray#
666         -> Int#
667         -> Int# -- -1 for &#60;; 0 for ==; +1 for >
668
669 gcdIntegerInt# :: 
670         :: Int# -> ByteArray#
671         -> Int#
672         -> Int#
673
674 divModInteger#, quotRemInteger#
675         :: Int# -> ByteArray#
676         -> Int# -> ByteArray#
677         -> (# Int#, ByteArray#,
678                   Int#, ByteArray# #)
679
680 integer2Int# :: Int# -> ByteArray# -> Int#
681
682 int2Integer#  :: Int#  -> Integer -- NB: no error-checking on these two!
683 word2Integer# :: Word# -> Integer
684
685 addr2Integer# :: Addr# -> Integer
686         -- the Addr# is taken to be a `char *' string
687         -- to be converted into an Integer.
688 </ProgramListing>
689
690 <IndexTerm><Primary><literal>negateInteger&num;</literal></Primary></IndexTerm>
691 <IndexTerm><Primary><literal>plusInteger&num;</literal></Primary></IndexTerm>
692 <IndexTerm><Primary><literal>minusInteger&num;</literal></Primary></IndexTerm>
693 <IndexTerm><Primary><literal>timesInteger&num;</literal></Primary></IndexTerm>
694 <IndexTerm><Primary><literal>quotInteger&num;</literal></Primary></IndexTerm>
695 <IndexTerm><Primary><literal>remInteger&num;</literal></Primary></IndexTerm>
696 <IndexTerm><Primary><literal>gcdInteger&num;</literal></Primary></IndexTerm>
697 <IndexTerm><Primary><literal>gcdIntegerInt&num;</literal></Primary></IndexTerm>
698 <IndexTerm><Primary><literal>divExactInteger&num;</literal></Primary></IndexTerm>
699 <IndexTerm><Primary><literal>cmpInteger&num;</literal></Primary></IndexTerm>
700 <IndexTerm><Primary><literal>divModInteger&num;</literal></Primary></IndexTerm>
701 <IndexTerm><Primary><literal>quotRemInteger&num;</literal></Primary></IndexTerm>
702 <IndexTerm><Primary><literal>integer2Int&num;</literal></Primary></IndexTerm>
703 <IndexTerm><Primary><literal>int2Integer&num;</literal></Primary></IndexTerm>
704 <IndexTerm><Primary><literal>word2Integer&num;</literal></Primary></IndexTerm>
705 <IndexTerm><Primary><literal>addr2Integer&num;</literal></Primary></IndexTerm>
706 </Para>
707
708 </Sect2>
709
710 <Sect2>
711 <Title>Words and addresses</Title>
712
713 <Para>
714 <IndexTerm><Primary>word, primitive type</Primary></IndexTerm>
715 <IndexTerm><Primary>address, primitive type</Primary></IndexTerm>
716 <IndexTerm><Primary>unsigned integer, primitive type</Primary></IndexTerm>
717 <IndexTerm><Primary>pointer, primitive type</Primary></IndexTerm>
718 </Para>
719
720 <Para>
721 A <Literal>Word&num;</Literal> is used for bit-twiddling operations.
722 It is the same size as an <Literal>Int&num;</Literal>, but has no sign
723 nor any arithmetic operations.
724
725 <ProgramListing>
726 type Word#      -- Same size/etc as Int# but *unsigned*
727 type Addr#      -- A pointer from outside the "Haskell world" (from C, probably);
728                 -- described under "arrays"
729 </ProgramListing>
730
731 <IndexTerm><Primary><literal>Word&num;</literal></Primary></IndexTerm>
732 <IndexTerm><Primary><literal>Addr&num;</literal></Primary></IndexTerm>
733 </Para>
734
735 <Para>
736 <Literal>Word&num;</Literal>s and <Literal>Addr&num;</Literal>s have
737 the usual comparison operations.  Other
738 unboxed-<Literal>Word</Literal> ops (bit-twiddling and coercions):
739 </Para>
740
741 <Para>
742
743 <ProgramListing>
744 {gt,ge,eq,ne,lt,le}Word# :: Word# -> Word# -> Bool
745
746 and#, or#, xor# :: Word# -> Word# -> Word#
747         -- standard bit ops.
748
749 quotWord#, remWord# :: Word# -> Word# -> Word#
750         -- word (i.e. unsigned) versions are different from int
751         -- versions, so we have to provide these explicitly.
752
753 not# :: Word# -> Word#
754
755 shiftL#, shiftRL# :: Word# -> Int# -> Word#
756         -- shift left, right logical
757
758 int2Word#       :: Int#  -> Word# -- just a cast, really
759 word2Int#       :: Word# -> Int#
760 </ProgramListing>
761
762 <IndexTerm><Primary>bit operations, Word and Addr</Primary></IndexTerm>
763 <IndexTerm><Primary><literal>gtWord&num;</literal></Primary></IndexTerm>
764 <IndexTerm><Primary><literal>geWord&num;</literal></Primary></IndexTerm>
765 <IndexTerm><Primary><literal>eqWord&num;</literal></Primary></IndexTerm>
766 <IndexTerm><Primary><literal>neWord&num;</literal></Primary></IndexTerm>
767 <IndexTerm><Primary><literal>ltWord&num;</literal></Primary></IndexTerm>
768 <IndexTerm><Primary><literal>leWord&num;</literal></Primary></IndexTerm>
769 <IndexTerm><Primary><literal>and&num;</literal></Primary></IndexTerm>
770 <IndexTerm><Primary><literal>or&num;</literal></Primary></IndexTerm>
771 <IndexTerm><Primary><literal>xor&num;</literal></Primary></IndexTerm>
772 <IndexTerm><Primary><literal>not&num;</literal></Primary></IndexTerm>
773 <IndexTerm><Primary><literal>quotWord&num;</literal></Primary></IndexTerm>
774 <IndexTerm><Primary><literal>remWord&num;</literal></Primary></IndexTerm>
775 <IndexTerm><Primary><literal>shiftL&num;</literal></Primary></IndexTerm>
776 <IndexTerm><Primary><literal>shiftRA&num;</literal></Primary></IndexTerm>
777 <IndexTerm><Primary><literal>shiftRL&num;</literal></Primary></IndexTerm>
778 <IndexTerm><Primary><literal>int2Word&num;</literal></Primary></IndexTerm>
779 <IndexTerm><Primary><literal>word2Int&num;</literal></Primary></IndexTerm>
780 </Para>
781
782 <Para>
783 Unboxed-<Literal>Addr</Literal> ops (C casts, really):
784
785 <ProgramListing>
786 {gt,ge,eq,ne,lt,le}Addr# :: Addr# -> Addr# -> Bool
787
788 int2Addr#       :: Int#  -> Addr#
789 addr2Int#       :: Addr# -> Int#
790 addr2Integer#   :: Addr# -> (# Int#, ByteArray# #)
791 </ProgramListing>
792
793 <IndexTerm><Primary><literal>gtAddr&num;</literal></Primary></IndexTerm>
794 <IndexTerm><Primary><literal>geAddr&num;</literal></Primary></IndexTerm>
795 <IndexTerm><Primary><literal>eqAddr&num;</literal></Primary></IndexTerm>
796 <IndexTerm><Primary><literal>neAddr&num;</literal></Primary></IndexTerm>
797 <IndexTerm><Primary><literal>ltAddr&num;</literal></Primary></IndexTerm>
798 <IndexTerm><Primary><literal>leAddr&num;</literal></Primary></IndexTerm>
799 <IndexTerm><Primary><literal>int2Addr&num;</literal></Primary></IndexTerm>
800 <IndexTerm><Primary><literal>addr2Int&num;</literal></Primary></IndexTerm>
801 <IndexTerm><Primary><literal>addr2Integer&num;</literal></Primary></IndexTerm>
802 </Para>
803
804 <Para>
805 The casts between <Literal>Int&num;</Literal>,
806 <Literal>Word&num;</Literal> and <Literal>Addr&num;</Literal>
807 correspond to null operations at the machine level, but are required
808 to keep the Haskell type checker happy.
809 </Para>
810
811 <Para>
812 Operations for indexing off of C pointers
813 (<Literal>Addr&num;</Literal>s) to snatch values are listed under
814 &ldquo;arrays&rdquo;.
815 </Para>
816
817 </Sect2>
818
819 <Sect2>
820 <Title>Arrays</Title>
821
822 <Para>
823 <IndexTerm><Primary>arrays, primitive</Primary></IndexTerm>
824 </Para>
825
826 <Para>
827 The type <Literal>Array&num; elt</Literal> is the type of primitive,
828 unpointed arrays of values of type <Literal>elt</Literal>.
829 </Para>
830
831 <Para>
832
833 <ProgramListing>
834 type Array# elt
835 </ProgramListing>
836
837 <IndexTerm><Primary><literal>Array&num;</literal></Primary></IndexTerm>
838 </Para>
839
840 <Para>
841 <Literal>Array&num;</Literal> is more primitive than a Haskell
842 array&mdash;indeed, the Haskell <Literal>Array</Literal> interface is
843 implemented using <Literal>Array&num;</Literal>&mdash;in that an
844 <Literal>Array&num;</Literal> is indexed only by
845 <Literal>Int&num;</Literal>s, starting at zero.  It is also more
846 primitive by virtue of being unboxed.  That doesn't mean that it isn't
847 a heap-allocated object&mdash;of course, it is.  Rather, being unboxed
848 means that it is represented by a pointer to the array itself, and not
849 to a thunk which will evaluate to the array (or to bottom).  The
850 components of an <Literal>Array&num;</Literal> are themselves boxed.
851 </Para>
852
853 <Para>
854 The type <Literal>ByteArray&num;</Literal> is similar to
855 <Literal>Array&num;</Literal>, except that it contains just a string
856 of (non-pointer) bytes.
857 </Para>
858
859 <Para>
860
861 <ProgramListing>
862 type ByteArray#
863 </ProgramListing>
864
865 <IndexTerm><Primary><literal>ByteArray&num;</literal></Primary></IndexTerm>
866 </Para>
867
868 <Para>
869 Arrays of these types are useful when a Haskell program wishes to
870 construct a value to pass to a C procedure. It is also possible to use
871 them to build (say) arrays of unboxed characters for internal use in a
872 Haskell program.  Given these uses, <Literal>ByteArray&num;</Literal>
873 is deliberately a bit vague about the type of its components.
874 Operations are provided to extract values of type
875 <Literal>Char&num;</Literal>, <Literal>Int&num;</Literal>,
876 <Literal>Float&num;</Literal>, <Literal>Double&num;</Literal>, and
877 <Literal>Addr&num;</Literal> from arbitrary offsets within a
878 <Literal>ByteArray&num;</Literal>.  (For type
879 <Literal>Foo&num;</Literal>, the $i$th offset gets you the $i$th
880 <Literal>Foo&num;</Literal>, not the <Literal>Foo&num;</Literal> at
881 byte-position $i$.  Mumble.)  (If you want a
882 <Literal>Word&num;</Literal>, grab an <Literal>Int&num;</Literal>,
883 then coerce it.)
884 </Para>
885
886 <Para>
887 Lastly, we have static byte-arrays, of type
888 <Literal>Addr&num;</Literal> &lsqb;mentioned previously].  (Remember
889 the duality between arrays and pointers in C.)  Arrays of this types
890 are represented by a pointer to an array in the world outside Haskell,
891 so this pointer is not followed by the garbage collector.  In other
892 respects they are just like <Literal>ByteArray&num;</Literal>.  They
893 are only needed in order to pass values from C to Haskell.
894 </Para>
895
896 </Sect2>
897
898 <Sect2>
899 <Title>Reading and writing</Title>
900
901 <Para>
902 Primitive arrays are linear, and indexed starting at zero.
903 </Para>
904
905 <Para>
906 The size and indices of a <Literal>ByteArray&num;</Literal>, <Literal>Addr&num;</Literal>, and
907 <Literal>MutableByteArray&num;</Literal> are all in bytes.  It's up to the program to
908 calculate the correct byte offset from the start of the array.  This
909 allows a <Literal>ByteArray&num;</Literal> to contain a mixture of values of different
910 type, which is often needed when preparing data for and unpicking
911 results from C.  (Umm&hellip;not true of indices&hellip;WDP 95/09)
912 </Para>
913
914 <Para>
915 <Emphasis>Should we provide some <Literal>sizeOfDouble&num;</Literal> constants?</Emphasis>
916 </Para>
917
918 <Para>
919 Out-of-range errors on indexing should be caught by the code which
920 uses the primitive operation; the primitive operations themselves do
921 <Emphasis>not</Emphasis> check for out-of-range indexes. The intention is that the
922 primitive ops compile to one machine instruction or thereabouts.
923 </Para>
924
925 <Para>
926 We use the terms &ldquo;reading&rdquo; and &ldquo;writing&rdquo; to refer to accessing
927 <Emphasis>mutable</Emphasis> arrays (see <XRef LinkEnd="sect-mutable">), and
928 &ldquo;indexing&rdquo; to refer to reading a value from an <Emphasis>immutable</Emphasis>
929 array.
930 </Para>
931
932 <Para>
933 Immutable byte arrays are straightforward to index (all indices in bytes):
934
935 <ProgramListing>
936 indexCharArray#   :: ByteArray# -> Int# -> Char#
937 indexIntArray#    :: ByteArray# -> Int# -> Int#
938 indexAddrArray#   :: ByteArray# -> Int# -> Addr#
939 indexFloatArray#  :: ByteArray# -> Int# -> Float#
940 indexDoubleArray# :: ByteArray# -> Int# -> Double#
941
942 indexCharOffAddr#   :: Addr# -> Int# -> Char#
943 indexIntOffAddr#    :: Addr# -> Int# -> Int#
944 indexFloatOffAddr#  :: Addr# -> Int# -> Float#
945 indexDoubleOffAddr# :: Addr# -> Int# -> Double#
946 indexAddrOffAddr#   :: Addr# -> Int# -> Addr#
947  -- Get an Addr# from an Addr# offset
948 </ProgramListing>
949
950 <IndexTerm><Primary><literal>indexCharArray&num;</literal></Primary></IndexTerm>
951 <IndexTerm><Primary><literal>indexIntArray&num;</literal></Primary></IndexTerm>
952 <IndexTerm><Primary><literal>indexAddrArray&num;</literal></Primary></IndexTerm>
953 <IndexTerm><Primary><literal>indexFloatArray&num;</literal></Primary></IndexTerm>
954 <IndexTerm><Primary><literal>indexDoubleArray&num;</literal></Primary></IndexTerm>
955 <IndexTerm><Primary><literal>indexCharOffAddr&num;</literal></Primary></IndexTerm>
956 <IndexTerm><Primary><literal>indexIntOffAddr&num;</literal></Primary></IndexTerm>
957 <IndexTerm><Primary><literal>indexFloatOffAddr&num;</literal></Primary></IndexTerm>
958 <IndexTerm><Primary><literal>indexDoubleOffAddr&num;</literal></Primary></IndexTerm>
959 <IndexTerm><Primary><literal>indexAddrOffAddr&num;</literal></Primary></IndexTerm>
960 </Para>
961
962 <Para>
963 The last of these, <Function>indexAddrOffAddr&num;</Function>, extracts an <Literal>Addr&num;</Literal> using an offset
964 from another <Literal>Addr&num;</Literal>, thereby providing the ability to follow a chain of
965 C pointers.
966 </Para>
967
968 <Para>
969 Something a bit more interesting goes on when indexing arrays of boxed
970 objects, because the result is simply the boxed object. So presumably
971 it should be entered&mdash;we never usually return an unevaluated
972 object!  This is a pain: primitive ops aren't supposed to do
973 complicated things like enter objects.  The current solution is to
974 return a single element unboxed tuple (see <XRef LinkEnd="unboxed-tuples">).
975 </Para>
976
977 <Para>
978
979 <ProgramListing>
980 indexArray#       :: Array# elt -> Int# -> (# elt #)
981 </ProgramListing>
982
983 <IndexTerm><Primary><literal>indexArray&num;</literal></Primary></IndexTerm>
984 </Para>
985
986 </Sect2>
987
988 <Sect2>
989 <Title>The state type</Title>
990
991 <Para>
992 <IndexTerm><Primary><literal>state, primitive type</literal></Primary></IndexTerm>
993 <IndexTerm><Primary><literal>State&num;</literal></Primary></IndexTerm>
994 </Para>
995
996 <Para>
997 The primitive type <Literal>State&num;</Literal> represents the state of a state
998 transformer.  It is parameterised on the desired type of state, which
999 serves to keep states from distinct threads distinct from one another.
1000 But the <Emphasis>only</Emphasis> effect of this parameterisation is in the type
1001 system: all values of type <Literal>State&num;</Literal> are represented in the same way.
1002 Indeed, they are all represented by nothing at all!  The code
1003 generator &ldquo;knows&rdquo; to generate no code, and allocate no registers
1004 etc, for primitive states.
1005 </Para>
1006
1007 <Para>
1008
1009 <ProgramListing>
1010 type State# s
1011 </ProgramListing>
1012
1013 </Para>
1014
1015 <Para>
1016 The type <Literal>GHC.RealWorld</Literal> is truly opaque: there are no values defined
1017 of this type, and no operations over it.  It is &ldquo;primitive&rdquo; in that
1018 sense - but it is <Emphasis>not unlifted!</Emphasis> Its only role in life is to be
1019 the type which distinguishes the <Literal>IO</Literal> state transformer.
1020 </Para>
1021
1022 <Para>
1023
1024 <ProgramListing>
1025 data RealWorld
1026 </ProgramListing>
1027
1028 </Para>
1029
1030 </Sect2>
1031
1032 <Sect2>
1033 <Title>State of the world</Title>
1034
1035 <Para>
1036 A single, primitive, value of type <Literal>State&num; RealWorld</Literal> is provided.
1037 </Para>
1038
1039 <Para>
1040
1041 <ProgramListing>
1042 realWorld# :: State# RealWorld
1043 </ProgramListing>
1044
1045 <IndexTerm><Primary>realWorld&num; state object</Primary></IndexTerm>
1046 </Para>
1047
1048 <Para>
1049 (Note: in the compiler, not a <Literal>PrimOp</Literal>; just a mucho magic
1050 <Literal>Id</Literal>. Exported from <Literal>GHC</Literal>, though).
1051 </Para>
1052
1053 </Sect2>
1054
1055 <Sect2 id="sect-mutable">
1056 <Title>Mutable arrays</Title>
1057
1058 <Para>
1059 <IndexTerm><Primary>mutable arrays</Primary></IndexTerm>
1060 <IndexTerm><Primary>arrays, mutable</Primary></IndexTerm>
1061 Corresponding to <Literal>Array&num;</Literal> and <Literal>ByteArray&num;</Literal>, we have the types of
1062 mutable versions of each.  In each case, the representation is a
1063 pointer to a suitable block of (mutable) heap-allocated storage.
1064 </Para>
1065
1066 <Para>
1067
1068 <ProgramListing>
1069 type MutableArray# s elt
1070 type MutableByteArray# s
1071 </ProgramListing>
1072
1073 <IndexTerm><Primary><literal>MutableArray&num;</literal></Primary></IndexTerm>
1074 <IndexTerm><Primary><literal>MutableByteArray&num;</literal></Primary></IndexTerm>
1075 </Para>
1076
1077 <Sect3>
1078 <Title>Allocation</Title>
1079
1080 <Para>
1081 <IndexTerm><Primary>mutable arrays, allocation</Primary></IndexTerm>
1082 <IndexTerm><Primary>arrays, allocation</Primary></IndexTerm>
1083 <IndexTerm><Primary>allocation, of mutable arrays</Primary></IndexTerm>
1084 </Para>
1085
1086 <Para>
1087 Mutable arrays can be allocated. Only pointer-arrays are initialised;
1088 arrays of non-pointers are filled in by &ldquo;user code&rdquo; rather than by
1089 the array-allocation primitive.  Reason: only the pointer case has to
1090 worry about GC striking with a partly-initialised array.
1091 </Para>
1092
1093 <Para>
1094
1095 <ProgramListing>
1096 newArray#       :: Int# -> elt -> State# s -> (# State# s, MutableArray# s elt #)
1097
1098 newCharArray#   :: Int# -> State# s -> (# State# s, MutableByteArray# s elt #)
1099 newIntArray#    :: Int# -> State# s -> (# State# s, MutableByteArray# s elt #)
1100 newAddrArray#   :: Int# -> State# s -> (# State# s, MutableByteArray# s elt #)
1101 newFloatArray#  :: Int# -> State# s -> (# State# s, MutableByteArray# s elt #)
1102 newDoubleArray# :: Int# -> State# s -> (# State# s, MutableByteArray# s elt #)
1103 </ProgramListing>
1104
1105 <IndexTerm><Primary><literal>newArray&num;</literal></Primary></IndexTerm>
1106 <IndexTerm><Primary><literal>newCharArray&num;</literal></Primary></IndexTerm>
1107 <IndexTerm><Primary><literal>newIntArray&num;</literal></Primary></IndexTerm>
1108 <IndexTerm><Primary><literal>newAddrArray&num;</literal></Primary></IndexTerm>
1109 <IndexTerm><Primary><literal>newFloatArray&num;</literal></Primary></IndexTerm>
1110 <IndexTerm><Primary><literal>newDoubleArray&num;</literal></Primary></IndexTerm>
1111 </Para>
1112
1113 <Para>
1114 The size of a <Literal>ByteArray&num;</Literal> is given in bytes.
1115 </Para>
1116
1117 </Sect3>
1118
1119 <Sect3>
1120 <Title>Reading and writing</Title>
1121
1122 <Para>
1123 <IndexTerm><Primary>arrays, reading and writing</Primary></IndexTerm>
1124 </Para>
1125
1126 <Para>
1127
1128 <ProgramListing>
1129 readArray#       :: MutableArray# s elt -> Int# -> State# s -> (# State# s, elt #)
1130 readCharArray#   :: MutableByteArray# s -> Int# -> State# s -> (# State# s, Char# #)
1131 readIntArray#    :: MutableByteArray# s -> Int# -> State# s -> (# State# s, Int# #)
1132 readAddrArray#   :: MutableByteArray# s -> Int# -> State# s -> (# State# s, Addr# #)
1133 readFloatArray#  :: MutableByteArray# s -> Int# -> State# s -> (# State# s, Float# #)
1134 readDoubleArray# :: MutableByteArray# s -> Int# -> State# s -> (# State# s, Double# #)
1135
1136 writeArray#       :: MutableArray# s elt -> Int# -> elt     -> State# s -> State# s
1137 writeCharArray#   :: MutableByteArray# s -> Int# -> Char#   -> State# s -> State# s
1138 writeIntArray#    :: MutableByteArray# s -> Int# -> Int#    -> State# s -> State# s
1139 writeAddrArray#   :: MutableByteArray# s -> Int# -> Addr#   -> State# s -> State# s
1140 writeFloatArray#  :: MutableByteArray# s -> Int# -> Float#  -> State# s -> State# s
1141 writeDoubleArray# :: MutableByteArray# s -> Int# -> Double# -> State# s -> State# s
1142 </ProgramListing>
1143
1144 <IndexTerm><Primary><literal>readArray&num;</literal></Primary></IndexTerm>
1145 <IndexTerm><Primary><literal>readCharArray&num;</literal></Primary></IndexTerm>
1146 <IndexTerm><Primary><literal>readIntArray&num;</literal></Primary></IndexTerm>
1147 <IndexTerm><Primary><literal>readAddrArray&num;</literal></Primary></IndexTerm>
1148 <IndexTerm><Primary><literal>readFloatArray&num;</literal></Primary></IndexTerm>
1149 <IndexTerm><Primary><literal>readDoubleArray&num;</literal></Primary></IndexTerm>
1150 <IndexTerm><Primary><literal>writeArray&num;</literal></Primary></IndexTerm>
1151 <IndexTerm><Primary><literal>writeCharArray&num;</literal></Primary></IndexTerm>
1152 <IndexTerm><Primary><literal>writeIntArray&num;</literal></Primary></IndexTerm>
1153 <IndexTerm><Primary><literal>writeAddrArray&num;</literal></Primary></IndexTerm>
1154 <IndexTerm><Primary><literal>writeFloatArray&num;</literal></Primary></IndexTerm>
1155 <IndexTerm><Primary><literal>writeDoubleArray&num;</literal></Primary></IndexTerm>
1156 </Para>
1157
1158 </Sect3>
1159
1160 <Sect3>
1161 <Title>Equality</Title>
1162
1163 <Para>
1164 <IndexTerm><Primary>arrays, testing for equality</Primary></IndexTerm>
1165 </Para>
1166
1167 <Para>
1168 One can take &ldquo;equality&rdquo; of mutable arrays.  What is compared is the
1169 <Emphasis>name</Emphasis> or reference to the mutable array, not its contents.
1170 </Para>
1171
1172 <Para>
1173
1174 <ProgramListing>
1175 sameMutableArray#     :: MutableArray# s elt -> MutableArray# s elt -> Bool
1176 sameMutableByteArray# :: MutableByteArray# s -> MutableByteArray# s -> Bool
1177 </ProgramListing>
1178
1179 <IndexTerm><Primary><literal>sameMutableArray&num;</literal></Primary></IndexTerm>
1180 <IndexTerm><Primary><literal>sameMutableByteArray&num;</literal></Primary></IndexTerm>
1181 </Para>
1182
1183 </Sect3>
1184
1185 <Sect3>
1186 <Title>Freezing mutable arrays</Title>
1187
1188 <Para>
1189 <IndexTerm><Primary>arrays, freezing mutable</Primary></IndexTerm>
1190 <IndexTerm><Primary>freezing mutable arrays</Primary></IndexTerm>
1191 <IndexTerm><Primary>mutable arrays, freezing</Primary></IndexTerm>
1192 </Para>
1193
1194 <Para>
1195 Only unsafe-freeze has a primitive.  (Safe freeze is done directly in Haskell
1196 by copying the array and then using <Function>unsafeFreeze</Function>.)
1197 </Para>
1198
1199 <Para>
1200
1201 <ProgramListing>
1202 unsafeFreezeArray#     :: MutableArray# s elt -> State# s -> (# State# s, Array# s elt #)
1203 unsafeFreezeByteArray# :: MutableByteArray# s -> State# s -> (# State# s, ByteArray# #)
1204 </ProgramListing>
1205
1206 <IndexTerm><Primary><literal>unsafeFreezeArray&num;</literal></Primary></IndexTerm>
1207 <IndexTerm><Primary><literal>unsafeFreezeByteArray&num;</literal></Primary></IndexTerm>
1208 </Para>
1209
1210 </Sect3>
1211
1212 </Sect2>
1213
1214 <Sect2>
1215 <Title>Synchronizing variables (M-vars)</Title>
1216
1217 <Para>
1218 <IndexTerm><Primary>synchronising variables (M-vars)</Primary></IndexTerm>
1219 <IndexTerm><Primary>M-Vars</Primary></IndexTerm>
1220 </Para>
1221
1222 <Para>
1223 Synchronising variables are the primitive type used to implement
1224 Concurrent Haskell's MVars (see the Concurrent Haskell paper for
1225 the operational behaviour of these operations).
1226 </Para>
1227
1228 <Para>
1229
1230 <ProgramListing>
1231 type MVar# s elt        -- primitive
1232
1233 newMVar#    :: State# s -> (# State# s, MVar# s elt #)
1234 takeMVar#   :: SynchVar# s elt -> State# s -> (# State# s, elt #)
1235 putMVar#    :: SynchVar# s elt -> State# s -> State# s
1236 </ProgramListing>
1237
1238 <IndexTerm><Primary><literal>SynchVar&num;</literal></Primary></IndexTerm>
1239 <IndexTerm><Primary><literal>newSynchVar&num;</literal></Primary></IndexTerm>
1240 <IndexTerm><Primary><literal>takeMVar</literal></Primary></IndexTerm>
1241 <IndexTerm><Primary><literal>putMVar</literal></Primary></IndexTerm>
1242 </Para>
1243
1244 </Sect2>
1245
1246 </Sect1>
1247
1248 <Sect1 id="glasgow-ST-monad">
1249 <Title>Primitive state-transformer monad
1250 </Title>
1251
1252 <Para>
1253 <IndexTerm><Primary>state transformers (Glasgow extensions)</Primary></IndexTerm>
1254 <IndexTerm><Primary>ST monad (Glasgow extension)</Primary></IndexTerm>
1255 </Para>
1256
1257 <Para>
1258 This monad underlies our implementation of arrays, mutable and
1259 immutable, and our implementation of I/O, including &ldquo;C calls&rdquo;.
1260 </Para>
1261
1262 <Para>
1263 The <Literal>ST</Literal> library, which provides access to the
1264 <Function>ST</Function> monad, is described in <xref
1265 linkend="sec-ST">.
1266 </Para>
1267
1268 </Sect1>
1269
1270 <Sect1 id="glasgow-prim-arrays">
1271 <Title>Primitive arrays, mutable and otherwise
1272 </Title>
1273
1274 <Para>
1275 <IndexTerm><Primary>primitive arrays (Glasgow extension)</Primary></IndexTerm>
1276 <IndexTerm><Primary>arrays, primitive (Glasgow extension)</Primary></IndexTerm>
1277 </Para>
1278
1279 <Para>
1280 GHC knows about quite a few flavours of Large Swathes of Bytes.
1281 </Para>
1282
1283 <Para>
1284 First, GHC distinguishes between primitive arrays of (boxed) Haskell
1285 objects (type <Literal>Array&num; obj</Literal>) and primitive arrays of bytes (type
1286 <Literal>ByteArray&num;</Literal>).
1287 </Para>
1288
1289 <Para>
1290 Second, it distinguishes between&hellip;
1291 <VariableList>
1292
1293 <VarListEntry>
1294 <Term>Immutable:</Term>
1295 <ListItem>
1296 <Para>
1297 Arrays that do not change (as with &ldquo;standard&rdquo; Haskell arrays); you
1298 can only read from them.  Obviously, they do not need the care and
1299 attention of the state-transformer monad.
1300 </Para>
1301 </ListItem>
1302 </VarListEntry>
1303 <VarListEntry>
1304 <Term>Mutable:</Term>
1305 <ListItem>
1306 <Para>
1307 Arrays that may be changed or &ldquo;mutated.&rdquo;  All the operations on them
1308 live within the state-transformer monad and the updates happen
1309 <Emphasis>in-place</Emphasis>.
1310 </Para>
1311 </ListItem>
1312 </VarListEntry>
1313 <VarListEntry>
1314 <Term>&ldquo;Static&rdquo; (in C land):</Term>
1315 <ListItem>
1316 <Para>
1317 A C routine may pass an <Literal>Addr&num;</Literal> pointer back into Haskell land.  There
1318 are then primitive operations with which you may merrily grab values
1319 over in C land, by indexing off the &ldquo;static&rdquo; pointer.
1320 </Para>
1321 </ListItem>
1322 </VarListEntry>
1323 <VarListEntry>
1324 <Term>&ldquo;Stable&rdquo; pointers:</Term>
1325 <ListItem>
1326 <Para>
1327 If, for some reason, you wish to hand a Haskell pointer (i.e.,
1328 <Emphasis>not</Emphasis> an unboxed value) to a C routine, you first make the
1329 pointer &ldquo;stable,&rdquo; so that the garbage collector won't forget that it
1330 exists.  That is, GHC provides a safe way to pass Haskell pointers to
1331 C.
1332 </Para>
1333
1334 <Para>
1335 Please see <XRef LinkEnd="sec-stable-pointers"> for more details.
1336 </Para>
1337 </ListItem>
1338 </VarListEntry>
1339 <VarListEntry>
1340 <Term>&ldquo;Foreign objects&rdquo;:</Term>
1341 <ListItem>
1342 <Para>
1343 A &ldquo;foreign object&rdquo; is a safe way to pass an external object (a
1344 C-allocated pointer, say) to Haskell and have Haskell do the Right
1345 Thing when it no longer references the object.  So, for example, C
1346 could pass a large bitmap over to Haskell and say &ldquo;please free this
1347 memory when you're done with it.&rdquo;
1348 </Para>
1349
1350 <Para>
1351 Please see <XRef LinkEnd="sec-ForeignObj"> for more details.
1352 </Para>
1353 </ListItem>
1354 </VarListEntry>
1355 </VariableList>
1356 </Para>
1357
1358 <Para>
1359 The libraries documentatation gives more details on all these
1360 &ldquo;primitive array&rdquo; types and the operations on them.
1361 </Para>
1362
1363 </Sect1>
1364
1365
1366 <Sect1 id="pattern-guards">
1367 <Title>Pattern guards</Title>
1368
1369 <Para>
1370 <IndexTerm><Primary>Pattern guards (Glasgow extension)</Primary></IndexTerm>
1371 The discussion that follows is an abbreviated version of Simon Peyton Jones's original <ULink URL="http://research.microsoft.com/~simonpj/Haskell/guards.html">proposal</ULink>. (Note that the proposal was written before pattern guards were implemented, so refers to them as unimplemented.)
1372 </Para>
1373
1374 <Para>
1375 Suppose we have an abstract data type of finite maps, with a
1376 lookup operation:
1377
1378 <ProgramListing>
1379 lookup :: FiniteMap -> Int -> Maybe Int
1380 </ProgramListing>
1381
1382 The lookup returns <Function>Nothing</Function> if the supplied key is not in the domain of the mapping, and <Function>(Just v)</Function> otherwise,
1383 where <VarName>v</VarName> is the value that the key maps to.  Now consider the following definition:
1384 </Para>
1385
1386 <ProgramListing>
1387 clunky env var1 var2 | ok1 && ok2 = val1 + val2
1388 | otherwise  = var1 + var2
1389 where
1390   m1 = lookup env var1
1391   m2 = lookup env var2
1392   ok1 = maybeToBool m1
1393   ok2 = maybeToBool m2
1394   val1 = expectJust m1
1395   val2 = expectJust m2
1396 </ProgramListing>
1397
1398 <Para>
1399 The auxiliary functions are 
1400 </Para>
1401
1402 <ProgramListing>
1403 maybeToBool :: Maybe a -&gt; Bool
1404 maybeToBool (Just x) = True
1405 maybeToBool Nothing  = False
1406
1407 expectJust :: Maybe a -&gt; a
1408 expectJust (Just x) = x
1409 expectJust Nothing  = error "Unexpected Nothing"
1410 </ProgramListing>
1411
1412 <Para>
1413 What is <Function>clunky</Function> doing? The guard <Literal>ok1 &&
1414 ok2</Literal> checks that both lookups succeed, using
1415 <Function>maybeToBool</Function> to convert the <Function>Maybe</Function>
1416 types to booleans. The (lazily evaluated) <Function>expectJust</Function>
1417 calls extract the values from the results of the lookups, and binds the
1418 returned values to <VarName>val1</VarName> and <VarName>val2</VarName>
1419 respectively.  If either lookup fails, then clunky takes the
1420 <Literal>otherwise</Literal> case and returns the sum of its arguments.
1421 </Para>
1422
1423 <Para>
1424 This is certainly legal Haskell, but it is a tremendously verbose and
1425 un-obvious way to achieve the desired effect.  Arguably, a more direct way
1426 to write clunky would be to use case expressions:
1427 </Para>
1428
1429 <ProgramListing>
1430 clunky env var1 var1 = case lookup env var1 of
1431   Nothing -&gt; fail
1432   Just val1 -&gt; case lookup env var2 of
1433     Nothing -&gt; fail
1434     Just val2 -&gt; val1 + val2
1435 where
1436   fail = val1 + val2
1437 </ProgramListing>
1438
1439 <Para>
1440 This is a bit shorter, but hardly better.  Of course, we can rewrite any set
1441 of pattern-matching, guarded equations as case expressions; that is
1442 precisely what the compiler does when compiling equations! The reason that
1443 Haskell provides guarded equations is because they allow us to write down
1444 the cases we want to consider, one at a time, independently of each other. 
1445 This structure is hidden in the case version.  Two of the right-hand sides
1446 are really the same (<Function>fail</Function>), and the whole expression
1447 tends to become more and more indented. 
1448 </Para>
1449
1450 <Para>
1451 Here is how I would write clunky:
1452 </Para>
1453
1454 <ProgramListing>
1455 clunky env var1 var1
1456   | Just val1 &lt;- lookup env var1
1457   , Just val2 &lt;- lookup env var2
1458   = val1 + val2
1459 ...other equations for clunky...
1460 </ProgramListing>
1461
1462 <Para>
1463 The semantics should be clear enough.  The qualifers are matched in order. 
1464 For a <Literal>&lt;-</Literal> qualifier, which I call a pattern guard, the
1465 right hand side is evaluated and matched against the pattern on the left. 
1466 If the match fails then the whole guard fails and the next equation is
1467 tried.  If it succeeds, then the appropriate binding takes place, and the
1468 next qualifier is matched, in the augmented environment.  Unlike list
1469 comprehensions, however, the type of the expression to the right of the
1470 <Literal>&lt;-</Literal> is the same as the type of the pattern to its
1471 left.  The bindings introduced by pattern guards scope over all the
1472 remaining guard qualifiers, and over the right hand side of the equation.
1473 </Para>
1474
1475 <Para>
1476 Just as with list comprehensions, boolean expressions can be freely mixed
1477 with among the pattern guards.  For example:
1478 </Para>
1479
1480 <ProgramListing>
1481 f x | [y] <- x
1482     , y > 3
1483     , Just z <- h y
1484     = ...
1485 </ProgramListing>
1486
1487 <Para>
1488 Haskell's current guards therefore emerge as a special case, in which the
1489 qualifier list has just one element, a boolean expression.
1490 </Para>
1491 </Sect1>
1492
1493   <sect1 id="sec-ffi">
1494     <title>The foreign interface</title>
1495
1496     <para>The foreign interface consists of the following components:</para>
1497
1498     <itemizedlist>
1499       <listitem>
1500         <para>The Foreign Function Interface language specification
1501         (included in this manual, in <xref linkend="ffi">).</para>
1502       </listitem>
1503
1504       <listitem>
1505         <para>The <literal>Foreign</literal> module (see <xref
1506         linkend="sec-Foreign">) collects together several interfaces
1507         which are useful in specifying foreign language
1508         interfaces, including the following:</para>
1509
1510         <itemizedlist>
1511           <listitem>
1512             <para>The <literal>ForeignObj</literal> module (see <xref
1513             linkend="sec-ForeignObj">), for managing pointers from
1514             Haskell into the outside world.</para>
1515           </listitem>
1516       
1517           <listitem>
1518             <para>The <literal>StablePtr</literal> module (see <xref
1519             linkend="sec-stable-pointers">), for managing pointers
1520             into Haskell from the outside world.</para>
1521           </listitem>
1522       
1523           <listitem>
1524             <para>The <literal>CTypes</literal> module (see <xref
1525             linkend="sec-CTypes">) gives Haskell equivalents for the
1526             standard C datatypes, for use in making Haskell bindings
1527             to existing C libraries.</para>
1528           </listitem>
1529       
1530           <listitem>
1531             <para>The <literal>CTypesISO</literal> module (see <xref
1532             linkend="sec-CTypesISO">) gives Haskell equivalents for C
1533             types defined by the ISO C standard.</para>
1534           </listitem>
1535       
1536           <listitem>
1537             <para>The <literal>Storable</literal> library, for
1538             primitive marshalling of data types between Haskell and
1539             the foreign language.</para>
1540           </listitem>
1541         </itemizedlist>
1542
1543       </listitem>
1544     </itemizedlist>
1545
1546 <para>The following sections also give some hints and tips on the use
1547 of the foreign function interface in GHC.</para>
1548
1549 <Sect2 id="glasgow-foreign-headers">
1550 <Title>Using function headers
1551 </Title>
1552
1553 <Para>
1554 <IndexTerm><Primary>C calls, function headers</Primary></IndexTerm>
1555 </Para>
1556
1557 <Para>
1558 When generating C (using the <Option>-fvia-C</Option> directive), one can assist the
1559 C compiler in detecting type errors by using the <Command>-&num;include</Command> directive
1560 to provide <Filename>.h</Filename> files containing function headers.
1561 </Para>
1562
1563 <Para>
1564 For example,
1565 </Para>
1566
1567 <Para>
1568
1569 <ProgramListing>
1570 #include "HsFFI.h"
1571
1572 void         initialiseEFS (HsInt size);
1573 HsInt        terminateEFS (void);
1574 HsForeignObj emptyEFS(void);
1575 HsForeignObj updateEFS (HsForeignObj a, HsInt i, HsInt x);
1576 HsInt        lookupEFS (HsForeignObj a, HsInt i);
1577 </ProgramListing>
1578 </Para>
1579
1580       <para>The types <literal>HsInt</literal>,
1581       <literal>HsForeignObj</literal> etc. are described in <xref
1582       linkend="sec-mapping-table">.</Para>
1583
1584       <Para>Note that this approach is only
1585       <Emphasis>essential</Emphasis> for returning
1586       <Literal>float</Literal>s (or if <Literal>sizeof(int) !=
1587       sizeof(int *)</Literal> on your architecture) but is a Good
1588       Thing for anyone who cares about writing solid code.  You're
1589       crazy not to do it.</Para>
1590
1591 </Sect2>
1592
1593 </Sect1>
1594
1595 <Sect1 id="multi-param-type-classes">
1596 <Title>Multi-parameter type classes
1597 </Title>
1598
1599 <Para>
1600 This section documents GHC's implementation of multi-parameter type
1601 classes.  There's lots of background in the paper <ULink
1602 URL="http://research.microsoft.com/~simonpj/multi.ps.gz" >Type
1603 classes: exploring the design space</ULink > (Simon Peyton Jones, Mark
1604 Jones, Erik Meijer).
1605 </Para>
1606
1607 <Para>
1608 I'd like to thank people who reported shorcomings in the GHC 3.02
1609 implementation.  Our default decisions were all conservative ones, and
1610 the experience of these heroic pioneers has given useful concrete
1611 examples to support several generalisations.  (These appear below as
1612 design choices not implemented in 3.02.)
1613 </Para>
1614
1615 <Para>
1616 I've discussed these notes with Mark Jones, and I believe that Hugs
1617 will migrate towards the same design choices as I outline here.
1618 Thanks to him, and to many others who have offered very useful
1619 feedback.
1620 </Para>
1621
1622 <Sect2>
1623 <Title>Types</Title>
1624
1625 <Para>
1626 There are the following restrictions on the form of a qualified
1627 type:
1628 </Para>
1629
1630 <Para>
1631
1632 <ProgramListing>
1633   forall tv1..tvn (c1, ...,cn) => type
1634 </ProgramListing>
1635
1636 </Para>
1637
1638 <Para>
1639 (Here, I write the "foralls" explicitly, although the Haskell source
1640 language omits them; in Haskell 1.4, all the free type variables of an
1641 explicit source-language type signature are universally quantified,
1642 except for the class type variables in a class declaration.  However,
1643 in GHC, you can give the foralls if you want.  See <XRef LinkEnd="universal-quantification">).
1644 </Para>
1645
1646 <Para>
1647
1648 <OrderedList>
1649 <ListItem>
1650
1651 <Para>
1652  <Emphasis>Each universally quantified type variable
1653 <Literal>tvi</Literal> must be mentioned (i.e. appear free) in <Literal>type</Literal></Emphasis>.
1654
1655 The reason for this is that a value with a type that does not obey
1656 this restriction could not be used without introducing
1657 ambiguity. Here, for example, is an illegal type:
1658
1659
1660 <ProgramListing>
1661   forall a. Eq a => Int
1662 </ProgramListing>
1663
1664
1665 When a value with this type was used, the constraint <Literal>Eq tv</Literal>
1666 would be introduced where <Literal>tv</Literal> is a fresh type variable, and
1667 (in the dictionary-translation implementation) the value would be
1668 applied to a dictionary for <Literal>Eq tv</Literal>.  The difficulty is that we
1669 can never know which instance of <Literal>Eq</Literal> to use because we never
1670 get any more information about <Literal>tv</Literal>.
1671
1672 </Para>
1673 </ListItem>
1674 <ListItem>
1675
1676 <Para>
1677  <Emphasis>Every constraint <Literal>ci</Literal> must mention at least one of the
1678 universally quantified type variables <Literal>tvi</Literal></Emphasis>.
1679
1680 For example, this type is OK because <Literal>C a b</Literal> mentions the
1681 universally quantified type variable <Literal>b</Literal>:
1682
1683
1684 <ProgramListing>
1685   forall a. C a b => burble
1686 </ProgramListing>
1687
1688
1689 The next type is illegal because the constraint <Literal>Eq b</Literal> does not
1690 mention <Literal>a</Literal>:
1691
1692
1693 <ProgramListing>
1694   forall a. Eq b => burble
1695 </ProgramListing>
1696
1697
1698 The reason for this restriction is milder than the other one.  The
1699 excluded types are never useful or necessary (because the offending
1700 context doesn't need to be witnessed at this point; it can be floated
1701 out).  Furthermore, floating them out increases sharing. Lastly,
1702 excluding them is a conservative choice; it leaves a patch of
1703 territory free in case we need it later.
1704
1705 </Para>
1706 </ListItem>
1707
1708 </OrderedList>
1709
1710 </Para>
1711
1712 <Para>
1713 These restrictions apply to all types, whether declared in a type signature
1714 or inferred.
1715 </Para>
1716
1717 <Para>
1718 Unlike Haskell 1.4, constraints in types do <Emphasis>not</Emphasis> have to be of
1719 the form <Emphasis>(class type-variables)</Emphasis>.  Thus, these type signatures
1720 are perfectly OK
1721 </Para>
1722
1723 <Para>
1724
1725 <ProgramListing>
1726   f :: Eq (m a) => [m a] -> [m a]
1727   g :: Eq [a] => ...
1728 </ProgramListing>
1729
1730 </Para>
1731
1732 <Para>
1733 This choice recovers principal types, a property that Haskell 1.4 does not have.
1734 </Para>
1735
1736 </Sect2>
1737
1738 <Sect2>
1739 <Title>Class declarations</Title>
1740
1741 <Para>
1742
1743 <OrderedList>
1744 <ListItem>
1745
1746 <Para>
1747  <Emphasis>Multi-parameter type classes are permitted</Emphasis>. For example:
1748
1749
1750 <ProgramListing>
1751   class Collection c a where
1752     union :: c a -> c a -> c a
1753     ...etc.
1754 </ProgramListing>
1755
1756
1757
1758 </Para>
1759 </ListItem>
1760 <ListItem>
1761
1762 <Para>
1763  <Emphasis>The class hierarchy must be acyclic</Emphasis>.  However, the definition
1764 of "acyclic" involves only the superclass relationships.  For example,
1765 this is OK:
1766
1767
1768 <ProgramListing>
1769   class C a where {
1770     op :: D b => a -> b -> b
1771   }
1772
1773   class C a => D a where { ... }
1774 </ProgramListing>
1775
1776
1777 Here, <Literal>C</Literal> is a superclass of <Literal>D</Literal>, but it's OK for a
1778 class operation <Literal>op</Literal> of <Literal>C</Literal> to mention <Literal>D</Literal>.  (It
1779 would not be OK for <Literal>D</Literal> to be a superclass of <Literal>C</Literal>.)
1780
1781 </Para>
1782 </ListItem>
1783 <ListItem>
1784
1785 <Para>
1786  <Emphasis>There are no restrictions on the context in a class declaration
1787 (which introduces superclasses), except that the class hierarchy must
1788 be acyclic</Emphasis>.  So these class declarations are OK:
1789
1790
1791 <ProgramListing>
1792   class Functor (m k) => FiniteMap m k where
1793     ...
1794
1795   class (Monad m, Monad (t m)) => Transform t m where
1796     lift :: m a -> (t m) a
1797 </ProgramListing>
1798
1799
1800 </Para>
1801 </ListItem>
1802 <ListItem>
1803
1804 <Para>
1805  <Emphasis>In the signature of a class operation, every constraint
1806 must mention at least one type variable that is not a class type
1807 variable</Emphasis>.
1808
1809 Thus:
1810
1811
1812 <ProgramListing>
1813   class Collection c a where
1814     mapC :: Collection c b => (a->b) -> c a -> c b
1815 </ProgramListing>
1816
1817
1818 is OK because the constraint <Literal>(Collection a b)</Literal> mentions
1819 <Literal>b</Literal>, even though it also mentions the class variable
1820 <Literal>a</Literal>.  On the other hand:
1821
1822
1823 <ProgramListing>
1824   class C a where
1825     op :: Eq a => (a,b) -> (a,b)
1826 </ProgramListing>
1827
1828
1829 is not OK because the constraint <Literal>(Eq a)</Literal> mentions on the class
1830 type variable <Literal>a</Literal>, but not <Literal>b</Literal>.  However, any such
1831 example is easily fixed by moving the offending context up to the
1832 superclass context:
1833
1834
1835 <ProgramListing>
1836   class Eq a => C a where
1837     op ::(a,b) -> (a,b)
1838 </ProgramListing>
1839
1840
1841 A yet more relaxed rule would allow the context of a class-op signature
1842 to mention only class type variables.  However, that conflicts with
1843 Rule 1(b) for types above.
1844
1845 </Para>
1846 </ListItem>
1847 <ListItem>
1848
1849 <Para>
1850  <Emphasis>The type of each class operation must mention <Emphasis>all</Emphasis> of
1851 the class type variables</Emphasis>.  For example:
1852
1853
1854 <ProgramListing>
1855   class Coll s a where
1856     empty  :: s
1857     insert :: s -> a -> s
1858 </ProgramListing>
1859
1860
1861 is not OK, because the type of <Literal>empty</Literal> doesn't mention
1862 <Literal>a</Literal>.  This rule is a consequence of Rule 1(a), above, for
1863 types, and has the same motivation.
1864
1865 Sometimes, offending class declarations exhibit misunderstandings.  For
1866 example, <Literal>Coll</Literal> might be rewritten
1867
1868
1869 <ProgramListing>
1870   class Coll s a where
1871     empty  :: s a
1872     insert :: s a -> a -> s a
1873 </ProgramListing>
1874
1875
1876 which makes the connection between the type of a collection of
1877 <Literal>a</Literal>'s (namely <Literal>(s a)</Literal>) and the element type <Literal>a</Literal>.
1878 Occasionally this really doesn't work, in which case you can split the
1879 class like this:
1880
1881
1882 <ProgramListing>
1883   class CollE s where
1884     empty  :: s
1885
1886   class CollE s => Coll s a where
1887     insert :: s -> a -> s
1888 </ProgramListing>
1889
1890
1891 </Para>
1892 </ListItem>
1893
1894 </OrderedList>
1895
1896 </Para>
1897
1898 </Sect2>
1899
1900 <Sect2>
1901 <Title>Instance declarations</Title>
1902
1903 <Para>
1904
1905 <OrderedList>
1906 <ListItem>
1907
1908 <Para>
1909  <Emphasis>Instance declarations may not overlap</Emphasis>.  The two instance
1910 declarations
1911
1912
1913 <ProgramListing>
1914   instance context1 => C type1 where ...
1915   instance context2 => C type2 where ...
1916 </ProgramListing>
1917
1918
1919 "overlap" if <Literal>type1</Literal> and <Literal>type2</Literal> unify
1920
1921 However, if you give the command line option
1922 <Option>-fallow-overlapping-instances</Option><IndexTerm><Primary>-fallow-overlapping-instances
1923 option</Primary></IndexTerm> then two overlapping instance declarations are permitted
1924 iff
1925
1926
1927 <ItemizedList>
1928 <ListItem>
1929
1930 <Para>
1931  EITHER <Literal>type1</Literal> and <Literal>type2</Literal> do not unify
1932 </Para>
1933 </ListItem>
1934 <ListItem>
1935
1936 <Para>
1937  OR <Literal>type2</Literal> is a substitution instance of <Literal>type1</Literal>
1938 (but not identical to <Literal>type1</Literal>)
1939 </Para>
1940 </ListItem>
1941 <ListItem>
1942
1943 <Para>
1944  OR vice versa
1945 </Para>
1946 </ListItem>
1947
1948 </ItemizedList>
1949
1950
1951 Notice that these rules
1952
1953
1954 <ItemizedList>
1955 <ListItem>
1956
1957 <Para>
1958  make it clear which instance decl to use
1959 (pick the most specific one that matches)
1960
1961 </Para>
1962 </ListItem>
1963 <ListItem>
1964
1965 <Para>
1966  do not mention the contexts <Literal>context1</Literal>, <Literal>context2</Literal>
1967 Reason: you can pick which instance decl
1968 "matches" based on the type.
1969 </Para>
1970 </ListItem>
1971
1972 </ItemizedList>
1973
1974
1975 Regrettably, GHC doesn't guarantee to detect overlapping instance
1976 declarations if they appear in different modules.  GHC can "see" the
1977 instance declarations in the transitive closure of all the modules
1978 imported by the one being compiled, so it can "see" all instance decls
1979 when it is compiling <Literal>Main</Literal>.  However, it currently chooses not
1980 to look at ones that can't possibly be of use in the module currently
1981 being compiled, in the interests of efficiency.  (Perhaps we should
1982 change that decision, at least for <Literal>Main</Literal>.)
1983
1984 </Para>
1985 </ListItem>
1986 <ListItem>
1987
1988 <Para>
1989  <Emphasis>There are no restrictions on the type in an instance
1990 <Emphasis>head</Emphasis>, except that at least one must not be a type variable</Emphasis>.
1991 The instance "head" is the bit after the "=>" in an instance decl. For
1992 example, these are OK:
1993
1994
1995 <ProgramListing>
1996   instance C Int a where ...
1997
1998   instance D (Int, Int) where ...
1999
2000   instance E [[a]] where ...
2001 </ProgramListing>
2002
2003
2004 Note that instance heads <Emphasis>may</Emphasis> contain repeated type variables.
2005 For example, this is OK:
2006
2007
2008 <ProgramListing>
2009   instance Stateful (ST s) (MutVar s) where ...
2010 </ProgramListing>
2011
2012
2013 The "at least one not a type variable" restriction is to ensure that
2014 context reduction terminates: each reduction step removes one type
2015 constructor.  For example, the following would make the type checker
2016 loop if it wasn't excluded:
2017
2018
2019 <ProgramListing>
2020   instance C a => C a where ...
2021 </ProgramListing>
2022
2023
2024 There are two situations in which the rule is a bit of a pain. First,
2025 if one allows overlapping instance declarations then it's quite
2026 convenient to have a "default instance" declaration that applies if
2027 something more specific does not:
2028
2029
2030 <ProgramListing>
2031   instance C a where
2032     op = ... -- Default
2033 </ProgramListing>
2034
2035
2036 Second, sometimes you might want to use the following to get the
2037 effect of a "class synonym":
2038
2039
2040 <ProgramListing>
2041   class (C1 a, C2 a, C3 a) => C a where { }
2042
2043   instance (C1 a, C2 a, C3 a) => C a where { }
2044 </ProgramListing>
2045
2046
2047 This allows you to write shorter signatures:
2048
2049
2050 <ProgramListing>
2051   f :: C a => ...
2052 </ProgramListing>
2053
2054
2055 instead of
2056
2057
2058 <ProgramListing>
2059   f :: (C1 a, C2 a, C3 a) => ...
2060 </ProgramListing>
2061
2062
2063 I'm on the lookout for a simple rule that preserves decidability while
2064 allowing these idioms.  The experimental flag
2065 <Option>-fallow-undecidable-instances</Option><IndexTerm><Primary>-fallow-undecidable-instances
2066 option</Primary></IndexTerm> lifts this restriction, allowing all the types in an
2067 instance head to be type variables.
2068
2069 </Para>
2070 </ListItem>
2071 <ListItem>
2072
2073 <Para>
2074  <Emphasis>Unlike Haskell 1.4, instance heads may use type
2075 synonyms</Emphasis>.  As always, using a type synonym is just shorthand for
2076 writing the RHS of the type synonym definition.  For example:
2077
2078
2079 <ProgramListing>
2080   type Point = (Int,Int)
2081   instance C Point   where ...
2082   instance C [Point] where ...
2083 </ProgramListing>
2084
2085
2086 is legal.  However, if you added
2087
2088
2089 <ProgramListing>
2090   instance C (Int,Int) where ...
2091 </ProgramListing>
2092
2093
2094 as well, then the compiler will complain about the overlapping
2095 (actually, identical) instance declarations.  As always, type synonyms
2096 must be fully applied.  You cannot, for example, write:
2097
2098
2099 <ProgramListing>
2100   type P a = [[a]]
2101   instance Monad P where ...
2102 </ProgramListing>
2103
2104
2105 This design decision is independent of all the others, and easily
2106 reversed, but it makes sense to me.
2107
2108 </Para>
2109 </ListItem>
2110 <ListItem>
2111
2112 <Para>
2113 <Emphasis>The types in an instance-declaration <Emphasis>context</Emphasis> must all
2114 be type variables</Emphasis>. Thus
2115
2116
2117 <ProgramListing>
2118 instance C a b => Eq (a,b) where ...
2119 </ProgramListing>
2120
2121
2122 is OK, but
2123
2124
2125 <ProgramListing>
2126 instance C Int b => Foo b where ...
2127 </ProgramListing>
2128
2129
2130 is not OK.  Again, the intent here is to make sure that context
2131 reduction terminates.
2132
2133 Voluminous correspondence on the Haskell mailing list has convinced me
2134 that it's worth experimenting with a more liberal rule.  If you use
2135 the flag <Option>-fallow-undecidable-instances</Option> can use arbitrary
2136 types in an instance context.  Termination is ensured by having a
2137 fixed-depth recursion stack.  If you exceed the stack depth you get a
2138 sort of backtrace, and the opportunity to increase the stack depth
2139 with <Option>-fcontext-stack</Option><Emphasis>N</Emphasis>.
2140
2141 </Para>
2142 </ListItem>
2143
2144 </OrderedList>
2145
2146 </Para>
2147
2148 </Sect2>
2149
2150 </Sect1>
2151
2152 <Sect1 id="universal-quantification">
2153 <Title>Explicit universal quantification
2154 </Title>
2155
2156 <Para>
2157 GHC now allows you to write explicitly quantified types.  GHC's
2158 syntax for this now agrees with Hugs's, namely:
2159 </Para>
2160
2161 <Para>
2162
2163 <ProgramListing>
2164         forall a b. (Ord a, Eq  b) => a -> b -> a
2165 </ProgramListing>
2166
2167 </Para>
2168
2169 <Para>
2170 The context is, of course, optional.  You can't use <Literal>forall</Literal> as
2171 a type variable any more!
2172 </Para>
2173
2174 <Para>
2175 Haskell type signatures are implicitly quantified.  The <Literal>forall</Literal>
2176 allows us to say exactly what this means.  For example:
2177 </Para>
2178
2179 <Para>
2180
2181 <ProgramListing>
2182         g :: b -> b
2183 </ProgramListing>
2184
2185 </Para>
2186
2187 <Para>
2188 means this:
2189 </Para>
2190
2191 <Para>
2192
2193 <ProgramListing>
2194         g :: forall b. (b -> b)
2195 </ProgramListing>
2196
2197 </Para>
2198
2199 <Para>
2200 The two are treated identically.
2201 </Para>
2202
2203 <Sect2 id="univ">
2204 <Title>Universally-quantified data type fields
2205 </Title>
2206
2207 <Para>
2208 In a <Literal>data</Literal> or <Literal>newtype</Literal> declaration one can quantify
2209 the types of the constructor arguments.  Here are several examples:
2210 </Para>
2211
2212 <Para>
2213
2214 <ProgramListing>
2215 data T a = T1 (forall b. b -> b -> b) a
2216
2217 data MonadT m = MkMonad { return :: forall a. a -> m a,
2218                           bind   :: forall a b. m a -> (a -> m b) -> m b
2219                         }
2220
2221 newtype Swizzle = MkSwizzle (Ord a => [a] -> [a])
2222 </ProgramListing>
2223
2224 </Para>
2225
2226 <Para>
2227 The constructors now have so-called <Emphasis>rank 2</Emphasis> polymorphic
2228 types, in which there is a for-all in the argument types.:
2229 </Para>
2230
2231 <Para>
2232
2233 <ProgramListing>
2234 T1 :: forall a. (forall b. b -> b -> b) -> a -> T a
2235 MkMonad :: forall m. (forall a. a -> m a)
2236                   -> (forall a b. m a -> (a -> m b) -> m b)
2237                   -> MonadT m
2238 MkSwizzle :: (Ord a => [a] -> [a]) -> Swizzle
2239 </ProgramListing>
2240
2241 </Para>
2242
2243 <Para>
2244 Notice that you don't need to use a <Literal>forall</Literal> if there's an
2245 explicit context.  For example in the first argument of the
2246 constructor <Function>MkSwizzle</Function>, an implicit "<Literal>forall a.</Literal>" is
2247 prefixed to the argument type.  The implicit <Literal>forall</Literal>
2248 quantifies all type variables that are not already in scope, and are
2249 mentioned in the type quantified over.
2250 </Para>
2251
2252 <Para>
2253 As for type signatures, implicit quantification happens for non-overloaded
2254 types too.  So if you write this:
2255
2256 <ProgramListing>
2257   data T a = MkT (Either a b) (b -> b)
2258 </ProgramListing>
2259
2260 it's just as if you had written this:
2261
2262 <ProgramListing>
2263   data T a = MkT (forall b. Either a b) (forall b. b -> b)
2264 </ProgramListing>
2265
2266 That is, since the type variable <Literal>b</Literal> isn't in scope, it's
2267 implicitly universally quantified.  (Arguably, it would be better
2268 to <Emphasis>require</Emphasis> explicit quantification on constructor arguments
2269 where that is what is wanted.  Feedback welcomed.)
2270 </Para>
2271
2272 </Sect2>
2273
2274 <Sect2>
2275 <Title>Construction </Title>
2276
2277 <Para>
2278 You construct values of types <Literal>T1, MonadT, Swizzle</Literal> by applying
2279 the constructor to suitable values, just as usual.  For example,
2280 </Para>
2281
2282 <Para>
2283
2284 <ProgramListing>
2285 (T1 (\xy->x) 3) :: T Int
2286
2287 (MkSwizzle sort)    :: Swizzle
2288 (MkSwizzle reverse) :: Swizzle
2289
2290 (let r x = Just x
2291      b m k = case m of
2292                 Just y -> k y
2293                 Nothing -> Nothing
2294   in
2295   MkMonad r b) :: MonadT Maybe
2296 </ProgramListing>
2297
2298 </Para>
2299
2300 <Para>
2301 The type of the argument can, as usual, be more general than the type
2302 required, as <Literal>(MkSwizzle reverse)</Literal> shows.  (<Function>reverse</Function>
2303 does not need the <Literal>Ord</Literal> constraint.)
2304 </Para>
2305
2306 </Sect2>
2307
2308 <Sect2>
2309 <Title>Pattern matching</Title>
2310
2311 <Para>
2312 When you use pattern matching, the bound variables may now have
2313 polymorphic types.  For example:
2314 </Para>
2315
2316 <Para>
2317
2318 <ProgramListing>
2319         f :: T a -> a -> (a, Char)
2320         f (T1 f k) x = (f k x, f 'c' 'd')
2321
2322         g :: (Ord a, Ord b) => Swizzle -> [a] -> (a -> b) -> [b]
2323         g (MkSwizzle s) xs f = s (map f (s xs))
2324
2325         h :: MonadT m -> [m a] -> m [a]
2326         h m [] = return m []
2327         h m (x:xs) = bind m x           $ \y ->
2328                       bind m (h m xs)   $ \ys ->
2329                       return m (y:ys)
2330 </ProgramListing>
2331
2332 </Para>
2333
2334 <Para>
2335 In the function <Function>h</Function> we use the record selectors <Literal>return</Literal>
2336 and <Literal>bind</Literal> to extract the polymorphic bind and return functions
2337 from the <Literal>MonadT</Literal> data structure, rather than using pattern
2338 matching.
2339 </Para>
2340
2341 <Para>
2342 You cannot pattern-match against an argument that is polymorphic.
2343 For example:
2344
2345 <ProgramListing>
2346         newtype TIM s a = TIM (ST s (Maybe a))
2347
2348         runTIM :: (forall s. TIM s a) -> Maybe a
2349         runTIM (TIM m) = runST m
2350 </ProgramListing>
2351
2352 </Para>
2353
2354 <Para>
2355 Here the pattern-match fails, because you can't pattern-match against
2356 an argument of type <Literal>(forall s. TIM s a)</Literal>.  Instead you
2357 must bind the variable and pattern match in the right hand side:
2358
2359 <ProgramListing>
2360         runTIM :: (forall s. TIM s a) -> Maybe a
2361         runTIM tm = case tm of { TIM m -> runST m }
2362 </ProgramListing>
2363
2364 The <Literal>tm</Literal> on the right hand side is (invisibly) instantiated, like
2365 any polymorphic value at its occurrence site, and now you can pattern-match
2366 against it.
2367 </Para>
2368
2369 </Sect2>
2370
2371 <Sect2>
2372 <Title>The partial-application restriction</Title>
2373
2374 <Para>
2375 There is really only one way in which data structures with polymorphic
2376 components might surprise you: you must not partially apply them.
2377 For example, this is illegal:
2378 </Para>
2379
2380 <Para>
2381
2382 <ProgramListing>
2383         map MkSwizzle [sort, reverse]
2384 </ProgramListing>
2385
2386 </Para>
2387
2388 <Para>
2389 The restriction is this: <Emphasis>every subexpression of the program must
2390 have a type that has no for-alls, except that in a function
2391 application (f e1&hellip;en) the partial applications are not subject to
2392 this rule</Emphasis>.  The restriction makes type inference feasible.
2393 </Para>
2394
2395 <Para>
2396 In the illegal example, the sub-expression <Literal>MkSwizzle</Literal> has the
2397 polymorphic type <Literal>(Ord b => [b] -> [b]) -> Swizzle</Literal> and is not
2398 a sub-expression of an enclosing application.  On the other hand, this
2399 expression is OK:
2400 </Para>
2401
2402 <Para>
2403
2404 <ProgramListing>
2405         map (T1 (\a b -> a)) [1,2,3]
2406 </ProgramListing>
2407
2408 </Para>
2409
2410 <Para>
2411 even though it involves a partial application of <Function>T1</Function>, because
2412 the sub-expression <Literal>T1 (\a b -> a)</Literal> has type <Literal>Int -> T
2413 Int</Literal>.
2414 </Para>
2415
2416 </Sect2>
2417
2418 <Sect2 id="sigs">
2419 <Title>Type signatures
2420 </Title>
2421
2422 <Para>
2423 Once you have data constructors with universally-quantified fields, or
2424 constants such as <Constant>runST</Constant> that have rank-2 types, it isn't long
2425 before you discover that you need more!  Consider:
2426 </Para>
2427
2428 <Para>
2429
2430 <ProgramListing>
2431   mkTs f x y = [T1 f x, T1 f y]
2432 </ProgramListing>
2433
2434 </Para>
2435
2436 <Para>
2437 <Function>mkTs</Function> is a fuction that constructs some values of type
2438 <Literal>T</Literal>, using some pieces passed to it.  The trouble is that since
2439 <Literal>f</Literal> is a function argument, Haskell assumes that it is
2440 monomorphic, so we'll get a type error when applying <Function>T1</Function> to
2441 it.  This is a rather silly example, but the problem really bites in
2442 practice.  Lots of people trip over the fact that you can't make
2443 "wrappers functions" for <Constant>runST</Constant> for exactly the same reason.
2444 In short, it is impossible to build abstractions around functions with
2445 rank-2 types.
2446 </Para>
2447
2448 <Para>
2449 The solution is fairly clear.  We provide the ability to give a rank-2
2450 type signature for <Emphasis>ordinary</Emphasis> functions (not only data
2451 constructors), thus:
2452 </Para>
2453
2454 <Para>
2455
2456 <ProgramListing>
2457   mkTs :: (forall b. b -> b -> b) -> a -> [T a]
2458   mkTs f x y = [T1 f x, T1 f y]
2459 </ProgramListing>
2460
2461 </Para>
2462
2463 <Para>
2464 This type signature tells the compiler to attribute <Literal>f</Literal> with
2465 the polymorphic type <Literal>(forall b. b -> b -> b)</Literal> when type
2466 checking the body of <Function>mkTs</Function>, so now the application of
2467 <Function>T1</Function> is fine.
2468 </Para>
2469
2470 <Para>
2471 There are two restrictions:
2472 </Para>
2473
2474 <Para>
2475
2476 <ItemizedList>
2477 <ListItem>
2478
2479 <Para>
2480  You can only define a rank 2 type, specified by the following
2481 grammar:
2482
2483
2484 <ProgramListing>
2485 rank2type ::= [forall tyvars .] [context =>] funty
2486 funty     ::= ([forall tyvars .] [context =>] ty) -> funty
2487             | ty
2488 ty        ::= ...current Haskell monotype syntax...
2489 </ProgramListing>
2490
2491
2492 Informally, the universal quantification must all be right at the beginning,
2493 or at the top level of a function argument.
2494
2495 </Para>
2496 </ListItem>
2497 <ListItem>
2498
2499 <Para>
2500  There is a restriction on the definition of a function whose
2501 type signature is a rank-2 type: the polymorphic arguments must be
2502 matched on the left hand side of the "<Literal>=</Literal>" sign.  You can't
2503 define <Function>mkTs</Function> like this:
2504
2505
2506 <ProgramListing>
2507 mkTs :: (forall b. b -> b -> b) -> a -> [T a]
2508 mkTs = \ f x y -> [T1 f x, T1 f y]
2509 </ProgramListing>
2510
2511
2512
2513 The same partial-application rule applies to ordinary functions with
2514 rank-2 types as applied to data constructors.
2515
2516 </Para>
2517 </ListItem>
2518
2519 </ItemizedList>
2520
2521 </Para>
2522
2523 </Sect2>
2524
2525
2526 <Sect2 id="hoist">
2527 <Title>Type synonyms and hoisting
2528 </Title>
2529
2530 <Para>
2531 GHC also allows you to write a <Literal>forall</Literal> in a type synonym, thus:
2532 <ProgramListing>
2533   type Discard a = forall b. a -> b -> a
2534
2535   f :: Discard a
2536   f x y = x
2537 </ProgramListing>
2538 However, it is often convenient to use these sort of synonyms at the right hand
2539 end of an arrow, thus:
2540 <ProgramListing>
2541   type Discard a = forall b. a -> b -> a
2542
2543   g :: Int -> Discard Int
2544   g x y z = x+y
2545 </ProgramListing>
2546 Simply expanding the type synonym would give
2547 <ProgramListing>
2548   g :: Int -> (forall b. Int -> b -> Int)
2549 </ProgramListing>
2550 but GHC "hoists" the <Literal>forall</Literal> to give the isomorphic type
2551 <ProgramListing>
2552   g :: forall b. Int -> Int -> b -> Int
2553 </ProgramListing>
2554 In general, the rule is this: <Emphasis>to determine the type specified by any explicit
2555 user-written type (e.g. in a type signature), GHC expands type synonyms and then repeatedly
2556 performs the transformation:</Emphasis>
2557 <ProgramListing>
2558   <Emphasis>type1</Emphasis> -> forall a. <Emphasis>type2</Emphasis>
2559 ==>
2560   forall a. <Emphasis>type1</Emphasis> -> <Emphasis>type2</Emphasis>
2561 </ProgramListing>
2562 (In fact, GHC tries to retain as much synonym information as possible for use in
2563 error messages, but that is a usability issue.)  This rule applies, of course, whether
2564 or not the <Literal>forall</Literal> comes from a synonym. For example, here is another
2565 valid way to write <Literal>g</Literal>'s type signature:
2566 <ProgramListing>
2567   g :: Int -> Int -> forall b. b -> Int
2568 </ProgramListing>
2569 </Para>
2570 </Sect2>
2571
2572 </Sect1>
2573
2574 <Sect1 id="existential-quantification">
2575 <Title>Existentially quantified data constructors
2576 </Title>
2577
2578 <Para>
2579 The idea of using existential quantification in data type declarations
2580 was suggested by Laufer (I believe, thought doubtless someone will
2581 correct me), and implemented in Hope+. It's been in Lennart
2582 Augustsson's <Command>hbc</Command> Haskell compiler for several years, and
2583 proved very useful.  Here's the idea.  Consider the declaration:
2584 </Para>
2585
2586 <Para>
2587
2588 <ProgramListing>
2589   data Foo = forall a. MkFoo a (a -> Bool)
2590            | Nil
2591 </ProgramListing>
2592
2593 </Para>
2594
2595 <Para>
2596 The data type <Literal>Foo</Literal> has two constructors with types:
2597 </Para>
2598
2599 <Para>
2600
2601 <ProgramListing>
2602   MkFoo :: forall a. a -> (a -> Bool) -> Foo
2603   Nil   :: Foo
2604 </ProgramListing>
2605
2606 </Para>
2607
2608 <Para>
2609 Notice that the type variable <Literal>a</Literal> in the type of <Function>MkFoo</Function>
2610 does not appear in the data type itself, which is plain <Literal>Foo</Literal>.
2611 For example, the following expression is fine:
2612 </Para>
2613
2614 <Para>
2615
2616 <ProgramListing>
2617   [MkFoo 3 even, MkFoo 'c' isUpper] :: [Foo]
2618 </ProgramListing>
2619
2620 </Para>
2621
2622 <Para>
2623 Here, <Literal>(MkFoo 3 even)</Literal> packages an integer with a function
2624 <Function>even</Function> that maps an integer to <Literal>Bool</Literal>; and <Function>MkFoo 'c'
2625 isUpper</Function> packages a character with a compatible function.  These
2626 two things are each of type <Literal>Foo</Literal> and can be put in a list.
2627 </Para>
2628
2629 <Para>
2630 What can we do with a value of type <Literal>Foo</Literal>?.  In particular,
2631 what happens when we pattern-match on <Function>MkFoo</Function>?
2632 </Para>
2633
2634 <Para>
2635
2636 <ProgramListing>
2637   f (MkFoo val fn) = ???
2638 </ProgramListing>
2639
2640 </Para>
2641
2642 <Para>
2643 Since all we know about <Literal>val</Literal> and <Function>fn</Function> is that they
2644 are compatible, the only (useful) thing we can do with them is to
2645 apply <Function>fn</Function> to <Literal>val</Literal> to get a boolean.  For example:
2646 </Para>
2647
2648 <Para>
2649
2650 <ProgramListing>
2651   f :: Foo -> Bool
2652   f (MkFoo val fn) = fn val
2653 </ProgramListing>
2654
2655 </Para>
2656
2657 <Para>
2658 What this allows us to do is to package heterogenous values
2659 together with a bunch of functions that manipulate them, and then treat
2660 that collection of packages in a uniform manner.  You can express
2661 quite a bit of object-oriented-like programming this way.
2662 </Para>
2663
2664 <Sect2 id="existential">
2665 <Title>Why existential?
2666 </Title>
2667
2668 <Para>
2669 What has this to do with <Emphasis>existential</Emphasis> quantification?
2670 Simply that <Function>MkFoo</Function> has the (nearly) isomorphic type
2671 </Para>
2672
2673 <Para>
2674
2675 <ProgramListing>
2676   MkFoo :: (exists a . (a, a -> Bool)) -> Foo
2677 </ProgramListing>
2678
2679 </Para>
2680
2681 <Para>
2682 But Haskell programmers can safely think of the ordinary
2683 <Emphasis>universally</Emphasis> quantified type given above, thereby avoiding
2684 adding a new existential quantification construct.
2685 </Para>
2686
2687 </Sect2>
2688
2689 <Sect2>
2690 <Title>Type classes</Title>
2691
2692 <Para>
2693 An easy extension (implemented in <Command>hbc</Command>) is to allow
2694 arbitrary contexts before the constructor.  For example:
2695 </Para>
2696
2697 <Para>
2698
2699 <ProgramListing>
2700 data Baz = forall a. Eq a => Baz1 a a
2701          | forall b. Show b => Baz2 b (b -> b)
2702 </ProgramListing>
2703
2704 </Para>
2705
2706 <Para>
2707 The two constructors have the types you'd expect:
2708 </Para>
2709
2710 <Para>
2711
2712 <ProgramListing>
2713 Baz1 :: forall a. Eq a => a -> a -> Baz
2714 Baz2 :: forall b. Show b => b -> (b -> b) -> Baz
2715 </ProgramListing>
2716
2717 </Para>
2718
2719 <Para>
2720 But when pattern matching on <Function>Baz1</Function> the matched values can be compared
2721 for equality, and when pattern matching on <Function>Baz2</Function> the first matched
2722 value can be converted to a string (as well as applying the function to it).
2723 So this program is legal:
2724 </Para>
2725
2726 <Para>
2727
2728 <ProgramListing>
2729   f :: Baz -> String
2730   f (Baz1 p q) | p == q    = "Yes"
2731                | otherwise = "No"
2732   f (Baz1 v fn)            = show (fn v)
2733 </ProgramListing>
2734
2735 </Para>
2736
2737 <Para>
2738 Operationally, in a dictionary-passing implementation, the
2739 constructors <Function>Baz1</Function> and <Function>Baz2</Function> must store the
2740 dictionaries for <Literal>Eq</Literal> and <Literal>Show</Literal> respectively, and
2741 extract it on pattern matching.
2742 </Para>
2743
2744 <Para>
2745 Notice the way that the syntax fits smoothly with that used for
2746 universal quantification earlier.
2747 </Para>
2748
2749 </Sect2>
2750
2751 <Sect2>
2752 <Title>Restrictions</Title>
2753
2754 <Para>
2755 There are several restrictions on the ways in which existentially-quantified
2756 constructors can be use.
2757 </Para>
2758
2759 <Para>
2760
2761 <ItemizedList>
2762 <ListItem>
2763
2764 <Para>
2765  When pattern matching, each pattern match introduces a new,
2766 distinct, type for each existential type variable.  These types cannot
2767 be unified with any other type, nor can they escape from the scope of
2768 the pattern match.  For example, these fragments are incorrect:
2769
2770
2771 <ProgramListing>
2772 f1 (MkFoo a f) = a
2773 </ProgramListing>
2774
2775
2776 Here, the type bound by <Function>MkFoo</Function> "escapes", because <Literal>a</Literal>
2777 is the result of <Function>f1</Function>.  One way to see why this is wrong is to
2778 ask what type <Function>f1</Function> has:
2779
2780
2781 <ProgramListing>
2782   f1 :: Foo -> a             -- Weird!
2783 </ProgramListing>
2784
2785
2786 What is this "<Literal>a</Literal>" in the result type? Clearly we don't mean
2787 this:
2788
2789
2790 <ProgramListing>
2791   f1 :: forall a. Foo -> a   -- Wrong!
2792 </ProgramListing>
2793
2794
2795 The original program is just plain wrong.  Here's another sort of error
2796
2797
2798 <ProgramListing>
2799   f2 (Baz1 a b) (Baz1 p q) = a==q
2800 </ProgramListing>
2801
2802
2803 It's ok to say <Literal>a==b</Literal> or <Literal>p==q</Literal>, but
2804 <Literal>a==q</Literal> is wrong because it equates the two distinct types arising
2805 from the two <Function>Baz1</Function> constructors.
2806
2807
2808 </Para>
2809 </ListItem>
2810 <ListItem>
2811
2812 <Para>
2813 You can't pattern-match on an existentially quantified
2814 constructor in a <Literal>let</Literal> or <Literal>where</Literal> group of
2815 bindings. So this is illegal:
2816
2817
2818 <ProgramListing>
2819   f3 x = a==b where { Baz1 a b = x }
2820 </ProgramListing>
2821
2822
2823 You can only pattern-match
2824 on an existentially-quantified constructor in a <Literal>case</Literal> expression or
2825 in the patterns of a function definition.
2826
2827 The reason for this restriction is really an implementation one.
2828 Type-checking binding groups is already a nightmare without
2829 existentials complicating the picture.  Also an existential pattern
2830 binding at the top level of a module doesn't make sense, because it's
2831 not clear how to prevent the existentially-quantified type "escaping".
2832 So for now, there's a simple-to-state restriction.  We'll see how
2833 annoying it is.
2834
2835 </Para>
2836 </ListItem>
2837 <ListItem>
2838
2839 <Para>
2840 You can't use existential quantification for <Literal>newtype</Literal>
2841 declarations.  So this is illegal:
2842
2843
2844 <ProgramListing>
2845   newtype T = forall a. Ord a => MkT a
2846 </ProgramListing>
2847
2848
2849 Reason: a value of type <Literal>T</Literal> must be represented as a pair
2850 of a dictionary for <Literal>Ord t</Literal> and a value of type <Literal>t</Literal>.
2851 That contradicts the idea that <Literal>newtype</Literal> should have no
2852 concrete representation.  You can get just the same efficiency and effect
2853 by using <Literal>data</Literal> instead of <Literal>newtype</Literal>.  If there is no
2854 overloading involved, then there is more of a case for allowing
2855 an existentially-quantified <Literal>newtype</Literal>, because the <Literal>data</Literal>
2856 because the <Literal>data</Literal> version does carry an implementation cost,
2857 but single-field existentially quantified constructors aren't much
2858 use.  So the simple restriction (no existential stuff on <Literal>newtype</Literal>)
2859 stands, unless there are convincing reasons to change it.
2860
2861
2862 </Para>
2863 </ListItem>
2864 <ListItem>
2865
2866 <Para>
2867  You can't use <Literal>deriving</Literal> to define instances of a
2868 data type with existentially quantified data constructors.
2869
2870 Reason: in most cases it would not make sense. For example:&num;
2871
2872 <ProgramListing>
2873 data T = forall a. MkT [a] deriving( Eq )
2874 </ProgramListing>
2875
2876 To derive <Literal>Eq</Literal> in the standard way we would need to have equality
2877 between the single component of two <Function>MkT</Function> constructors:
2878
2879 <ProgramListing>
2880 instance Eq T where
2881   (MkT a) == (MkT b) = ???
2882 </ProgramListing>
2883
2884 But <VarName>a</VarName> and <VarName>b</VarName> have distinct types, and so can't be compared.
2885 It's just about possible to imagine examples in which the derived instance
2886 would make sense, but it seems altogether simpler simply to prohibit such
2887 declarations.  Define your own instances!
2888 </Para>
2889 </ListItem>
2890
2891 </ItemizedList>
2892
2893 </Para>
2894
2895 </Sect2>
2896
2897 </Sect1>
2898
2899 <Sect1 id="sec-assertions">
2900 <Title>Assertions
2901 <IndexTerm><Primary>Assertions</Primary></IndexTerm>
2902 </Title>
2903
2904 <Para>
2905 If you want to make use of assertions in your standard Haskell code, you
2906 could define a function like the following:
2907 </Para>
2908
2909 <Para>
2910
2911 <ProgramListing>
2912 assert :: Bool -> a -> a
2913 assert False x = error "assertion failed!"
2914 assert _     x = x
2915 </ProgramListing>
2916
2917 </Para>
2918
2919 <Para>
2920 which works, but gives you back a less than useful error message --
2921 an assertion failed, but which and where?
2922 </Para>
2923
2924 <Para>
2925 One way out is to define an extended <Function>assert</Function> function which also
2926 takes a descriptive string to include in the error message and
2927 perhaps combine this with the use of a pre-processor which inserts
2928 the source location where <Function>assert</Function> was used.
2929 </Para>
2930
2931 <Para>
2932 Ghc offers a helping hand here, doing all of this for you. For every
2933 use of <Function>assert</Function> in the user's source:
2934 </Para>
2935
2936 <Para>
2937
2938 <ProgramListing>
2939 kelvinToC :: Double -> Double
2940 kelvinToC k = assert (k &gt;= 0.0) (k+273.15)
2941 </ProgramListing>
2942
2943 </Para>
2944
2945 <Para>
2946 Ghc will rewrite this to also include the source location where the
2947 assertion was made,
2948 </Para>
2949
2950 <Para>
2951
2952 <ProgramListing>
2953 assert pred val ==> assertError "Main.hs|15" pred val
2954 </ProgramListing>
2955
2956 </Para>
2957
2958 <Para>
2959 The rewrite is only performed by the compiler when it spots
2960 applications of <Function>Exception.assert</Function>, so you can still define and
2961 use your own versions of <Function>assert</Function>, should you so wish. If not,
2962 import <Literal>Exception</Literal> to make use <Function>assert</Function> in your code.
2963 </Para>
2964
2965 <Para>
2966 To have the compiler ignore uses of assert, use the compiler option
2967 <Option>-fignore-asserts</Option>. <IndexTerm><Primary>-fignore-asserts option</Primary></IndexTerm> That is,
2968 expressions of the form <Literal>assert pred e</Literal> will be rewritten to <Literal>e</Literal>.
2969 </Para>
2970
2971 <Para>
2972 Assertion failures can be caught, see the documentation for the
2973 <literal>Exception</literal> library (<xref linkend="sec-Exception">)
2974 for the details.
2975 </Para>
2976
2977 </Sect1>
2978
2979 <Sect1 id="scoped-type-variables">
2980 <Title>Scoped Type Variables
2981 </Title>
2982
2983 <Para>
2984 A <Emphasis>pattern type signature</Emphasis> can introduce a <Emphasis>scoped type
2985 variable</Emphasis>.  For example
2986 </Para>
2987
2988 <Para>
2989
2990 <ProgramListing>
2991 f (xs::[a]) = ys ++ ys
2992            where
2993               ys :: [a]
2994               ys = reverse xs
2995 </ProgramListing>
2996
2997 </Para>
2998
2999 <Para>
3000 The pattern <Literal>(xs::[a])</Literal> includes a type signature for <VarName>xs</VarName>.
3001 This brings the type variable <Literal>a</Literal> into scope; it scopes over
3002 all the patterns and right hand sides for this equation for <Function>f</Function>.
3003 In particular, it is in scope at the type signature for <VarName>y</VarName>.
3004 </Para>
3005
3006 <Para>
3007 At ordinary type signatures, such as that for <VarName>ys</VarName>, any type variables
3008 mentioned in the type signature <Emphasis>that are not in scope</Emphasis> are
3009 implicitly universally quantified.  (If there are no type variables in
3010 scope, all type variables mentioned in the signature are universally
3011 quantified, which is just as in Haskell 98.)  In this case, since <VarName>a</VarName>
3012 is in scope, it is not universally quantified, so the type of <VarName>ys</VarName> is
3013 the same as that of <VarName>xs</VarName>.  In Haskell 98 it is not possible to declare
3014 a type for <VarName>ys</VarName>; a major benefit of scoped type variables is that
3015 it becomes possible to do so.
3016 </Para>
3017
3018 <Para>
3019 Scoped type variables are implemented in both GHC and Hugs.  Where the
3020 implementations differ from the specification below, those differences
3021 are noted.
3022 </Para>
3023
3024 <Para>
3025 So much for the basic idea.  Here are the details.
3026 </Para>
3027
3028 <Sect2>
3029 <Title>Scope and implicit quantification</Title>
3030
3031 <Para>
3032
3033 <ItemizedList>
3034 <ListItem>
3035
3036 <Para>
3037  All the type variables mentioned in the patterns for a single
3038 function definition equation, that are not already in scope,
3039 are brought into scope by the patterns.  We describe this set as
3040 the <Emphasis>type variables bound by the equation</Emphasis>.
3041
3042 </Para>
3043 </ListItem>
3044 <ListItem>
3045
3046 <Para>
3047  The type variables thus brought into scope may be mentioned
3048 in ordinary type signatures or pattern type signatures anywhere within
3049 their scope.
3050
3051 </Para>
3052 </ListItem>
3053 <ListItem>
3054
3055 <Para>
3056  In ordinary type signatures, any type variable mentioned in the
3057 signature that is in scope is <Emphasis>not</Emphasis> universally quantified.
3058
3059 </Para>
3060 </ListItem>
3061 <ListItem>
3062
3063 <Para>
3064  Ordinary type signatures do not bring any new type variables
3065 into scope (except in the type signature itself!). So this is illegal:
3066
3067
3068 <ProgramListing>
3069   f :: a -> a
3070   f x = x::a
3071 </ProgramListing>
3072
3073
3074 It's illegal because <VarName>a</VarName> is not in scope in the body of <Function>f</Function>,
3075 so the ordinary signature <Literal>x::a</Literal> is equivalent to <Literal>x::forall a.a</Literal>;
3076 and that is an incorrect typing.
3077
3078 </Para>
3079 </ListItem>
3080 <ListItem>
3081
3082 <Para>
3083  There is no implicit universal quantification on pattern type
3084 signatures, nor may one write an explicit <Literal>forall</Literal> type in a pattern
3085 type signature.  The pattern type signature is a monotype.
3086
3087 </Para>
3088 </ListItem>
3089 <ListItem>
3090
3091 <Para>
3092
3093 The type variables in the head of a <Literal>class</Literal> or <Literal>instance</Literal> declaration
3094 scope over the methods defined in the <Literal>where</Literal> part.  For example:
3095
3096
3097 <ProgramListing>
3098   class C a where
3099     op :: [a] -> a
3100
3101     op xs = let ys::[a]
3102                 ys = reverse xs
3103             in
3104             head ys
3105 </ProgramListing>
3106
3107
3108 (Not implemented in Hugs yet, Dec 98).
3109 </Para>
3110 </ListItem>
3111
3112 </ItemizedList>
3113
3114 </Para>
3115
3116 </Sect2>
3117
3118 <Sect2>
3119 <Title>Polymorphism</Title>
3120
3121 <Para>
3122
3123 <ItemizedList>
3124 <ListItem>
3125
3126 <Para>
3127  Pattern type signatures are completely orthogonal to ordinary, separate
3128 type signatures.  The two can be used independently or together.  There is
3129 no scoping associated with the names of the type variables in a separate type signature.
3130
3131
3132 <ProgramListing>
3133    f :: [a] -> [a]
3134    f (xs::[b]) = reverse xs
3135 </ProgramListing>
3136
3137
3138 </Para>
3139 </ListItem>
3140 <ListItem>
3141
3142 <Para>
3143  The function must be polymorphic in the type variables
3144 bound by all its equations.  Operationally, the type variables bound
3145 by one equation must not:
3146
3147
3148 <ItemizedList>
3149 <ListItem>
3150
3151 <Para>
3152  Be unified with a type (such as <Literal>Int</Literal>, or <Literal>[a]</Literal>).
3153 </Para>
3154 </ListItem>
3155 <ListItem>
3156
3157 <Para>
3158  Be unified with a type variable free in the environment.
3159 </Para>
3160 </ListItem>
3161 <ListItem>
3162
3163 <Para>
3164  Be unified with each other.  (They may unify with the type variables
3165 bound by another equation for the same function, of course.)
3166 </Para>
3167 </ListItem>
3168
3169 </ItemizedList>
3170
3171
3172 For example, the following all fail to type check:
3173
3174
3175 <ProgramListing>
3176   f (x::a) (y::b) = [x,y]       -- a unifies with b
3177
3178   g (x::a) = x + 1::Int         -- a unifies with Int
3179
3180   h x = let k (y::a) = [x,y]    -- a is free in the
3181         in k x                  -- environment
3182
3183   k (x::a) True    = ...        -- a unifies with Int
3184   k (x::Int) False = ...
3185
3186   w :: [b] -> [b]
3187   w (x::a) = x                  -- a unifies with [b]
3188 </ProgramListing>
3189
3190
3191 </Para>
3192 </ListItem>
3193 <ListItem>
3194
3195 <Para>
3196  The pattern-bound type variable may, however, be constrained
3197 by the context of the principal type, thus:
3198
3199
3200 <ProgramListing>
3201   f (x::a) (y::a) = x+y*2
3202 </ProgramListing>
3203
3204
3205 gets the inferred type: <Literal>forall a. Num a =&gt; a -&gt; a -&gt; a</Literal>.
3206 </Para>
3207 </ListItem>
3208
3209 </ItemizedList>
3210
3211 </Para>
3212
3213 </Sect2>
3214
3215 <Sect2>
3216 <Title>Result type signatures</Title>
3217
3218 <Para>
3219
3220 <ItemizedList>
3221 <ListItem>
3222
3223 <Para>
3224  The result type of a function can be given a signature,
3225 thus:
3226
3227
3228 <ProgramListing>
3229   f (x::a) :: [a] = [x,x,x]
3230 </ProgramListing>
3231
3232
3233 The final <Literal>:: [a]</Literal> after all the patterns gives a signature to the
3234 result type.  Sometimes this is the only way of naming the type variable
3235 you want:
3236
3237
3238 <ProgramListing>
3239   f :: Int -> [a] -> [a]
3240   f n :: ([a] -> [a]) = let g (x::a, y::a) = (y,x)
3241                         in \xs -> map g (reverse xs `zip` xs)
3242 </ProgramListing>
3243
3244
3245 </Para>
3246 </ListItem>
3247
3248 </ItemizedList>
3249
3250 </Para>
3251
3252 <Para>
3253 Result type signatures are not yet implemented in Hugs.
3254 </Para>
3255
3256 </Sect2>
3257
3258 <Sect2>
3259 <Title>Pattern signatures on other constructs</Title>
3260
3261 <Para>
3262
3263 <ItemizedList>
3264 <ListItem>
3265
3266 <Para>
3267  A pattern type signature can be on an arbitrary sub-pattern, not
3268 just on a variable:
3269
3270
3271 <ProgramListing>
3272   f ((x,y)::(a,b)) = (y,x) :: (b,a)
3273 </ProgramListing>
3274
3275
3276 </Para>
3277 </ListItem>
3278 <ListItem>
3279
3280 <Para>
3281  Pattern type signatures, including the result part, can be used
3282 in lambda abstractions:
3283
3284
3285 <ProgramListing>
3286   (\ (x::a, y) :: a -> x)
3287 </ProgramListing>
3288
3289
3290 Type variables bound by these patterns must be polymorphic in
3291 the sense defined above.
3292 For example:
3293
3294
3295 <ProgramListing>
3296   f1 (x::c) = f1 x      -- ok
3297   f2 = \(x::c) -> f2 x  -- not ok
3298 </ProgramListing>
3299
3300
3301 Here, <Function>f1</Function> is OK, but <Function>f2</Function> is not, because <VarName>c</VarName> gets unified
3302 with a type variable free in the environment, in this
3303 case, the type of <Function>f2</Function>, which is in the environment when
3304 the lambda abstraction is checked.
3305
3306 </Para>
3307 </ListItem>
3308 <ListItem>
3309
3310 <Para>
3311  Pattern type signatures, including the result part, can be used
3312 in <Literal>case</Literal> expressions:
3313
3314
3315 <ProgramListing>
3316   case e of { (x::a, y) :: a -> x }
3317 </ProgramListing>
3318
3319
3320 The pattern-bound type variables must, as usual,
3321 be polymorphic in the following sense: each case alternative,
3322 considered as a lambda abstraction, must be polymorphic.
3323 Thus this is OK:
3324
3325
3326 <ProgramListing>
3327   case (True,False) of { (x::a, y) -> x }
3328 </ProgramListing>
3329
3330
3331 Even though the context is that of a pair of booleans,
3332 the alternative itself is polymorphic.  Of course, it is
3333 also OK to say:
3334
3335
3336 <ProgramListing>
3337   case (True,False) of { (x::Bool, y) -> x }
3338 </ProgramListing>
3339
3340
3341 </Para>
3342 </ListItem>
3343 <ListItem>
3344
3345 <Para>
3346 To avoid ambiguity, the type after the &ldquo;<Literal>::</Literal>&rdquo; in a result
3347 pattern signature on a lambda or <Literal>case</Literal> must be atomic (i.e. a single
3348 token or a parenthesised type of some sort).  To see why,
3349 consider how one would parse this:
3350
3351
3352 <ProgramListing>
3353   \ x :: a -> b -> x
3354 </ProgramListing>
3355
3356
3357 </Para>
3358 </ListItem>
3359 <ListItem>
3360
3361 <Para>
3362  Pattern type signatures that bind new type variables
3363 may not be used in pattern bindings at all.
3364 So this is illegal:
3365
3366
3367 <ProgramListing>
3368   f x = let (y, z::a) = x in ...
3369 </ProgramListing>
3370
3371
3372 But these are OK, because they do not bind fresh type variables:
3373
3374
3375 <ProgramListing>
3376   f1 x            = let (y, z::Int) = x in ...
3377   f2 (x::(Int,a)) = let (y, z::a)   = x in ...
3378 </ProgramListing>
3379
3380
3381 However a single variable is considered a degenerate function binding,
3382 rather than a degerate pattern binding, so this is permitted, even
3383 though it binds a type variable:
3384
3385
3386 <ProgramListing>
3387   f :: (b->b) = \(x::b) -> x
3388 </ProgramListing>
3389
3390
3391 </Para>
3392 </ListItem>
3393
3394 </ItemizedList>
3395
3396 Such degnerate function bindings do not fall under the monomorphism
3397 restriction.  Thus:
3398 </Para>
3399
3400 <Para>
3401
3402 <ProgramListing>
3403   g :: a -> a -> Bool = \x y. x==y
3404 </ProgramListing>
3405
3406 </Para>
3407
3408 <Para>
3409 Here <Function>g</Function> has type <Literal>forall a. Eq a =&gt; a -&gt; a -&gt; Bool</Literal>, just as if
3410 <Function>g</Function> had a separate type signature.  Lacking a type signature, <Function>g</Function>
3411 would get a monomorphic type.
3412 </Para>
3413
3414 </Sect2>
3415
3416 <Sect2>
3417 <Title>Existentials</Title>
3418
3419 <Para>
3420
3421 <ItemizedList>
3422 <ListItem>
3423
3424 <Para>
3425  Pattern type signatures can bind existential type variables.
3426 For example:
3427
3428
3429 <ProgramListing>
3430   data T = forall a. MkT [a]
3431
3432   f :: T -> T
3433   f (MkT [t::a]) = MkT t3
3434                  where
3435                    t3::[a] = [t,t,t]
3436 </ProgramListing>
3437
3438
3439 </Para>
3440 </ListItem>
3441
3442 </ItemizedList>
3443
3444 </Para>
3445
3446 </Sect2>
3447
3448 </Sect1>
3449
3450 <Sect1 id="pragmas">
3451 <Title>Pragmas
3452 </Title>
3453
3454 <Para>
3455 GHC supports several pragmas, or instructions to the compiler placed
3456 in the source code.  Pragmas don't affect the meaning of the program,
3457 but they might affect the efficiency of the generated code.
3458 </Para>
3459
3460 <Sect2 id="inline-pragma">
3461 <Title>INLINE pragma
3462
3463 <IndexTerm><Primary>INLINE pragma</Primary></IndexTerm>
3464 <IndexTerm><Primary>pragma, INLINE</Primary></IndexTerm></Title>
3465
3466 <Para>
3467 GHC (with <Option>-O</Option>, as always) tries to inline (or &ldquo;unfold&rdquo;)
3468 functions/values that are &ldquo;small enough,&rdquo; thus avoiding the call
3469 overhead and possibly exposing other more-wonderful optimisations.
3470 </Para>
3471
3472 <Para>
3473 You will probably see these unfoldings (in Core syntax) in your
3474 interface files.
3475 </Para>
3476
3477 <Para>
3478 Normally, if GHC decides a function is &ldquo;too expensive&rdquo; to inline, it
3479 will not do so, nor will it export that unfolding for other modules to
3480 use.
3481 </Para>
3482
3483 <Para>
3484 The sledgehammer you can bring to bear is the
3485 <Literal>INLINE</Literal><IndexTerm><Primary>INLINE pragma</Primary></IndexTerm> pragma, used thusly:
3486
3487 <ProgramListing>
3488 key_function :: Int -> String -> (Bool, Double)
3489
3490 #ifdef __GLASGOW_HASKELL__
3491 {-# INLINE key_function #-}
3492 #endif
3493 </ProgramListing>
3494
3495 (You don't need to do the C pre-processor carry-on unless you're going
3496 to stick the code through HBC&mdash;it doesn't like <Literal>INLINE</Literal> pragmas.)
3497 </Para>
3498
3499 <Para>
3500 The major effect of an <Literal>INLINE</Literal> pragma is to declare a function's
3501 &ldquo;cost&rdquo; to be very low.  The normal unfolding machinery will then be
3502 very keen to inline it.
3503 </Para>
3504
3505 <Para>
3506 An <Literal>INLINE</Literal> pragma for a function can be put anywhere its type
3507 signature could be put.
3508 </Para>
3509
3510 <Para>
3511 <Literal>INLINE</Literal> pragmas are a particularly good idea for the
3512 <Literal>then</Literal>/<Literal>return</Literal> (or <Literal>bind</Literal>/<Literal>unit</Literal>) functions in a monad.
3513 For example, in GHC's own <Literal>UniqueSupply</Literal> monad code, we have:
3514
3515 <ProgramListing>
3516 #ifdef __GLASGOW_HASKELL__
3517 {-# INLINE thenUs #-}
3518 {-# INLINE returnUs #-}
3519 #endif
3520 </ProgramListing>
3521
3522 </Para>
3523
3524 </Sect2>
3525
3526 <Sect2 id="noinline-pragma">
3527 <Title>NOINLINE pragma
3528 </Title>
3529
3530 <Para>
3531 <IndexTerm><Primary>NOINLINE pragma</Primary></IndexTerm>
3532 <IndexTerm><Primary>pragma, NOINLINE</Primary></IndexTerm>
3533 </Para>
3534
3535 <Para>
3536 The <Literal>NOINLINE</Literal> pragma does exactly what you'd expect: it stops the
3537 named function from being inlined by the compiler.  You shouldn't ever
3538 need to do this, unless you're very cautious about code size.
3539 </Para>
3540
3541 </Sect2>
3542
3543 <Sect2 id="specialize-pragma">
3544 <Title>SPECIALIZE pragma
3545 </Title>
3546
3547 <Para>
3548 <IndexTerm><Primary>SPECIALIZE pragma</Primary></IndexTerm>
3549 <IndexTerm><Primary>pragma, SPECIALIZE</Primary></IndexTerm>
3550 <IndexTerm><Primary>overloading, death to</Primary></IndexTerm>
3551 </Para>
3552
3553 <Para>
3554 (UK spelling also accepted.)  For key overloaded functions, you can
3555 create extra versions (NB: more code space) specialised to particular
3556 types.  Thus, if you have an overloaded function:
3557 </Para>
3558
3559 <Para>
3560
3561 <ProgramListing>
3562 hammeredLookup :: Ord key => [(key, value)] -> key -> value
3563 </ProgramListing>
3564
3565 </Para>
3566
3567 <Para>
3568 If it is heavily used on lists with <Literal>Widget</Literal> keys, you could
3569 specialise it as follows:
3570
3571 <ProgramListing>
3572 {-# SPECIALIZE hammeredLookup :: [(Widget, value)] -> Widget -> value #-}
3573 </ProgramListing>
3574
3575 </Para>
3576
3577 <Para>
3578 To get very fancy, you can also specify a named function to use for
3579 the specialised value, by adding <Literal>= blah</Literal>, as in:
3580
3581 <ProgramListing>
3582 {-# SPECIALIZE hammeredLookup :: ...as before... = blah #-}
3583 </ProgramListing>
3584
3585 It's <Emphasis>Your Responsibility</Emphasis> to make sure that <Function>blah</Function> really
3586 behaves as a specialised version of <Function>hammeredLookup</Function>!!!
3587 </Para>
3588
3589 <Para>
3590 NOTE: the <Literal>=blah</Literal> feature isn't implemented in GHC 4.xx.
3591 </Para>
3592
3593 <Para>
3594 An example in which the <Literal>= blah</Literal> form will Win Big:
3595
3596 <ProgramListing>
3597 toDouble :: Real a => a -> Double
3598 toDouble = fromRational . toRational
3599
3600 {-# SPECIALIZE toDouble :: Int -> Double = i2d #-}
3601 i2d (I# i) = D# (int2Double# i) -- uses Glasgow prim-op directly
3602 </ProgramListing>
3603
3604 The <Function>i2d</Function> function is virtually one machine instruction; the
3605 default conversion&mdash;via an intermediate <Literal>Rational</Literal>&mdash;is obscenely
3606 expensive by comparison.
3607 </Para>
3608
3609 <Para>
3610 By using the US spelling, your <Literal>SPECIALIZE</Literal> pragma will work with
3611 HBC, too.  Note that HBC doesn't support the <Literal>= blah</Literal> form.
3612 </Para>
3613
3614 <Para>
3615 A <Literal>SPECIALIZE</Literal> pragma for a function can be put anywhere its type
3616 signature could be put.
3617 </Para>
3618
3619 </Sect2>
3620
3621 <Sect2 id="specialize-instance-pragma">
3622 <Title>SPECIALIZE instance pragma
3623 </Title>
3624
3625 <Para>
3626 <IndexTerm><Primary>SPECIALIZE pragma</Primary></IndexTerm>
3627 <IndexTerm><Primary>overloading, death to</Primary></IndexTerm>
3628 Same idea, except for instance declarations.  For example:
3629
3630 <ProgramListing>
3631 instance (Eq a) => Eq (Foo a) where { ... usual stuff ... }
3632
3633 {-# SPECIALIZE instance Eq (Foo [(Int, Bar)] #-}
3634 </ProgramListing>
3635
3636 Compatible with HBC, by the way.
3637 </Para>
3638
3639 </Sect2>
3640
3641 <Sect2 id="line-pragma">
3642 <Title>LINE pragma
3643 </Title>
3644
3645 <Para>
3646 <IndexTerm><Primary>LINE pragma</Primary></IndexTerm>
3647 <IndexTerm><Primary>pragma, LINE</Primary></IndexTerm>
3648 </Para>
3649
3650 <Para>
3651 This pragma is similar to C's <Literal>&num;line</Literal> pragma, and is mainly for use in
3652 automatically generated Haskell code.  It lets you specify the line
3653 number and filename of the original code; for example
3654 </Para>
3655
3656 <Para>
3657
3658 <ProgramListing>
3659 {-# LINE 42 "Foo.vhs" #-}
3660 </ProgramListing>
3661
3662 </Para>
3663
3664 <Para>
3665 if you'd generated the current file from something called <Filename>Foo.vhs</Filename>
3666 and this line corresponds to line 42 in the original.  GHC will adjust
3667 its error messages to refer to the line/file named in the <Literal>LINE</Literal>
3668 pragma.
3669 </Para>
3670
3671 </Sect2>
3672
3673 <Sect2>
3674 <Title>RULES pragma</Title>
3675
3676 <Para>
3677 The RULES pragma lets you specify rewrite rules.  It is described in
3678 <XRef LinkEnd="rewrite-rules">.
3679 </Para>
3680
3681 </Sect2>
3682
3683 </Sect1>
3684
3685 <Sect1 id="rewrite-rules">
3686 <Title>Rewrite rules
3687
3688 <IndexTerm><Primary>RULES pagma</Primary></IndexTerm>
3689 <IndexTerm><Primary>pragma, RULES</Primary></IndexTerm>
3690 <IndexTerm><Primary>rewrite rules</Primary></IndexTerm></Title>
3691
3692 <Para>
3693 The programmer can specify rewrite rules as part of the source program
3694 (in a pragma).  GHC applies these rewrite rules wherever it can.
3695 </Para>
3696
3697 <Para>
3698 Here is an example:
3699
3700 <ProgramListing>
3701   {-# RULES
3702         "map/map"       forall f g xs. map f (map g xs) = map (f.g) xs
3703   #-}
3704 </ProgramListing>
3705
3706 </Para>
3707
3708 <Sect2>
3709 <Title>Syntax</Title>
3710
3711 <Para>
3712 From a syntactic point of view:
3713
3714 <ItemizedList>
3715 <ListItem>
3716
3717 <Para>
3718  Each rule has a name, enclosed in double quotes.  The name itself has
3719 no significance at all.  It is only used when reporting how many times the rule fired.
3720 </Para>
3721 </ListItem>
3722 <ListItem>
3723
3724 <Para>
3725  There may be zero or more rules in a <Literal>RULES</Literal> pragma.
3726 </Para>
3727 </ListItem>
3728 <ListItem>
3729
3730 <Para>
3731  Layout applies in a <Literal>RULES</Literal> pragma.  Currently no new indentation level
3732 is set, so you must lay out your rules starting in the same column as the
3733 enclosing definitions.
3734 </Para>
3735 </ListItem>
3736 <ListItem>
3737
3738 <Para>
3739  Each variable mentioned in a rule must either be in scope (e.g. <Function>map</Function>),
3740 or bound by the <Literal>forall</Literal> (e.g. <Function>f</Function>, <Function>g</Function>, <Function>xs</Function>).  The variables bound by
3741 the <Literal>forall</Literal> are called the <Emphasis>pattern</Emphasis> variables.  They are separated
3742 by spaces, just like in a type <Literal>forall</Literal>.
3743 </Para>
3744 </ListItem>
3745 <ListItem>
3746
3747 <Para>
3748  A pattern variable may optionally have a type signature.
3749 If the type of the pattern variable is polymorphic, it <Emphasis>must</Emphasis> have a type signature.
3750 For example, here is the <Literal>foldr/build</Literal> rule:
3751
3752 <ProgramListing>
3753 "fold/build"  forall k z (g::forall b. (a->b->b) -> b -> b) .
3754               foldr k z (build g) = g k z
3755 </ProgramListing>
3756
3757 Since <Function>g</Function> has a polymorphic type, it must have a type signature.
3758
3759 </Para>
3760 </ListItem>
3761 <ListItem>
3762
3763 <Para>
3764 The left hand side of a rule must consist of a top-level variable applied
3765 to arbitrary expressions.  For example, this is <Emphasis>not</Emphasis> OK:
3766
3767 <ProgramListing>
3768 "wrong1"   forall e1 e2.  case True of { True -> e1; False -> e2 } = e1
3769 "wrong2"   forall f.      f True = True
3770 </ProgramListing>
3771
3772 In <Literal>"wrong1"</Literal>, the LHS is not an application; in <Literal>"wrong2"</Literal>, the LHS has a pattern variable
3773 in the head.
3774 </Para>
3775 </ListItem>
3776 <ListItem>
3777
3778 <Para>
3779  A rule does not need to be in the same module as (any of) the
3780 variables it mentions, though of course they need to be in scope.
3781 </Para>
3782 </ListItem>
3783 <ListItem>
3784
3785 <Para>
3786  Rules are automatically exported from a module, just as instance declarations are.
3787 </Para>
3788 </ListItem>
3789
3790 </ItemizedList>
3791
3792 </Para>
3793
3794 </Sect2>
3795
3796 <Sect2>
3797 <Title>Semantics</Title>
3798
3799 <Para>
3800 From a semantic point of view:
3801
3802 <ItemizedList>
3803 <ListItem>
3804
3805 <Para>
3806 Rules are only applied if you use the <Option>-O</Option> flag.
3807 </Para>
3808 </ListItem>
3809
3810 <ListItem>
3811 <Para>
3812  Rules are regarded as left-to-right rewrite rules.
3813 When GHC finds an expression that is a substitution instance of the LHS
3814 of a rule, it replaces the expression by the (appropriately-substituted) RHS.
3815 By "a substitution instance" we mean that the LHS can be made equal to the
3816 expression by substituting for the pattern variables.
3817
3818 </Para>
3819 </ListItem>
3820 <ListItem>
3821
3822 <Para>
3823  The LHS and RHS of a rule are typechecked, and must have the
3824 same type.
3825
3826 </Para>
3827 </ListItem>
3828 <ListItem>
3829
3830 <Para>
3831  GHC makes absolutely no attempt to verify that the LHS and RHS
3832 of a rule have the same meaning.  That is undecideable in general, and
3833 infeasible in most interesting cases.  The responsibility is entirely the programmer's!
3834
3835 </Para>
3836 </ListItem>
3837 <ListItem>
3838
3839 <Para>
3840  GHC makes no attempt to make sure that the rules are confluent or
3841 terminating.  For example:
3842
3843 <ProgramListing>
3844   "loop"        forall x,y.  f x y = f y x
3845 </ProgramListing>
3846
3847 This rule will cause the compiler to go into an infinite loop.
3848
3849 </Para>
3850 </ListItem>
3851 <ListItem>
3852
3853 <Para>
3854  If more than one rule matches a call, GHC will choose one arbitrarily to apply.
3855
3856 </Para>
3857 </ListItem>
3858 <ListItem>
3859 <Para>
3860  GHC currently uses a very simple, syntactic, matching algorithm
3861 for matching a rule LHS with an expression.  It seeks a substitution
3862 which makes the LHS and expression syntactically equal modulo alpha
3863 conversion.  The pattern (rule), but not the expression, is eta-expanded if
3864 necessary.  (Eta-expanding the epression can lead to laziness bugs.)
3865 But not beta conversion (that's called higher-order matching).
3866 </Para>
3867
3868 <Para>
3869 Matching is carried out on GHC's intermediate language, which includes
3870 type abstractions and applications.  So a rule only matches if the
3871 types match too.  See <XRef LinkEnd="rule-spec"> below.
3872 </Para>
3873 </ListItem>
3874 <ListItem>
3875
3876 <Para>
3877  GHC keeps trying to apply the rules as it optimises the program.
3878 For example, consider:
3879
3880 <ProgramListing>
3881   let s = map f
3882       t = map g
3883   in
3884   s (t xs)
3885 </ProgramListing>
3886
3887 The expression <Literal>s (t xs)</Literal> does not match the rule <Literal>"map/map"</Literal>, but GHC
3888 will substitute for <VarName>s</VarName> and <VarName>t</VarName>, giving an expression which does match.
3889 If <VarName>s</VarName> or <VarName>t</VarName> was (a) used more than once, and (b) large or a redex, then it would
3890 not be substituted, and the rule would not fire.
3891
3892 </Para>
3893 </ListItem>
3894 <ListItem>
3895
3896 <Para>
3897  In the earlier phases of compilation, GHC inlines <Emphasis>nothing
3898 that appears on the LHS of a rule</Emphasis>, because once you have substituted
3899 for something you can't match against it (given the simple minded
3900 matching).  So if you write the rule
3901
3902 <ProgramListing>
3903         "map/map"       forall f,g.  map f . map g = map (f.g)
3904 </ProgramListing>
3905
3906 this <Emphasis>won't</Emphasis> match the expression <Literal>map f (map g xs)</Literal>.
3907 It will only match something written with explicit use of ".".
3908 Well, not quite.  It <Emphasis>will</Emphasis> match the expression
3909
3910 <ProgramListing>
3911 wibble f g xs
3912 </ProgramListing>
3913
3914 where <Function>wibble</Function> is defined:
3915
3916 <ProgramListing>
3917 wibble f g = map f . map g
3918 </ProgramListing>
3919
3920 because <Function>wibble</Function> will be inlined (it's small).
3921
3922 Later on in compilation, GHC starts inlining even things on the
3923 LHS of rules, but still leaves the rules enabled.  This inlining
3924 policy is controlled by the per-simplification-pass flag <Option>-finline-phase</Option><Emphasis>n</Emphasis>.
3925
3926 </Para>
3927 </ListItem>
3928 <ListItem>
3929
3930 <Para>
3931  All rules are implicitly exported from the module, and are therefore
3932 in force in any module that imports the module that defined the rule, directly
3933 or indirectly.  (That is, if A imports B, which imports C, then C's rules are
3934 in force when compiling A.)  The situation is very similar to that for instance
3935 declarations.
3936 </Para>
3937 </ListItem>
3938
3939 </ItemizedList>
3940
3941 </Para>
3942
3943 </Sect2>
3944
3945 <Sect2>
3946 <Title>List fusion</Title>
3947
3948 <Para>
3949 The RULES mechanism is used to implement fusion (deforestation) of common list functions.
3950 If a "good consumer" consumes an intermediate list constructed by a "good producer", the
3951 intermediate list should be eliminated entirely.
3952 </Para>
3953
3954 <Para>
3955 The following are good producers:
3956
3957 <ItemizedList>
3958 <ListItem>
3959
3960 <Para>
3961  List comprehensions
3962 </Para>
3963 </ListItem>
3964 <ListItem>
3965
3966 <Para>
3967  Enumerations of <Literal>Int</Literal> and <Literal>Char</Literal> (e.g. <Literal>['a'..'z']</Literal>).
3968 </Para>
3969 </ListItem>
3970 <ListItem>
3971
3972 <Para>
3973  Explicit lists (e.g. <Literal>[True, False]</Literal>)
3974 </Para>
3975 </ListItem>
3976 <ListItem>
3977
3978 <Para>
3979  The cons constructor (e.g <Literal>3:4:[]</Literal>)
3980 </Para>
3981 </ListItem>
3982 <ListItem>
3983
3984 <Para>
3985  <Function>++</Function>
3986 </Para>
3987 </ListItem>
3988 <ListItem>
3989
3990 <Para>
3991  <Function>map</Function>
3992 </Para>
3993 </ListItem>
3994 <ListItem>
3995
3996 <Para>
3997  <Function>filter</Function>
3998 </Para>
3999 </ListItem>
4000 <ListItem>
4001
4002 <Para>
4003  <Function>iterate</Function>, <Function>repeat</Function>
4004 </Para>
4005 </ListItem>
4006 <ListItem>
4007
4008 <Para>
4009  <Function>zip</Function>, <Function>zipWith</Function>
4010 </Para>
4011 </ListItem>
4012
4013 </ItemizedList>
4014
4015 </Para>
4016
4017 <Para>
4018 The following are good consumers:
4019
4020 <ItemizedList>
4021 <ListItem>
4022
4023 <Para>
4024  List comprehensions
4025 </Para>
4026 </ListItem>
4027 <ListItem>
4028
4029 <Para>
4030  <Function>array</Function> (on its second argument)
4031 </Para>
4032 </ListItem>
4033 <ListItem>
4034
4035 <Para>
4036  <Function>length</Function>
4037 </Para>
4038 </ListItem>
4039 <ListItem>
4040
4041 <Para>
4042  <Function>++</Function> (on its first argument)
4043 </Para>
4044 </ListItem>
4045 <ListItem>
4046
4047 <Para>
4048  <Function>map</Function>
4049 </Para>
4050 </ListItem>
4051 <ListItem>
4052
4053 <Para>
4054  <Function>filter</Function>
4055 </Para>
4056 </ListItem>
4057 <ListItem>
4058
4059 <Para>
4060  <Function>concat</Function>
4061 </Para>
4062 </ListItem>
4063 <ListItem>
4064
4065 <Para>
4066  <Function>unzip</Function>, <Function>unzip2</Function>, <Function>unzip3</Function>, <Function>unzip4</Function>
4067 </Para>
4068 </ListItem>
4069 <ListItem>
4070
4071 <Para>
4072  <Function>zip</Function>, <Function>zipWith</Function> (but on one argument only; if both are good producers, <Function>zip</Function>
4073 will fuse with one but not the other)
4074 </Para>
4075 </ListItem>
4076 <ListItem>
4077
4078 <Para>
4079  <Function>partition</Function>
4080 </Para>
4081 </ListItem>
4082 <ListItem>
4083
4084 <Para>
4085  <Function>head</Function>
4086 </Para>
4087 </ListItem>
4088 <ListItem>
4089
4090 <Para>
4091  <Function>and</Function>, <Function>or</Function>, <Function>any</Function>, <Function>all</Function>
4092 </Para>
4093 </ListItem>
4094 <ListItem>
4095
4096 <Para>
4097  <Function>sequence&lowbar;</Function>
4098 </Para>
4099 </ListItem>
4100 <ListItem>
4101
4102 <Para>
4103  <Function>msum</Function>
4104 </Para>
4105 </ListItem>
4106 <ListItem>
4107
4108 <Para>
4109  <Function>sortBy</Function>
4110 </Para>
4111 </ListItem>
4112
4113 </ItemizedList>
4114
4115 </Para>
4116
4117 <Para>
4118 So, for example, the following should generate no intermediate lists:
4119
4120 <ProgramListing>
4121 array (1,10) [(i,i*i) | i &#60;- map (+ 1) [0..9]]
4122 </ProgramListing>
4123
4124 </Para>
4125
4126 <Para>
4127 This list could readily be extended; if there are Prelude functions that you use
4128 a lot which are not included, please tell us.
4129 </Para>
4130
4131 <Para>
4132 If you want to write your own good consumers or producers, look at the
4133 Prelude definitions of the above functions to see how to do so.
4134 </Para>
4135
4136 </Sect2>
4137
4138 <Sect2 id="rule-spec">
4139 <Title>Specialisation
4140 </Title>
4141
4142 <Para>
4143 Rewrite rules can be used to get the same effect as a feature
4144 present in earlier version of GHC:
4145
4146 <ProgramListing>
4147   {-# SPECIALIZE fromIntegral :: Int8 -> Int16 = int8ToInt16 #-}
4148 </ProgramListing>
4149
4150 This told GHC to use <Function>int8ToInt16</Function> instead of <Function>fromIntegral</Function> whenever
4151 the latter was called with type <Literal>Int8 -&gt; Int16</Literal>.  That is, rather than
4152 specialising the original definition of <Function>fromIntegral</Function> the programmer is
4153 promising that it is safe to use <Function>int8ToInt16</Function> instead.
4154 </Para>
4155
4156 <Para>
4157 This feature is no longer in GHC.  But rewrite rules let you do the
4158 same thing:
4159
4160 <ProgramListing>
4161 {-# RULES
4162   "fromIntegral/Int8/Int16" fromIntegral = int8ToInt16
4163 #-}
4164 </ProgramListing>
4165
4166 This slightly odd-looking rule instructs GHC to replace <Function>fromIntegral</Function>
4167 by <Function>int8ToInt16</Function> <Emphasis>whenever the types match</Emphasis>.  Speaking more operationally,
4168 GHC adds the type and dictionary applications to get the typed rule
4169
4170 <ProgramListing>
4171 forall (d1::Integral Int8) (d2::Num Int16) .
4172         fromIntegral Int8 Int16 d1 d2 = int8ToInt16
4173 </ProgramListing>
4174
4175 What is more,
4176 this rule does not need to be in the same file as fromIntegral,
4177 unlike the <Literal>SPECIALISE</Literal> pragmas which currently do (so that they
4178 have an original definition available to specialise).
4179 </Para>
4180
4181 </Sect2>
4182
4183 <Sect2>
4184 <Title>Controlling what's going on</Title>
4185
4186 <Para>
4187
4188 <ItemizedList>
4189 <ListItem>
4190
4191 <Para>
4192  Use <Option>-ddump-rules</Option> to see what transformation rules GHC is using.
4193 </Para>
4194 </ListItem>
4195 <ListItem>
4196
4197 <Para>
4198  Use <Option>-ddump-simpl-stats</Option> to see what rules are being fired.
4199 If you add <Option>-dppr-debug</Option> you get a more detailed listing.
4200 </Para>
4201 </ListItem>
4202 <ListItem>
4203
4204 <Para>
4205  The defintion of (say) <Function>build</Function> in <FileName>PrelBase.lhs</FileName> looks llike this:
4206
4207 <ProgramListing>
4208         build   :: forall a. (forall b. (a -> b -> b) -> b -> b) -> [a]
4209         {-# INLINE build #-}
4210         build g = g (:) []
4211 </ProgramListing>
4212
4213 Notice the <Literal>INLINE</Literal>!  That prevents <Literal>(:)</Literal> from being inlined when compiling
4214 <Literal>PrelBase</Literal>, so that an importing module will &ldquo;see&rdquo; the <Literal>(:)</Literal>, and can
4215 match it on the LHS of a rule.  <Literal>INLINE</Literal> prevents any inlining happening
4216 in the RHS of the <Literal>INLINE</Literal> thing.  I regret the delicacy of this.
4217
4218 </Para>
4219 </ListItem>
4220 <ListItem>
4221
4222 <Para>
4223  In <Filename>ghc/lib/std/PrelBase.lhs</Filename> look at the rules for <Function>map</Function> to
4224 see how to write rules that will do fusion and yet give an efficient
4225 program even if fusion doesn't happen.  More rules in <Filename>PrelList.lhs</Filename>.
4226 </Para>
4227 </ListItem>
4228
4229 </ItemizedList>
4230
4231 </Para>
4232
4233 </Sect2>
4234
4235 </Sect1>
4236
4237 <Sect1 id="generic-classes">
4238 <Title>Generic classes</Title>
4239
4240 <Para>
4241 The ideas behind this extension are described in detail in "Derivable type classes",
4242 Ralf Hinze and Simon Peyton Jones, Haskell Workshop, Montreal Sept 2000, pp94-105.
4243 An example will give the idea:
4244 </Para>
4245
4246 <ProgramListing>
4247   class Bin a where
4248     toBin   :: a -> [Int]
4249     fromBin :: [Int] -> (a, [Int])
4250   
4251     toBin {| Unit |}    Unit      = []
4252     toBin {| a :+: b |} (Inl x)   = 0 : toBin x
4253     toBin {| a :+: b |} (Inr y)   = 1 : toBin y
4254     toBin {| a :*: b |} (x :*: y) = toBin x ++ toBin y
4255   
4256     fromBin {| Unit |}    bs      = (Unit, bs)
4257     fromBin {| a :+: b |} (0:bs)  = (Inl x, bs')    where (x,bs') = fromBin bs
4258     fromBin {| a :+: b |} (1:bs)  = (Inr y, bs')    where (y,bs') = fromBin bs
4259     fromBin {| a :*: b |} bs      = (x :*: y, bs'') where (x,bs' ) = fromBin bs
4260                                                           (y,bs'') = fromBin bs'
4261 </ProgramListing>
4262 <Para>
4263 This class declaration explains how <Literal>toBin</Literal> and <Literal>fromBin</Literal>
4264 work for arbitrary data types.  They do so by giving cases for unit, product, and sum,
4265 which are defined thus:
4266 </Para>
4267 <ProgramListing>
4268   data Unit    = Unit
4269   data a :+: b = Inl a | Inr b
4270   data a :*: b = a :*: b
4271 </ProgramListing>
4272 <Para>
4273 Now you can make a data type into an instance of Bin like this:
4274 <ProgramListing>
4275   instance (Bin a, Bin b) => Bin (a,b)
4276   instance Bin a => Bin [a]
4277 </ProgramListing>
4278 That is, just leave off the "where" clasuse.  Of course, you can put in the
4279 where clause and over-ride whichever methods you please.
4280
4281
4282 <Sect2> <Title> Using generics </Title>
4283 </Sect2>
4284 <Para>
4285 To use generics you need to
4286 <ItemizedList>
4287 <ListItem>
4288 Use the <Option>-fgenerics</Option> flag.
4289 </ListItem>
4290 <ListItem>
4291 Import the module <Literal>Generics</Literal> from the <Literal>lang</Literal> package.
4292 This import brings into scope the data types <Literal>Unit</Literal>, <Literal>:*:</Literal>, 
4293 and <Literal>:+:</Literal>.  (You don't need this import if you don't mention these
4294 types explicitly; for example, if you are simply giving instance declarations.)
4295 </ListItem>
4296 </ItemizedList>
4297
4298 <Sect2> <Title> Changes wrt the paper </Title>
4299 <Para>
4300 Note that the type constructors <Literal>:+:</Literal> and <Literal>:*:</Literal> 
4301 can be written infix (indeed, you can now use
4302 any operator starting in a colon as an infix type constructor).  Also note that
4303 the type constructors are not exactly as in the paper (Unit instead of 1, etc).
4304 Finally, note that the syntax of the type patterns in the class declaration
4305 uses "<Literal>{|</Literal>" and "<Literal>{|</Literal>" brackets; curly braces
4306 alone would ambiguous when they appear on right hand sides (an extension we 
4307 anticipate wanting).
4308 </Para>
4309 </Sect2>
4310
4311 <Sect2> <Title>Terminology and restrictions</Title>
4312 <Para>
4313 Terminology.  A "generic default method" in a class declaration
4314 is one that is defined using type patterns as above.
4315 A "polymorphic default method" is a default method defined as in Haskell 98.
4316 A "generic class declaration" is a class declaration with at least one
4317 generic default method.
4318 </Para>
4319 Restrictions:
4320 <ItemizedList>
4321 <ListItem> Alas, we do not yet implement the stuff about constructor names and 
4322 field labels.
4323 </ListItem>
4324
4325 <ListItem> A generic class can have only one parameter; you can't have a generic
4326 multi-parameter class.
4327 </ListItem>
4328
4329 <ListItem> A default method must be defined entirely using type patterns, or entirely
4330 without.  So this is illegal:
4331 <ProgramListing>
4332   class Foo a where
4333     op :: a -> (a, Bool)
4334     op {| Unit |} Unit = (Unit, True)
4335     op x               = (x,    False)
4336 </ProgramListing>
4337 However it is perfectly OK for some methods of a generic class to have 
4338 generic default methods and others to have polymorphic default methods.
4339 </ListItem>
4340
4341 <ListItem> The type variable(s) in the type pattern for a generic method declaration
4342 scope over the right hand side.  So this is legal (note the use of the type variable
4343 "p" in a type signature on the right hand side:
4344 <ProgramListing>
4345   class Foo a where
4346     op :: a -> Bool
4347     op {| p :*: q |} (x :*: y) = op (x :: p)
4348     ...
4349 </ProgramListing>
4350
4351 <ListItem> The type patterns in a generic default method must take one of the forms:
4352 <ProgramListing>
4353        a :+: b
4354        a :*: b
4355        Unit
4356 </ProgramListing>
4357 where "a" and "b" are type variables.  Furthermore, all the type patterns for
4358 a single type constructor (<Literal>:*:</Literal>, say) must be identical; they
4359 must use the same type variables.  So this is illegal:
4360 <ProgramListing>
4361   class Foo a where
4362     op :: a -> Bool
4363     op {| a :+: b |} (Inl x) = True
4364     op {| p :+: q |} (Inr y) = False
4365 </ProgramListing>
4366 The type patterns must be identical, even in equations for different methods of the class.
4367 So this too is illegal:
4368 <ProgramListing>
4369   class Foo a where
4370     op1 :: a -> Bool
4371     op {| a :*: b |} (Inl x) = True
4372
4373     op2 :: a -> Bool
4374     op {| p :*: q |} (Inr y) = False
4375 </ProgramListing>
4376 (The reason for this restriction is that we gather all the equations for a particular type consructor
4377 into a single generic instance declaration.)
4378 </ListItem>
4379
4380 <ListItem> A generic method declaration must give a case for each of the three type constructors.
4381 </ListItem>
4382
4383 <ListItem> In an instance declaration for a generic class, the idea is that the compiler
4384 will fill in the methods for you, based on the generic templates.  However it can only
4385 do so if
4386   <ItemizedList>
4387   <ListItem> The instance type is simple (a type constructor applied to type variables, as in Haskell 98).
4388              </ListItem>
4389   <ListItem> No constructor of the instance type has unboxed fields. </ListItem>
4390   </ItemizedList>
4391 (Of course, these things can only arise if you are already using GHC extensions.)
4392 However, you can still give an instance declarations for types which break these rules,
4393 provided you give explicit code to override any generic default methods.
4394
4395 </ListItem>
4396
4397 </ItemizedList>
4398 <Para>
4399 The option <Option>-ddump-deriv</Option> dumps incomprehensible stuff giving details of 
4400 what the compiler does with generic declarations.
4401 </Para>
4402
4403 </Sect2>
4404
4405 <Sect2> <Title> Another example </Title>
4406 <Para>
4407 Just to finish with, here's another example I rather like:
4408 <ProgramListing>
4409   class Tag a where
4410     nCons :: a -> Int
4411     nCons {| Unit |}    _ = 1
4412     nCons {| a :*: b |} _ = 1
4413     nCons {| a :+: b |} _ = nCons (bot::a) + nCons (bot::b)
4414   
4415     tag :: a -> Int
4416     tag {| Unit |}    _       = 1
4417     tag {| a :*: b |} _       = 1   
4418     tag {| a :+: b |} (Inl x) = tag x
4419     tag {| a :+: b |} (Inr y) = nCons (bot::a) + tag y
4420 </ProgramListing>
4421 </Sect2>
4422 </Sect1>
4423
4424 <!-- Emacs stuff:
4425      ;;; Local Variables: ***
4426      ;;; mode: sgml ***
4427      ;;; sgml-parent-document: ("users_guide.sgml" "book" "chapter" "sect1") ***
4428      ;;; End: ***
4429  -->