530f83e12ed7db3f5682edfbc0199c546bc7b59d
[ghc-hetmet.git] / ghc / docs / users_guide / libmisc.sgml
1 <Sect1 id="GHC-library">
2 <Title>Miscellaneous libraries
3 </Title>
4
5 <Para>
6 <IndexTerm><Primary>libraries, miscellaneous</Primary></IndexTerm>
7 <IndexTerm><Primary>misc, syslib</Primary></IndexTerm>
8 </Para>
9
10 <Para>
11 This section describes a collection of Haskell libraries we've
12 collected over the years.  Access to any of these modules is provided
13 by giving the <Literal>-syslib misc</Literal><IndexTerm><Primary>-syslib misc option</Primary></IndexTerm>.
14 </Para>
15
16 <Sect2 id="Bag">
17 <Title>The <Literal>Bag</Literal> type
18 </Title>
19
20 <Para>
21 <IndexTerm><Primary>Bag module (misc syslib)</Primary></IndexTerm>
22 </Para>
23
24 <Para>
25 A <Emphasis>bag</Emphasis> is an unordered collection of elements which may contain
26 duplicates.  To use, <Literal>import Bag</Literal>.
27 </Para>
28
29 <Para>
30
31 <ProgramListing>
32 data Bag elt    -- abstract
33
34 emptyBag        :: Bag elt
35 unitBag         :: elt -&#62; Bag elt
36
37 consBag         :: elt       -&#62; Bag elt -&#62; Bag elt
38 snocBag         :: Bag elt   -&#62; elt     -&#62; Bag elt
39
40 unionBags       :: Bag elt   -&#62; Bag elt -&#62; Bag elt
41 unionManyBags   :: [Bag elt] -&#62; Bag elt
42
43 isEmptyBag      :: Bag elt   -&#62; Bool
44 elemBag         :: Eq elt =&#62; elt -&#62; Bag elt -&#62; Bool
45
46 filterBag       :: (elt -&#62; Bool) -&#62; Bag elt -&#62; Bag elt
47 partitionBag    :: (elt -&#62; Bool) -&#62; Bag elt-&#62; (Bag elt, Bag elt)
48         -- returns the elements that do/don't satisfy the predicate
49
50 concatBag       :: Bag (Bag a) -&#62; Bag a
51 foldBag         :: (r -&#62; r -&#62; r) -&#62; (a -&#62; r) -&#62; r -&#62; Bag a -&#62; r
52 mapBag          :: (a -&#62; b) -&#62; Bag a -&#62; Bag b
53
54 listToBag       :: [elt] -&#62; Bag elt
55 bagToList       :: Bag elt -&#62; [elt]
56 </ProgramListing>
57
58 </Para>
59
60 </Sect2>
61
62 <Sect2 id="FiniteMap">
63 <Title>The <Literal>FiniteMap</Literal> type
64 </Title>
65
66 <Para>
67 <IndexTerm><Primary>FiniteMap module (misc syslib)</Primary></IndexTerm>
68 </Para>
69
70 <Para>
71 What functional programmers call a <Emphasis>finite map</Emphasis>, everyone else
72 calls a <Emphasis>lookup table</Emphasis>.
73 </Para>
74
75 <Para>
76 Out code is derived from that in this paper:
77 <QUOTE
78 >S Adams
79 "Efficient sets: a balancing act"
80 Journal of functional programming 3(4) Oct 1993, pages 553-562</QUOTE
81 >
82 Guess what?  The implementation uses balanced trees.
83 </Para>
84
85 <Para>
86
87 <ProgramListing>
88 data FiniteMap key elt  -- abstract
89
90 --      BUILDING
91 emptyFM         :: FiniteMap key elt
92 unitFM          :: key -&#62; elt -&#62; FiniteMap key elt
93 listToFM        :: Ord key =&#62; [(key,elt)] -&#62; FiniteMap key elt
94                         -- In the case of duplicates, the last is taken
95
96 --      ADDING AND DELETING
97                    -- Throws away any previous binding
98                    -- In the list case, the items are added starting with the
99                    -- first one in the list
100 addToFM         :: Ord key =&#62; FiniteMap key elt -&#62; key -&#62; elt  -&#62; FiniteMap key elt
101 addListToFM     :: Ord key =&#62; FiniteMap key elt -&#62; [(key,elt)] -&#62; FiniteMap key elt
102
103                  -- Combines with previous binding
104                  -- In the combining function, the first argument is
105                  -- the "old" element, while the second is the "new" one.
106 addToFM_C       :: Ord key =&#62; (elt -&#62; elt -&#62; elt)
107                            -&#62; FiniteMap key elt -&#62; key -&#62; elt
108                            -&#62; FiniteMap key elt
109 addListToFM_C   :: Ord key =&#62; (elt -&#62; elt -&#62; elt)
110                            -&#62; FiniteMap key elt -&#62; [(key,elt)]
111                            -&#62; FiniteMap key elt
112
113                  -- Deletion doesn't complain if you try to delete something
114                  -- which isn't there
115 delFromFM       :: Ord key =&#62; FiniteMap key elt -&#62; key   -&#62; FiniteMap key elt
116 delListFromFM   :: Ord key =&#62; FiniteMap key elt -&#62; [key] -&#62; FiniteMap key elt
117
118 --      COMBINING
119                  -- Bindings in right argument shadow those in the left
120 plusFM          :: Ord key =&#62; FiniteMap key elt -&#62; FiniteMap key elt
121                            -&#62; FiniteMap key elt
122
123                    -- Combines bindings for the same thing with the given function
124 plusFM_C        :: Ord key =&#62; (elt -&#62; elt -&#62; elt)
125                            -&#62; FiniteMap key elt -&#62; FiniteMap key elt -&#62; FiniteMap key elt
126
127 minusFM         :: Ord key =&#62; FiniteMap key elt -&#62; FiniteMap key elt -&#62; FiniteMap key elt
128                    -- (minusFM a1 a2) deletes from a1 any bindings which are bound in a2
129
130 intersectFM     :: Ord key =&#62; FiniteMap key elt -&#62; FiniteMap key elt -&#62; FiniteMap key elt
131 intersectFM_C   :: Ord key =&#62; (elt -&#62; elt -&#62; elt)
132                            -&#62; FiniteMap key elt -&#62; FiniteMap key elt -&#62; FiniteMap key elt
133
134 --      MAPPING, FOLDING, FILTERING
135 foldFM          :: (key -&#62; elt -&#62; a -&#62; a) -&#62; a -&#62; FiniteMap key elt -&#62; a
136 mapFM           :: (key -&#62; elt1 -&#62; elt2) -&#62; FiniteMap key elt1 -&#62; FiniteMap key elt2
137 filterFM        :: Ord key =&#62; (key -&#62; elt -&#62; Bool)
138                            -&#62; FiniteMap key elt -&#62; FiniteMap key elt
139
140 --      INTERROGATING
141 sizeFM          :: FiniteMap key elt -&#62; Int
142 isEmptyFM       :: FiniteMap key elt -&#62; Bool
143
144 elemFM          :: Ord key =&#62; key -&#62; FiniteMap key elt -&#62; Bool
145 lookupFM        :: Ord key =&#62; FiniteMap key elt -&#62; key -&#62; Maybe elt
146 lookupWithDefaultFM
147                 :: Ord key =&#62; FiniteMap key elt -&#62; elt -&#62; key -&#62; elt
148                 -- lookupWithDefaultFM supplies a "default" elt
149                 -- to return for an unmapped key
150
151 --      LISTIFYING
152 fmToList        :: FiniteMap key elt -&#62; [(key,elt)]
153 keysFM          :: FiniteMap key elt -&#62; [key]
154 eltsFM          :: FiniteMap key elt -&#62; [elt]
155 </ProgramListing>
156
157 </Para>
158
159 </Sect2>
160
161 <Sect2 id="ListSetOps">
162 <Title>The <Literal>ListSetOps</Literal> type
163 </Title>
164
165 <Para>
166 <IndexTerm><Primary>ListSetOps module (misc syslib)</Primary></IndexTerm>
167 </Para>
168
169 <Para>
170 Just a few set-sounding operations on lists.  If you want sets, use
171 the <Literal>Set</Literal> module.
172 </Para>
173
174 <Para>
175
176 <ProgramListing>
177 unionLists          :: Eq a =&#62; [a] -&#62; [a] -&#62; [a]
178 intersectLists      :: Eq a =&#62; [a] -&#62; [a] -&#62; [a]
179 minusList           :: Eq a =&#62; [a] -&#62; [a] -&#62; [a]
180 disjointLists       :: Eq a =&#62; [a] -&#62; [a] -&#62; Bool
181 intersectingLists   :: Eq a =&#62; [a] -&#62; [a] -&#62; Bool
182 </ProgramListing>
183
184 </Para>
185
186 </Sect2>
187
188 <Sect2 id="Maybes">
189 <Title>The <Literal>Maybes</Literal> type
190 </Title>
191
192 <Para>
193 <IndexTerm><Primary>Maybes module (misc syslib)</Primary></IndexTerm>
194 </Para>
195
196 <Para>
197 The <Literal>Maybe</Literal> type is in the Haskell 1.4 prelude. Moreover, the
198 required <Literal>Maybe</Literal> library provides many useful functions on
199 <Literal>Maybe</Literal>s. This (pre-1.3) module provides some more:
200 </Para>
201
202 <Para>
203 An <Literal>Either</Literal>-like type called <Literal>MaybeErr</Literal>:
204
205 <ProgramListing>
206 data MaybeErr val err = Succeeded val | Failed err
207 </ProgramListing>
208
209 </Para>
210
211 <Para>
212 Some operations to do with <Literal>Maybe</Literal> (some commentary follows):
213
214 <ProgramListing>
215 maybeToBool :: Maybe a -&#62; Bool      -- Nothing =&#62; False; Just =&#62; True
216 allMaybes   :: [Maybe a] -&#62; Maybe [a]
217 firstJust   :: [Maybe a] -&#62; Maybe a
218 findJust    :: (a -&#62; Maybe b) -&#62; [a] -&#62; Maybe b
219
220 assocMaybe  :: Eq a =&#62; [(a,b)] -&#62; a -&#62; Maybe b
221 mkLookupFun :: (key -&#62; key -&#62; Bool) -- Equality predicate
222             -&#62; [(key,val)]          -- The assoc list
223             -&#62; (key -&#62; Maybe val)   -- A lookup fun to use
224 mkLookupFunDef :: (key -&#62; key -&#62; Bool)  -- Equality predicate
225                -&#62; [(key,val)]           -- The assoc list
226                -&#62; val                   -- Value to return on failure
227                -&#62; key                   -- The key
228                -&#62; val                   -- The corresponding value
229
230     -- a monad thing
231 thenMaybe   :: Maybe a -&#62; (a -&#62; Maybe b) -&#62; Maybe b
232 returnMaybe :: a -&#62; Maybe a
233 failMaybe   :: Maybe a
234 mapMaybe    :: (a -&#62; Maybe b) -&#62; [a] -&#62; Maybe [b]
235 </ProgramListing>
236
237 </Para>
238
239 <Para>
240 NB: <Literal>catMaybes</Literal> which used to be here, is now available via the
241 standard <Literal>Maybe</Literal> interface (<Literal>Maybe</Literal> is an instance of <Literal>MonadPlus</Literal>).
242 </Para>
243
244 <Para>
245 <Literal>allMaybes</Literal> collects a list of <Literal>Justs</Literal> into a single <Literal>Just</Literal>, returning
246 <Literal>Nothing</Literal> if there are any <Literal>Nothings</Literal>.
247 </Para>
248
249 <Para>
250 <Literal>firstJust</Literal> takes a list of <Literal>Maybes</Literal> and returns the
251 first <Literal>Just</Literal> if there is one, or <Literal>Nothing</Literal> otherwise.
252 </Para>
253
254 <Para>
255 <Literal>assocMaybe</Literal> looks up in an association list, returning
256 <Literal>Nothing</Literal> if it fails.
257 </Para>
258
259 <Para>
260 Now, some operations to do with <Literal>MaybeErr</Literal> (comments follow):
261
262 <ProgramListing>
263     -- a monad thing (surprise, surprise)
264 thenMaB   :: MaybeErr a err -&#62; (a -&#62; MaybeErr b err) -&#62; MaybeErr b err
265 returnMaB :: val -&#62; MaybeErr val err
266 failMaB   :: err -&#62; MaybeErr val err
267
268 listMaybeErrs :: [MaybeErr val err] -&#62; MaybeErr [val] [err]
269 foldlMaybeErrs :: (acc -&#62; input -&#62; MaybeErr acc err)
270                -&#62; acc
271                -&#62; [input]
272                -&#62; MaybeErr acc [err]
273 </ProgramListing>
274
275 </Para>
276
277 <Para>
278 <Literal>listMaybeErrs</Literal> takes a list of <Literal>MaybeErrs</Literal> and, if they all succeed,
279 returns a <Literal>Succeeded</Literal> of a list of their values.  If any fail, it
280 returns a <Literal>Failed</Literal> of the list of all the errors in the list.
281 </Para>
282
283 <Para>
284 <Literal>foldlMaybeErrs</Literal> works along a list, carrying an accumulator; it
285 applies the given function to the accumulator and the next list item,
286 accumulating any errors that occur.
287 </Para>
288
289 </Sect2>
290
291 <Sect2 id="memo-library">
292 <Title>The <Literal>Memo</Literal> library
293 </Title>
294
295 <Para>
296 <IndexTerm><Primary>Memo (misc syslib)</Primary></IndexTerm>
297 </Para>
298
299 <Para>
300 The <Literal>Memo</Literal> library provides fast polymorphic memo functions using hash
301 tables.  The interface is:
302 </Para>
303
304 <Para>
305
306 <ProgramListing>
307 memo :: (a -&#62; b) -&#62; a -&#62; b
308 </ProgramListing>
309
310 </Para>
311
312 <Para>
313 So, for example, <Literal>memo f</Literal> is a version of <Literal>f</Literal> that caches the results
314 of previous calls.
315 </Para>
316
317 <Para>
318 The searching is very fast, being based on pointer equality.  One
319 consequence of this is that the caching will only be effective if
320 <Emphasis>exactly the same argument is passed again to the memoised
321 function</Emphasis>.  This means not just a copy of a previous argument, but the
322 same instance.  It's not useful to memoise integer functions using
323 this interface, because integers are generally copied a lot and two
324 instances of '27' are unlikely to refer to the same object.
325 </Para>
326
327 <Para>
328 This memoisation library works well when the keys are large (or even
329 infinite).
330 </Para>
331
332 <Para>
333 The memo table implementation uses weak pointers and stable names (see
334 the GHC/Hugs library document) to avoid space leaks and allow hashing
335 for arbitrary Haskell objects.  NOTE: while individual memo table
336 entries will be garbage collected if the associated key becomes
337 garbage, the memo table itself will not be collected if the function
338 becomes garbage.  We plan to fix this in a future version.
339 </Para>
340
341 <Para>
342 There's another version of <Literal>memo</Literal> if you want to explicitly give a
343 size for the hash table (the default size is 1001 buckets):
344 </Para>
345
346 <Para>
347
348 <ProgramListing>
349 memo_sized :: Int -&#62; (a -&#62; b) -&#62; a -&#62; b
350 </ProgramListing>
351
352 </Para>
353
354 </Sect2>
355
356 <Sect2 id="PackedString">
357 <Title>The <Literal>PackedString</Literal> type
358 </Title>
359
360 <Para>
361 <IndexTerm><Primary>PackedString module (misc syslib)</Primary></IndexTerm>
362 </Para>
363
364 <Para>
365 You need to <Literal>import PackedString</Literal> and heave in your
366 <Literal>-syslib ghc</Literal> to use <Literal>PackedString</Literal>s.
367 </Para>
368
369 <Para>
370 The basic type and functions available are:
371
372 <ProgramListing>
373 data PackedString -- abstract
374
375 packString          :: [Char] -&#62; PackedString
376 packStringST        :: [Char] -&#62; ST s PackedString
377 packCBytesST        :: Int -&#62; Addr -&#62; ST s PackedString
378 packBytesForCST     :: [Char] -&#62; ST s (ByteArray Int)
379 byteArrayToPS       :: ByteArray Int -&#62; PackedString
380 unsafeByteArrayToPS :: ByteArray a   -&#62; Int -&#62; PackedString
381 psToByteArray       :: PackedString -&#62; ByteArray Int
382 psToByteArrayST     :: PackedString -&#62; ST s (ByteArray Int)
383
384 unpackPS        :: PackedString -&#62; [Char]
385 </ProgramListing>
386
387 </Para>
388
389 <Para>
390 We also provide a wad of list-manipulation-like functions:
391
392 <ProgramListing>
393 nilPS       :: PackedString
394 consPS      :: Char -&#62; PackedString -&#62; PackedString
395
396 headPS      :: PackedString -&#62; Char
397 tailPS      :: PackedString -&#62; PackedString
398 nullPS      :: PackedString -&#62; Bool
399 appendPS    :: PackedString -&#62; PackedString -&#62; PackedString
400 lengthPS    :: PackedString -&#62; Int
401 indexPS     :: PackedString -&#62; Int -&#62; Char
402             -- 0-origin indexing into the string
403 mapPS       :: (Char -&#62; Char) -&#62; PackedString -&#62; PackedString
404 filterPS    :: (Char -&#62; Bool) -&#62; PackedString -&#62; PackedString
405 foldlPS     :: (a -&#62; Char -&#62; a) -&#62; a -&#62; PackedString -&#62; a
406 foldrPS     :: (Char -&#62; a -&#62; a) -&#62; a -&#62; PackedString -&#62; a
407 takePS      :: Int -&#62; PackedString -&#62; PackedString
408 dropPS      :: Int -&#62; PackedString -&#62; PackedString
409 splitAtPS   :: Int -&#62; PackedString -&#62; (PackedString, PackedString)
410 takeWhilePS :: (Char -&#62; Bool) -&#62; PackedString -&#62; PackedString
411 dropWhilePS :: (Char -&#62; Bool) -&#62; PackedString -&#62; PackedString
412 spanPS      :: (Char -&#62; Bool) -&#62; PackedString -&#62; (PackedString, PackedString)
413 breakPS     :: (Char -&#62; Bool) -&#62; PackedString -&#62; (PackedString, PackedString)
414 linesPS     :: PackedString -&#62; [PackedString]
415 wordsPS     :: PackedString -&#62; [PackedString]
416 reversePS   :: PackedString -&#62; PackedString
417 concatPS    :: [PackedString] -&#62; PackedString
418 elemPS      :: Char -&#62; PackedString -&#62; Bool
419   -- Perl-style split&amp;join
420 splitPS     :: Char -&#62; PackedString -&#62; [PackedString]
421 splitWithPS :: (Char -&#62; Bool) -&#62; PackedString -&#62; [PackedString]
422 joinPS      :: PackedString -&#62; [PackedString] -&#62; PackedString
423
424 substrPS   :: PackedString -&#62; Int -&#62; Int -&#62; PackedString
425            -- pluck out a piece of a PackedString
426            -- start and end chars you want; both 0-origin-specified
427 </ProgramListing>
428
429 </Para>
430
431 </Sect2>
432
433 <Sect2 id="Set">
434 <Title>The <Literal>Set</Literal> type
435 </Title>
436
437 <Para>
438 <IndexTerm><Primary>Set module (misc syslib)</Primary></IndexTerm>
439 </Para>
440
441 <Para>
442 Our implementation of <Emphasis>sets</Emphasis> (key property: no duplicates) is just
443 a variant of the <Literal>FiniteMap</Literal> module.
444 </Para>
445
446 <Para>
447
448 <ProgramListing>
449 data Set        -- abstract
450                 -- instance of: Eq
451
452 emptySet        :: Set a
453 mkSet           :: Ord a =&#62; [a]  -&#62; Set a
454 setToList       :: Set a -&#62; [a]
455 unitSet         :: a -&#62; Set a
456 singletonSet    :: a -&#62; Set a  -- deprecated, use unitSet.
457
458 union           :: Ord a =&#62; Set a -&#62; Set a -&#62; Set a
459 unionManySets   :: Ord a =&#62; [Set a] -&#62; Set a
460 minusSet        :: Ord a =&#62; Set a -&#62; Set a -&#62; Set a
461 mapSet          :: Ord a =&#62; (b -&#62; a) -&#62; Set b -&#62; Set a
462 intersect       :: Ord a =&#62; Set a -&#62; Set a -&#62; Set a
463
464 elementOf       :: Ord a =&#62; a -&#62; Set a -&#62; Bool
465 isEmptySet      :: Set a -&#62; Bool
466
467 cardinality     :: Set a -&#62; Int
468 </ProgramListing>
469
470 </Para>
471
472 </Sect2>
473
474 <Sect2 id="BitSet">
475 <Title>The <Literal>BitSet</Literal> interface
476 </Title>
477
478 <Para>
479 <IndexTerm><Primary>Bitset interface (misc syslib)</Primary></IndexTerm>
480 </Para>
481
482 <Para>
483 Bit sets are a fast implementation of sets of integers ranging from 0
484 to one less than the number of bits in a machine word (typically 31).
485 If any element exceeds the maximum value for a particular machine
486 architecture, the results of these operations are undefined.  You have
487 been warned.
488 </Para>
489
490 <Para>
491
492 <ProgramListing>
493 data BitSet   -- abstract
494               -- instance of:
495
496 emptyBS       :: BitSet
497 mkBS          :: [Int] -&#62; BitSet
498 unitBS        :: Int -&#62; BitSet
499 unionBS       :: BitSet -&#62; BitSet -&#62; BitSet
500 minusBS       :: BitSet -&#62; BitSet -&#62; BitSet
501 isEmptyBS     :: BitSet -&#62; Bool
502 intersectBS   :: BitSet -&#62; BitSet -&#62; BitSet
503 elementBS     :: Int -&#62; BitSet -&#62; Bool
504 listBS        :: BitSet -&#62; [Int]
505 </ProgramListing>
506
507 </Para>
508
509 </Sect2>
510
511 <Sect2 id="Util">
512 <Title>The <Literal>Util</Literal> type
513 </Title>
514
515 <Para>
516 <IndexTerm><Primary>Util module (misc syslib)</Primary></IndexTerm>
517 </Para>
518
519 <Para>
520 Stuff that has been generally useful to use in writing the compiler.
521 Don't be too surprised if this stuff moves/gets-renamed/etc.
522 </Para>
523
524 <Para>
525
526 <ProgramListing>
527 -- general list processing
528 forall          :: (a -&#62; Bool) -&#62; [a] -&#62; Bool
529 exists          :: (a -&#62; Bool) -&#62; [a] -&#62; Bool
530
531 nOfThem         :: Int -&#62; a -&#62; [a]
532 lengthExceeds   :: [a] -&#62; Int -&#62; Bool
533 isSingleton     :: [a] -&#62; Bool
534
535 --paranoid zip'ing (equal length lists)
536 zipEqual        :: [a] -&#62; [b] -&#62; [(a,b)]
537 zipWithEqual    :: String -&#62; (a-&#62;b-&#62;c) -&#62; [a]-&#62;[b]-&#62;[c]
538 zipWith3Equal   :: String -&#62; (a-&#62;b-&#62;c-&#62;d) -&#62; [a]-&#62;[b]-&#62;[c]-&#62;[d]
539 zipWith4Equal   :: String -&#62; (a-&#62;b-&#62;c-&#62;d-&#62;e) -&#62; [a]-&#62;[b]-&#62;[c]-&#62;[d]-&#62;[e]
540 -- lazy in second argument
541 zipLazy :: [a] -&#62; [b] -&#62; [(a,b)]
542
543 mapAndUnzip :: (a -&#62; (b, c)) -&#62; [a] -&#62; ([b], [c])
544 mapAndUnzip3 :: (a -&#62; (b, c, d)) -&#62; [a] -&#62; ([b], [c], [d])
545
546 -- prefix and suffix matching on lists of characters.
547 startsWith :: {-prefix-}String -&#62; String -&#62; Maybe String
548 endsWith   :: {-suffix-}String -&#62; String -&#62; Maybe String
549
550 -- association lists
551 assoc       :: Eq a =&#62; String -&#62; [(a, b)] -&#62; a -&#62; b
552
553 -- duplicate handling
554 hasNoDups    :: Eq a =&#62; [a] -&#62; Bool
555 equivClasses :: (a -&#62; a -&#62; Ordering) -&#62; [a] -&#62; [[a]]
556 runs         :: (a -&#62; a -&#62; Bool)     -&#62; [a] -&#62; [[a]]
557 removeDups   :: (a -&#62; a -&#62; Ordering) -&#62; [a] -&#62; ([a], [[a]])
558
559 -- sorting (don't complain of no choice...)
560 quicksort          :: (a -&#62; a -&#62; Bool)     -&#62; [a] -&#62; [a]
561 sortLt             :: (a -&#62; a -&#62; Bool)     -&#62; [a] -&#62; [a]
562 stableSortLt       :: (a -&#62; a -&#62; Bool)     -&#62; [a] -&#62; [a]
563 mergesort          :: (a -&#62; a -&#62; _CMP_TAG) -&#62; [a] -&#62; [a]
564 mergeSort          :: Ord a =&#62; [a] -&#62; [a]
565 naturalMergeSort   :: Ord a =&#62; [a] -&#62; [a]
566 mergeSortLe        :: Ord a =&#62; [a] -&#62; [a]
567 naturalMergeSortLe :: Ord a =&#62; [a] -&#62; [a]
568
569 -- transitive closures
570 transitiveClosure :: (a -&#62; [a])         -- Successor function
571                   -&#62; (a -&#62; a -&#62; Bool)   -- Equality predicate
572                   -&#62; [a]
573                   -&#62; [a]                -- The transitive closure
574
575 -- accumulating (Left, Right, Bi-directional)
576 mapAccumL :: (acc -&#62; x -&#62; (acc, y))
577                         -- Function of elt of input list and
578                         -- accumulator, returning new accumulator and
579                         -- elt of result list
580           -&#62; acc        -- Initial accumulator
581           -&#62; [x]        -- Input list
582           -&#62; (acc, [y]) -- Final accumulator and result list
583
584 mapAccumR :: (acc -&#62; x -&#62; (acc, y)) -&#62; acc -&#62; [x] -&#62; (acc, [y])
585
586 mapAccumB :: (accl -&#62; accr -&#62; x -&#62; (accl, accr,y))
587           -&#62; accl -&#62; accr -&#62; [x]
588           -&#62; (accl, accr, [y])
589
590 --list comparison with explicit element comparer.
591 cmpList :: (a -&#62; a -&#62; Ordering) -&#62; [a] -&#62; [a] -&#62; Ordering
592
593 -- pairs
594 applyToPair :: ((a -&#62; c), (b -&#62; d)) -&#62; (a, b) -&#62; (c, d)
595 applyToFst  :: (a -&#62; c) -&#62; (a, b) -&#62; (c, b)
596 applyToSnd  :: (b -&#62; d) -&#62; (a, b) -&#62; (a, d)
597 foldPair    :: (a-&#62;a-&#62;a, b-&#62;b-&#62;b) -&#62; (a, b) -&#62; [(a, b)] -&#62; (a, b)
598 unzipWith   :: (a -&#62; b -&#62; c) -&#62; [(a, b)] -&#62; [c]
599 </ProgramListing>
600
601 </Para>
602
603 </Sect2>
604
605 </Sect1>
606
607 <Sect1 id="C-interfaces">
608 <Title>Interfaces to C libraries
609 </Title>
610
611 <Para>
612 <IndexTerm><Primary>C library interfaces</Primary></IndexTerm>
613 <IndexTerm><Primary>interfaces, C library</Primary></IndexTerm>
614 </Para>
615
616 <Para>
617 The GHC system library (<Literal>-syslib misc</Literal>) also provides interfaces to
618 several useful C libraries, mostly from the GNU project.
619 </Para>
620
621 <Sect2 id="Readline">
622 <Title>The <Literal>Readline</Literal> interface
623 </Title>
624
625 <Para>
626 <IndexTerm><Primary>Readline library (misc syslib)</Primary></IndexTerm>
627 <IndexTerm><Primary>command-line editing library</Primary></IndexTerm>
628 </Para>
629
630 <Para>
631 (Darren Moffat supplied the <Literal>Readline</Literal> interface.)
632 </Para>
633
634 <Para>
635 The <Literal>Readline</Literal> module is a straightforward interface to the GNU
636 Readline library.  As such, you will need to look at the GNU
637 documentation (and have a <Literal>libreadline.a</Literal> file around somewhere&hellip;)
638 </Para>
639
640 <Para>
641 You'll need to link any Readlining program with <Literal>-lreadline -ltermcap</Literal>,
642 besides the usual <Literal>-syslib ghc</Literal> (and <Literal>-fhaskell-1.3</Literal>).
643 </Para>
644
645 <Para>
646 The main function you'll use is:
647
648 <ProgramListing>
649 readline :: String{-the prompt-} -&#62; IO String
650 </ProgramListing>
651
652 </Para>
653
654 <Para>
655 If you want to mess around with Full Readline G(l)ory, we also
656 provide:
657
658 <ProgramListing>
659 rlInitialize, addHistory,
660
661 rlBindKey, rlAddDefun, RlCallbackFunction(..),
662
663 rlGetLineBuffer, rlSetLineBuffer, rlGetPoint, rlSetPoint, rlGetEnd,
664 rlSetEnd, rlGetMark, rlSetMark, rlSetDone, rlPendingInput,
665
666 rlPrompt, rlTerminalName, rlSetReadlineName, rlGetReadlineName
667 </ProgramListing>
668
669 (All those names are just Haskellised versions of what you
670 will see in the GNU readline documentation.)
671 </Para>
672
673 </Sect2>
674
675 <Sect2 id="Regex">
676 <Title>The <Literal>Regex</Literal> and <Literal>MatchPS</Literal> interfaces
677 </Title>
678
679 <Para>
680 <IndexTerm><Primary>Regex library (misc syslib)</Primary></IndexTerm>
681 <IndexTerm><Primary>MatchPS library (misc syslib)</Primary></IndexTerm>
682 <IndexTerm><Primary>regular-expressions library</Primary></IndexTerm>
683 </Para>
684
685 <Para>
686 (Sigbjorn Finne supplied the regular-expressions interface.)
687 </Para>
688
689 <Para>
690 The <Literal>Regex</Literal> library provides quite direct interface to the GNU
691 regular-expression library, for doing manipulation on <Literal>PackedString</Literal>s.
692 You probably need to see the GNU documentation if you are operating at
693 this level.  Alternatively, you can use the simpler and higher-level
694 <Literal>RegexString</Literal> interface.
695 </Para>
696
697 <Para>
698 The datatypes and functions that <Literal>Regex</Literal> provides are:
699
700 <ProgramListing>
701 data PatBuffer  # just a bunch of bytes (mutable)
702
703 data REmatch
704  = REmatch (Array Int GroupBounds)  -- for $1, ... $n
705            GroupBounds              -- for $` (everything before match)
706            GroupBounds              -- for $&amp; (entire matched string)
707            GroupBounds              -- for $' (everything after)
708            GroupBounds              -- for $+ (matched by last bracket)
709
710 -- GroupBounds hold the interval where a group
711 -- matched inside a string, e.g.
712 --
713 -- matching "reg(exp)" "a regexp" returns the pair (5,7) for the
714 -- (exp) group. (PackedString indices start from 0)
715
716 type GroupBounds = (Int, Int)
717
718 re_compile_pattern
719         :: PackedString         -- pattern to compile
720         -&#62; Bool                 -- True &#60;=&#62; assume single-line mode
721         -&#62; Bool                 -- True &#60;=&#62; case-insensitive
722         -&#62; PrimIO PatBuffer
723
724 re_match :: PatBuffer           -- compiled regexp
725          -&#62; PackedString        -- string to match
726          -&#62; Int                 -- start position
727          -&#62; Bool                -- True &#60;=&#62; record results in registers
728          -&#62; PrimIO (Maybe REmatch)
729
730 -- Matching on 2 strings is useful when you're dealing with multiple
731 -- buffers, which is something that could prove useful for
732 -- PackedStrings, as we don't want to stuff the contents of a file
733 -- into one massive heap chunk, but load (smaller chunks) on demand.
734
735 re_match2 :: PatBuffer          -- 2-string version
736           -&#62; PackedString
737           -&#62; PackedString
738           -&#62; Int
739           -&#62; Int
740           -&#62; Bool
741           -&#62; PrimIO (Maybe REmatch)
742
743 re_search :: PatBuffer          -- compiled regexp
744           -&#62; PackedString       -- string to search
745           -&#62; Int                -- start index
746           -&#62; Int                -- stop index
747           -&#62; Bool               -- True &#60;=&#62; record results in registers
748           -&#62; PrimIO (Maybe REmatch)
749
750 re_search2 :: PatBuffer         -- Double buffer search
751            -&#62; PackedString
752            -&#62; PackedString
753            -&#62; Int               -- start index
754            -&#62; Int               -- range (?)
755            -&#62; Int               -- stop index
756            -&#62; Bool              -- True &#60;=&#62; results in registers
757            -&#62; PrimIO (Maybe REmatch)
758 </ProgramListing>
759
760 </Para>
761
762 <Para>
763 The <Literal>MatchPS</Literal> module provides Perl-like ``higher-level'' facilities
764 to operate on <Literal>PackedStrings</Literal>.  The regular expressions in
765 question are in Perl syntax.  The ``flags'' on various functions can
766 include: <Literal>i</Literal> for case-insensitive, <Literal>s</Literal> for single-line mode, and
767 <Literal>g</Literal> for global.  (It's probably worth your time to peruse the
768 source code&hellip;)
769 </Para>
770
771 <Para>
772
773 <ProgramListing>
774 matchPS :: PackedString    -- regexp
775         -&#62; PackedString    -- string to match
776         -&#62; [Char]          -- flags
777         -&#62; Maybe REmatch   -- info about what matched and where
778
779 searchPS :: PackedString    -- regexp
780          -&#62; PackedString    -- string to match
781          -&#62; [Char]          -- flags
782          -&#62; Maybe REmatch
783
784 -- Perl-like match-and-substitute:
785 substPS :: PackedString     -- regexp
786         -&#62; PackedString     -- replacement
787         -&#62; [Char]           -- flags
788         -&#62; PackedString     -- string
789         -&#62; PackedString
790
791 -- same as substPS, but no prefix and suffix:
792 replacePS :: PackedString  -- regexp
793           -&#62; PackedString  -- replacement
794           -&#62; [Char]        -- flags
795           -&#62; PackedString  -- string
796           -&#62; PackedString
797
798 match2PS :: PackedString   -- regexp
799          -&#62; PackedString   -- string1 to match
800          -&#62; PackedString   -- string2 to match
801          -&#62; [Char]         -- flags
802          -&#62; Maybe REmatch
803
804 search2PS :: PackedString  -- regexp
805           -&#62; PackedString  -- string to match
806           -&#62; PackedString  -- string to match
807           -&#62; [Char]        -- flags
808           -&#62; Maybe REmatch
809
810 -- functions to pull the matched pieces out of an REmatch:
811
812 getMatchesNo    :: REmatch -&#62; Int
813 getMatchedGroup :: REmatch -&#62; Int -&#62; PackedString -&#62; PackedString
814 getWholeMatch   :: REmatch -&#62; PackedString -&#62; PackedString
815 getLastMatch    :: REmatch -&#62; PackedString -&#62; PackedString
816 getAfterMatch   :: REmatch -&#62; PackedString -&#62; PackedString
817
818 -- (reverse) brute-force string matching;
819 -- Perl equivalent is index/rindex:
820 findPS, rfindPS :: PackedString -&#62; PackedString -&#62; Maybe Int
821
822 -- Equivalent to Perl "chop" (off the last character, if any):
823 chopPS :: PackedString -&#62; PackedString
824
825 -- matchPrefixPS: tries to match as much as possible of strA starting
826 -- from the beginning of strB (handy when matching fancy literals in
827 -- parsers):
828 matchPrefixPS :: PackedString -&#62; PackedString -&#62; Int
829 </ProgramListing>
830
831 </Para>
832
833 </Sect2>
834
835 <Sect2 id="RegexString">
836 <Title>The <Literal>RegexString</Literal> interface
837 </Title>
838
839 <Para>
840 <IndexTerm><Primary>RegexString library (misc syslib)</Primary></IndexTerm>
841 <IndexTerm><Primary>regular-expressions library</Primary></IndexTerm>
842 </Para>
843
844 <Para>
845 (Simon Marlow supplied the String Regex wrapper.)
846 </Para>
847
848 <Para>
849 For simple regular expression operations, the <Literal>Regex</Literal> library is a
850 little heavyweight.  <Literal>RegexString</Literal> permits regex matching on ordinary
851 Haskell <Literal>String</Literal>s.
852 </Para>
853
854 <Para>
855 The datatypes and functions that <Literal>RegexString</Literal> provides are:
856
857 <ProgramListing>
858 data Regex              -- a compiled regular expression
859
860 mkRegex
861         :: String       -- regexp to compile
862         -&#62; Regex        -- compiled regexp
863
864 matchRegex
865         :: Regex        -- compiled regexp
866         -&#62; String       -- string to match
867         -&#62; Maybe [String] -- text of $1, $2, ... (if matched)
868 </ProgramListing>
869
870 </Para>
871
872 </Sect2>
873
874 <Sect2 id="Socket">
875 <Title>Network-interface toolkit&mdash;<Literal>Socket</Literal> and <Literal>SocketPrim</Literal>
876 </Title>
877
878 <Para>
879 <IndexTerm><Primary>SocketPrim interface (misc syslib)</Primary></IndexTerm>
880 <IndexTerm><Primary>Socket interface (misc syslib)</Primary></IndexTerm>
881 <IndexTerm><Primary>network-interface library</Primary></IndexTerm>
882 <IndexTerm><Primary>sockets library</Primary></IndexTerm>
883 <IndexTerm><Primary>BSD sockets library</Primary></IndexTerm>
884 (Darren Moffat supplied the initial version of this library.)
885 </Para>
886
887 <Para>
888 Your best bet for documentation is to look at the code&mdash;really!&mdash;
889 normally in
890 <Literal>fptools/ghc/lib/misc/&lcub;BSD,Socket,SocketPrim</Literal>.lhs&rcub;.
891 </Para>
892
893 <Para>
894 The <Literal>BSD</Literal> module provides functions to get at
895 system-database info; pretty straightforward if you're into this sort of
896 thing:
897
898 <ProgramListing>
899 getHostName         :: IO String
900
901 getServiceByName    :: ServiceName -&#62; IO ServiceEntry
902 getServicePortNumber:: ServiceName -&#62; IO PortNumber
903 getServiceEntry     :: IO ServiceEntry
904 setServiceEntry     :: Bool -&#62; IO ()
905 endServiceEntry     :: IO ()
906
907 getProtocolByName   :: ProtocolName -&#62; IO ProtocolEntry
908 getProtocolByNumber :: ProtocolNumber -&#62; IO ProtcolEntry
909 getProtocolNumber   :: ProtocolName -&#62; ProtocolNumber
910 getProtocolEntry    :: IO ProtocolEntry
911 setProtocolEntry    :: Bool -&#62; IO ()
912 endProtocolEntry    :: IO ()
913
914 getHostByName       :: HostName -&#62; IO HostEntry
915 getHostByAddr       :: Family -&#62; HostAddress -&#62; IO HostEntry
916 getHostEntry        :: IO HostEntry
917 setHostEntry        :: Bool -&#62; IO ()
918 endHostEntry        :: IO ()
919 </ProgramListing>
920 </Para>
921
922 <Para>
923 The <Literal>SocketPrim</Literal> interface provides quite direct access to
924 the socket facilities in a BSD Unix system, including all the
925 complications.  We hope you don't need to use it!  See the source if
926 needed&hellip;
927 </Para>
928
929 <Para>
930 The <Literal>Socket</Literal> interface is a ``higher-level'' interface to
931 sockets, and it is what we recommend.  Please tell us if the facilities it
932 offers are inadequate to your task!
933 </Para>
934
935 <Para>
936 The interface is relatively modest:
937
938 <ProgramListing>
939 connectTo       :: Hostname -&#62; PortID -&#62; IO Handle
940 listenOn        :: PortID -&#62; IO Socket
941
942 accept          :: Socket -&#62; IO (Handle, HostName)
943 sendTo          :: Hostname -&#62; PortID -&#62; String -&#62; IO ()
944
945 recvFrom        :: Hostname -&#62; PortID -&#62; IO String
946 socketPort      :: Socket -&#62; IO PortID
947
948 data PortID     -- PortID is a non-abstract type
949   = Service String        -- Service Name eg "ftp"
950   | PortNumber PortNumber -- User defined Port Number
951   | UnixSocket String     -- Unix family socket in file system
952
953 type Hostname = String
954
955  -- 16-bit value (stored in network byte order).
956 data PortNumber
957  -- instance of: Eq, Num, Show.
958
959 mkPortNumber :: Int -&#62; PortNumber
960 </ProgramListing>
961 </Para>
962
963 <Para>
964 Various examples of networking Haskell code are provided in
965 </Para>
966
967 </Sect2>
968
969 <Sect2 id="Select">
970 <Title>The <Literal>Select</Literal> interface
971 </Title>
972
973 <Para>
974 <IndexTerm><Primary>Select interface (misc syslib)</Primary></IndexTerm>
975 </Para>
976
977 <Para>
978 The <Literal>Select</Literal> interface provides a Haskell wrapper for the <Literal>select()</Literal>
979 OS call supplied by many modern UNIX variants. <Literal>Select</Literal> exports the
980 following:
981 </Para>
982
983 <Para>
984
985 <ProgramListing>
986 type TimeOut = Maybe Int
987   -- Nothing =&#62; wait indefinitely.
988   -- Just x | x &#62;= 0    =&#62; block waiting for 'x' micro seconds.
989   --        | otherwise =&#62; block waiting for '-x' micro seconds.
990
991 hSelect :: [Handle]
992         -&#62; [Handle]
993         -&#62; [Handle]
994         -&#62; TimeOut
995         -&#62; IO SelectResult
996
997 type SelectResult
998  = ( [Handle]  -- input  handles ready
999    , [Handle]  -- output handles ready
1000    , [Handle]  -- exc.   handles ready
1001    )
1002 </ProgramListing>
1003
1004 </Para>
1005
1006 <Para>
1007 Here's an example of how it could be used:
1008 </Para>
1009
1010 <Para>
1011
1012 <ProgramListing>
1013 module Main(main) where
1014
1015 import Select
1016 import IO
1017
1018 main :: IO ()
1019 main = do
1020   hSetBuffering stdin NoBuffering
1021   putStrLn "waiting for input to appear"
1022   hSelect [stdin] [] [] Nothing
1023   putStrLn "input ready, let's try reading"
1024   x &#60;- getChar
1025   print x
1026 </ProgramListing>
1027
1028 </Para>
1029
1030 <Para>
1031 where the call to <Literal>hSelect</Literal> makes the process go to sleep
1032 until there's input available on <Literal>stdin</Literal>.
1033 </Para>
1034
1035 <Para>
1036 Notice that this particular use of <Literal>hSelect</Literal> is now really a no-op
1037 with GHC compiled code, as its implementation of IO will take care to
1038 avoid blocking the process (i.e., all running Haskell threads), and
1039 call <Literal>select()</Literal> for you, if needs be. However, <Literal>hSelect</Literal> exposes
1040 functionality that is useful in other contexts (e.g., you want to
1041 wait for input on two <Literal>Handles</Literal> for 3 seconds, but no longer.)
1042 </Para>
1043
1044 </Sect2>
1045
1046 </Sect1>