[project @ 1998-12-02 13:17:09 by simonm]
[ghc-hetmet.git] / ghc / docs / users_guide / libmisc.vsgml
1 %************************************************************************
2 %*                                                                      *
3 <sect1>Miscellaneous libraries
4 <label id="GHC-library">
5 <p>
6 <nidx>libraries, miscellaneous</nidx>
7 <nidx>misc, syslib</nidx>
8 %*                                                                      *
9 %************************************************************************
10
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 @-syslib misc@<nidx>-syslib misc option</nidx>.
14
15 %************************************************************************
16 %*                                                                      *
17 <sect2>The @Bag@ type
18 <label id="Bag">
19 <p>
20 <nidx>Bag module (GHC syslib)</nidx>
21 %*                                                                      *
22 %************************************************************************
23
24 A <em>bag</em> is an unordered collection of elements which may contain
25 duplicates.  To use, @import Bag@.
26
27 <tscreen><verb>
28 data Bag elt    -- abstract
29
30 emptyBag        :: Bag elt
31 unitBag         :: elt -> Bag elt
32
33 consBag         :: elt       -> Bag elt -> Bag elt
34 snocBag         :: Bag elt   -> elt     -> Bag elt
35
36 unionBags       :: Bag elt   -> Bag elt -> Bag elt
37 unionManyBags   :: [Bag elt] -> Bag elt
38
39 isEmptyBag      :: Bag elt   -> Bool
40 elemBag         :: Eq elt => elt -> Bag elt -> Bool
41
42 filterBag       :: (elt -> Bool) -> Bag elt -> Bag elt
43 partitionBag    :: (elt -> Bool) -> Bag elt-> (Bag elt, Bag elt)
44         -- returns the elements that do/don't satisfy the predicate
45
46 concatBag       :: Bag (Bag a) -> Bag a 
47 foldBag         :: (r -> r -> r) -> (a -> r) -> r -> Bag a -> r
48 mapBag          :: (a -> b) -> Bag a -> Bag b
49
50 listToBag       :: [elt] -> Bag elt
51 bagToList       :: Bag elt -> [elt]
52 </verb></tscreen>
53
54 %************************************************************************
55 %*                                                                      *
56 <sect2>The @FiniteMap@ type
57 <label id="FiniteMap">
58 <p>
59 <nidx>FiniteMap module (GHC syslib)</nidx>
60 %*                                                                      *
61 %************************************************************************
62
63 What functional programmers call a <em>finite map</em>, everyone else
64 calls a <em>lookup table</em>.
65
66 Out code is derived from that in this paper:
67 <quote>
68 S Adams
69 "Efficient sets: a balancing act"
70 Journal of functional programming 3(4) Oct 1993, pages 553-562
71 </quote>
72 Guess what?  The implementation uses balanced trees.
73
74 <tscreen><verb>
75 data FiniteMap key elt  -- abstract
76
77 --      BUILDING
78 emptyFM         :: FiniteMap key elt
79 unitFM          :: key -> elt -> FiniteMap key elt
80 listToFM        :: Ord key => [(key,elt)] -> FiniteMap key elt
81                         -- In the case of duplicates, the last is taken
82
83 --      ADDING AND DELETING
84                    -- Throws away any previous binding
85                    -- In the list case, the items are added starting with the
86                    -- first one in the list
87 addToFM         :: Ord key => FiniteMap key elt -> key -> elt  -> FiniteMap key elt
88 addListToFM     :: Ord key => FiniteMap key elt -> [(key,elt)] -> FiniteMap key elt
89
90                  -- Combines with previous binding
91                  -- In the combining function, the first argument is
92                  -- the "old" element, while the second is the "new" one.
93 addToFM_C       :: Ord key => (elt -> elt -> elt)
94                            -> FiniteMap key elt -> key -> elt  
95                            -> FiniteMap key elt
96 addListToFM_C   :: Ord key => (elt -> elt -> elt)
97                            -> FiniteMap key elt -> [(key,elt)] 
98                            -> FiniteMap key elt
99
100                  -- Deletion doesn't complain if you try to delete something
101                  -- which isn't there
102 delFromFM       :: Ord key => FiniteMap key elt -> key   -> FiniteMap key elt
103 delListFromFM   :: Ord key => FiniteMap key elt -> [key] -> FiniteMap key elt
104
105 --      COMBINING
106                  -- Bindings in right argument shadow those in the left
107 plusFM          :: Ord key => FiniteMap key elt -> FiniteMap key elt
108                            -> FiniteMap key elt
109
110                    -- Combines bindings for the same thing with the given function
111 plusFM_C        :: Ord key => (elt -> elt -> elt) 
112                            -> FiniteMap key elt -> FiniteMap key elt -> FiniteMap key elt
113
114 minusFM         :: Ord key => FiniteMap key elt -> FiniteMap key elt -> FiniteMap key elt
115                    -- (minusFM a1 a2) deletes from a1 any bindings which are bound in a2
116
117 intersectFM     :: Ord key => FiniteMap key elt -> FiniteMap key elt -> FiniteMap key elt 
118 intersectFM_C   :: Ord key => (elt -> elt -> elt)
119                            -> FiniteMap key elt -> FiniteMap key elt -> FiniteMap key elt 
120
121 --      MAPPING, FOLDING, FILTERING
122 foldFM          :: (key -> elt -> a -> a) -> a -> FiniteMap key elt -> a
123 mapFM           :: (key -> elt1 -> elt2) -> FiniteMap key elt1 -> FiniteMap key elt2
124 filterFM        :: Ord key => (key -> elt -> Bool) 
125                            -> FiniteMap key elt -> FiniteMap key elt
126
127 --      INTERROGATING
128 sizeFM          :: FiniteMap key elt -> Int
129 isEmptyFM       :: FiniteMap key elt -> Bool
130
131 elemFM          :: Ord key => key -> FiniteMap key elt -> Bool
132 lookupFM        :: Ord key => FiniteMap key elt -> key -> Maybe elt
133 lookupWithDefaultFM
134                 :: Ord key => FiniteMap key elt -> elt -> key -> elt
135                 -- lookupWithDefaultFM supplies a "default" elt
136                 -- to return for an unmapped key
137
138 --      LISTIFYING
139 fmToList        :: FiniteMap key elt -> [(key,elt)]
140 keysFM          :: FiniteMap key elt -> [key]
141 eltsFM          :: FiniteMap key elt -> [elt]
142 </verb></tscreen>
143
144 %************************************************************************
145 %*                                                                      *
146 <sect2>The @ListSetOps@ type
147 <label id="ListSetOps">
148 <p>
149 <nidx>ListSetOps module (GHC syslib)</nidx>
150 %*                                                                      *
151 %************************************************************************
152
153 Just a few set-sounding operations on lists.  If you want sets, use
154 the @Set@ module.
155
156 <tscreen><verb>
157 unionLists          :: Eq a => [a] -> [a] -> [a]
158 intersectLists      :: Eq a => [a] -> [a] -> [a]
159 minusList           :: Eq a => [a] -> [a] -> [a]
160 disjointLists       :: Eq a => [a] -> [a] -> Bool
161 intersectingLists   :: Eq a => [a] -> [a] -> Bool
162 </verb></tscreen>
163
164 %************************************************************************
165 %*                                                                      *
166 <sect2>The @Maybes@ type
167 <label id="Maybes">
168 <p>
169 <nidx>Maybes module (GHC syslib)</nidx>
170 %*                                                                      *
171 %************************************************************************
172
173 The @Maybe@ type is in the Haskell 1.4 prelude. Moreover, the
174 required @Maybe@ library provides many useful functions on
175 @Maybe@s. This (pre-1.3) module provides some more:
176
177 An @Either@-like type called @MaybeErr@:
178 <tscreen><verb>
179 data MaybeErr val err = Succeeded val | Failed err
180 </verb></tscreen>
181
182 Some operations to do with @Maybe@ (some commentary follows):
183 <tscreen><verb>
184 maybeToBool :: Maybe a -> Bool      -- Nothing => False; Just => True
185 allMaybes   :: [Maybe a] -> Maybe [a]
186 firstJust   :: [Maybe a] -> Maybe a
187 findJust    :: (a -> Maybe b) -> [a] -> Maybe b
188
189 assocMaybe  :: Eq a => [(a,b)] -> a -> Maybe b
190 mkLookupFun :: (key -> key -> Bool) -- Equality predicate
191             -> [(key,val)]          -- The assoc list
192             -> (key -> Maybe val)   -- A lookup fun to use
193 mkLookupFunDef :: (key -> key -> Bool)  -- Equality predicate
194                -> [(key,val)]           -- The assoc list
195                -> val                   -- Value to return on failure
196                -> key                   -- The key
197                -> val                   -- The corresponding value
198
199     -- a monad thing
200 thenMaybe   :: Maybe a -> (a -> Maybe b) -> Maybe b
201 returnMaybe :: a -> Maybe a
202 failMaybe   :: Maybe a
203 mapMaybe    :: (a -> Maybe b) -> [a] -> Maybe [b]
204 </verb></tscreen>
205
206 NB: @catMaybes@ which used to be here, is now available via the
207 standard @Maybe@ interface (@Maybe@ is an instance of @MonadPlus@).
208
209 @allMaybes@ collects a list of @Justs@ into a single @Just@, returning
210 @Nothing@ if there are any @Nothings@.
211
212 @firstJust@ takes a list of @Maybes@ and returns the
213 first @Just@ if there is one, or @Nothing@ otherwise.
214
215 @assocMaybe@ looks up in an association list, returning
216 @Nothing@ if it fails.
217
218 Now, some operations to do with @MaybeErr@ (comments follow):
219 <tscreen><verb>
220     -- a monad thing (surprise, surprise)
221 thenMaB   :: MaybeErr a err -> (a -> MaybeErr b err) -> MaybeErr b err
222 returnMaB :: val -> MaybeErr val err
223 failMaB   :: err -> MaybeErr val err
224
225 listMaybeErrs :: [MaybeErr val err] -> MaybeErr [val] [err]
226 foldlMaybeErrs :: (acc -> input -> MaybeErr acc err)
227                -> acc
228                -> [input]
229                -> MaybeErr acc [err]
230 </verb></tscreen>
231
232 @listMaybeErrs@ takes a list of @MaybeErrs@ and, if they all succeed,
233 returns a @Succeeded@ of a list of their values.  If any fail, it
234 returns a @Failed@ of the list of all the errors in the list.
235
236 @foldlMaybeErrs@ works along a list, carrying an accumulator; it
237 applies the given function to the accumulator and the next list item,
238 accumulating any errors that occur.
239
240 %************************************************************************
241 %*                                                                      *
242 <sect2>The @PackedString@ type
243 <label id="PackedString">
244 <p>
245 <nidx>PackedString module (GHC syslib)</nidx>
246 %*                                                                      *
247 %************************************************************************
248
249 You need to @import PackedString@ and heave in your
250 @-syslib ghc@ to use @PackedString@s.
251
252 The basic type and functions available are:
253 <tscreen><verb>
254 data PackedString -- abstract
255
256 packString          :: [Char] -> PackedString
257 packStringST        :: [Char] -> ST s PackedString
258 packCBytesST        :: Int -> Addr -> ST s PackedString
259 packBytesForCST     :: [Char] -> ST s (ByteArray Int)
260 byteArrayToPS       :: ByteArray Int -> PackedString
261 unsafeByteArrayToPS :: ByteArray a   -> Int -> PackedString
262 psToByteArray       :: PackedString -> ByteArray Int
263 psToByteArrayST     :: PackedString -> ST s (ByteArray Int)
264
265 unpackPS        :: PackedString -> [Char]
266 </verb></tscreen>
267
268 We also provide a wad of list-manipulation-like functions:
269 <tscreen><verb>
270 nilPS       :: PackedString
271 consPS      :: Char -> PackedString -> PackedString
272
273 headPS      :: PackedString -> Char
274 tailPS      :: PackedString -> PackedString
275 nullPS      :: PackedString -> Bool
276 appendPS    :: PackedString -> PackedString -> PackedString
277 lengthPS    :: PackedString -> Int
278 indexPS     :: PackedString -> Int -> Char
279             -- 0-origin indexing into the string
280 mapPS       :: (Char -> Char) -> PackedString -> PackedString
281 filterPS    :: (Char -> Bool) -> PackedString -> PackedString
282 foldlPS     :: (a -> Char -> a) -> a -> PackedString -> a
283 foldrPS     :: (Char -> a -> a) -> a -> PackedString -> a
284 takePS      :: Int -> PackedString -> PackedString
285 dropPS      :: Int -> PackedString -> PackedString
286 splitAtPS   :: Int -> PackedString -> (PackedString, PackedString)
287 takeWhilePS :: (Char -> Bool) -> PackedString -> PackedString
288 dropWhilePS :: (Char -> Bool) -> PackedString -> PackedString
289 spanPS      :: (Char -> Bool) -> PackedString -> (PackedString, PackedString)
290 breakPS     :: (Char -> Bool) -> PackedString -> (PackedString, PackedString)
291 linesPS     :: PackedString -> [PackedString]
292 wordsPS     :: PackedString -> [PackedString]
293 reversePS   :: PackedString -> PackedString
294 concatPS    :: [PackedString] -> PackedString
295 elemPS      :: Char -> PackedString -> Bool
296   -- Perl-style split&join
297 splitPS     :: Char -> PackedString -> [PackedString]
298 splitWithPS :: (Char -> Bool) -> PackedString -> [PackedString]
299 joinPS      :: PackedString -> [PackedString] -> PackedString
300
301 substrPS   :: PackedString -> Int -> Int -> PackedString
302            -- pluck out a piece of a PackedString
303            -- start and end chars you want; both 0-origin-specified
304 </verb></tscreen>
305
306 %************************************************************************
307 %*                                                                      *
308 <sect2>The @Pretty@ type
309 <label id="Pretty">
310 <p>
311 <nidx>Pretty module (GHC syslib)</nidx>
312 %*                                                                      *
313 %************************************************************************
314
315 This is the pretty-printer that is currently used in GHC:
316
317 <tscreen><verb>
318 type Pretty
319
320 ppShow          :: Int{-width-} -> Pretty -> [Char]
321
322 pp'SP           :: Pretty -- "comma space"
323 ppComma         :: Pretty -- ,
324 ppEquals        :: Pretty -- =
325 ppLbrack        :: Pretty -- [
326 ppLparen        :: Pretty -- (
327 ppNil           :: Pretty -- nothing
328 ppRparen        :: Pretty -- )
329 ppRbrack        :: Pretty -- ]
330 ppSP            :: Pretty -- space
331 ppSemi          :: Pretty -- ;
332
333 ppChar          :: Char -> Pretty
334 ppDouble        :: Double -> Pretty
335 ppFloat         :: Float -> Pretty
336 ppInt           :: Int -> Pretty
337 ppInteger       :: Integer -> Pretty
338 ppRational      :: Rational -> Pretty
339 ppStr           :: [Char] -> Pretty
340
341 ppAbove         :: Pretty -> Pretty -> Pretty
342 ppAboves        :: [Pretty] -> Pretty
343 ppBeside        :: Pretty -> Pretty -> Pretty
344 ppBesides       :: [Pretty] -> Pretty
345 ppCat           :: [Pretty] -> Pretty
346 ppHang          :: Pretty -> Int -> Pretty -> Pretty
347 ppInterleave    :: Pretty -> [Pretty] -> Pretty -- spacing between
348 ppIntersperse   :: Pretty -> [Pretty] -> Pretty -- no spacing between
349 ppNest          :: Int -> Pretty -> Pretty
350 ppSep           :: [Pretty] -> Pretty
351 </verb></tscreen>
352
353 %************************************************************************
354 %*                                                                      *
355 <sect2>The @Set@ type
356 <label id="Set">
357 <p>
358 <nidx>Set module (GHC syslib)</nidx>
359 %*                                                                      *
360 %************************************************************************
361
362 Our implementation of <em>sets</em> (key property: no duplicates) is just
363 a variant of the @FiniteMap@ module.
364
365 <tscreen><verb>
366 data Set        -- abstract
367                 -- instance of: Eq
368
369 emptySet        :: Set a
370 mkSet           :: Ord a => [a]  -> Set a
371 setToList       :: Set a -> [a]
372 unitSet         :: a -> Set a
373 singletonSet    :: a -> Set a  -- deprecated, use unitSet.
374
375 union           :: Ord a => Set a -> Set a -> Set a
376 unionManySets   :: Ord a => [Set a] -> Set a
377 minusSet        :: Ord a => Set a -> Set a -> Set a
378 mapSet          :: Ord a => (b -> a) -> Set b -> Set a
379 intersect       :: Ord a => Set a -> Set a -> Set a
380
381 elementOf       :: Ord a => a -> Set a -> Bool
382 isEmptySet      :: Set a -> Bool
383
384 cardinality     :: Set a -> Int
385
386 </verb></tscreen>
387
388 %************************************************************************
389 %*                                                                      *
390 <sect2>The @BitSet@ interface
391 <label id="BitSet">
392 <p>
393 <nidx>Bitset interface (GHC syslib)</nidx>
394 %*                                                                      *
395 %************************************************************************
396
397 Bit sets are a fast implementation of sets of integers ranging from 0
398 to one less than the number of bits in a machine word (typically 31).
399 If any element exceeds the maximum value for a particular machine
400 architecture, the results of these operations are undefined.  You have
401 been warned. 
402
403 <tscreen><verb>
404 data BitSet   -- abstract
405               -- instance of:
406
407 emptyBS       :: BitSet
408 mkBS          :: [Int] -> BitSet
409 unitBS        :: Int -> BitSet
410 unionBS       :: BitSet -> BitSet -> BitSet
411 minusBS       :: BitSet -> BitSet -> BitSet
412 isEmptyBS     :: BitSet -> Bool
413 intersectBS   :: BitSet -> BitSet -> BitSet
414 elementBS     :: Int -> BitSet -> Bool
415 listBS        :: BitSet -> [Int]
416 </verb></tscreen>
417
418 %************************************************************************
419 %*                                                                      *
420 <sect2>The @Util@ type
421 <label id="Util">
422 <p>
423 <nidx>Util module (GHC syslib)</nidx>
424 %*                                                                      *
425 %************************************************************************
426
427 Stuff that has been generally useful to use in writing the compiler.
428 Don't be too surprised if this stuff moves/gets-renamed/etc.
429
430 <tscreen><verb>
431 -- general list processing
432 forall          :: (a -> Bool) -> [a] -> Bool
433 exists          :: (a -> Bool) -> [a] -> Bool
434
435 nOfThem         :: Int -> a -> [a]
436 lengthExceeds   :: [a] -> Int -> Bool
437 isSingleton     :: [a] -> Bool
438
439 --paranoid zip'ing (equal length lists)
440 zipEqual        :: [a] -> [b] -> [(a,b)]
441 zipWithEqual    :: String -> (a->b->c) -> [a]->[b]->[c]
442 zipWith3Equal   :: String -> (a->b->c->d) -> [a]->[b]->[c]->[d]
443 zipWith4Equal   :: String -> (a->b->c->d->e) -> [a]->[b]->[c]->[d]->[e]
444 -- lazy in second argument
445 zipLazy :: [a] -> [b] -> [(a,b)]
446
447 mapAndUnzip :: (a -> (b, c)) -> [a] -> ([b], [c])
448 mapAndUnzip3 :: (a -> (b, c, d)) -> [a] -> ([b], [c], [d])
449
450 -- prefix and suffix matching on lists of characters.
451 startsWith :: {-prefix-}String -> String -> Maybe String
452 endsWith   :: {-suffix-}String -> String -> Maybe String
453
454 -- association lists
455 assoc       :: Eq a => String -> [(a, b)] -> a -> b
456
457 -- duplicate handling
458 hasNoDups    :: Eq a => [a] -> Bool
459 equivClasses :: (a -> a -> Ordering) -> [a] -> [[a]]
460 runs         :: (a -> a -> Bool)     -> [a] -> [[a]]
461 removeDups   :: (a -> a -> Ordering) -> [a] -> ([a], [[a]])
462
463 -- sorting (don't complain of no choice...)
464 quicksort          :: (a -> a -> Bool)     -> [a] -> [a]
465 sortLt             :: (a -> a -> Bool)     -> [a] -> [a]
466 stableSortLt       :: (a -> a -> Bool)     -> [a] -> [a]
467 mergesort          :: (a -> a -> _CMP_TAG) -> [a] -> [a]
468 mergeSort          :: Ord a => [a] -> [a]
469 naturalMergeSort   :: Ord a => [a] -> [a]
470 mergeSortLe        :: Ord a => [a] -> [a]
471 naturalMergeSortLe :: Ord a => [a] -> [a]
472
473 -- transitive closures
474 transitiveClosure :: (a -> [a])         -- Successor function
475                   -> (a -> a -> Bool)   -- Equality predicate
476                   -> [a] 
477                   -> [a]                -- The transitive closure
478
479 -- accumulating (Left, Right, Bi-directional)
480 mapAccumL :: (acc -> x -> (acc, y))
481                         -- Function of elt of input list and
482                         -- accumulator, returning new accumulator and
483                         -- elt of result list
484           -> acc        -- Initial accumulator
485           -> [x]        -- Input list
486           -> (acc, [y]) -- Final accumulator and result list
487
488 mapAccumR :: (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y])
489
490 mapAccumB :: (accl -> accr -> x -> (accl, accr,y))
491           -> accl -> accr -> [x]
492           -> (accl, accr, [y])
493
494 --list comparison with explicit element comparer.
495 cmpList :: (a -> a -> Ordering) -> [a] -> [a] -> Ordering
496
497 -- pairs
498 applyToPair :: ((a -> c), (b -> d)) -> (a, b) -> (c, d)
499 applyToFst  :: (a -> c) -> (a, b) -> (c, b)
500 applyToSnd  :: (b -> d) -> (a, b) -> (a, d)
501 foldPair    :: (a->a->a, b->b->b) -> (a, b) -> [(a, b)] -> (a, b)
502 unzipWith   :: (a -> b -> c) -> [(a, b)] -> [c]
503 </verb></tscreen>
504
505 %************************************************************************
506 %*                                                                      *
507 <sect1>Interfaces to C libraries
508 <label id="C-interfaces">
509 <p>
510 <nidx>C library interfaces</nidx>
511 <nidx>interfaces, C library</nidx>
512 %*                                                                      *
513 %************************************************************************
514
515 The GHC system library (@-syslib ghc@) also provides interfaces to
516 several useful C libraries, mostly from the GNU project.
517
518 %************************************************************************
519 %*                                                                      *
520 <sect2>The @Readline@ interface
521 <label id="Readline">
522 <p>
523 <nidx>Readline library (GHC syslib)</nidx>
524 <nidx>command-line editing library</nidx>
525 %*                                                                      *
526 %************************************************************************
527
528 (Darren Moffat supplied the @Readline@ interface.)
529
530 The @Readline@ module is a straightforward interface to the GNU
531 Readline library.  As such, you will need to look at the GNU
532 documentation (and have a @libreadline.a@ file around somewhere...)
533
534 You'll need to link any Readlining program with @-lreadline -ltermcap@,
535 besides the usual @-syslib ghc@ (and @-fhaskell-1.3@).
536
537 The main function you'll use is:
538 <tscreen><verb>
539 readline :: String{-the prompt-} -> IO String
540 </verb></tscreen>
541
542 If you want to mess around with Full Readline G(l)ory, we also
543 provide:
544 <tscreen><verb>
545 rlInitialize, addHistory,
546
547 rlBindKey, rlAddDefun, RlCallbackFunction(..),
548
549 rlGetLineBuffer, rlSetLineBuffer, rlGetPoint, rlSetPoint, rlGetEnd,
550 rlSetEnd, rlGetMark, rlSetMark, rlSetDone, rlPendingInput,
551
552 rlPrompt, rlTerminalName, rlSetReadlineName, rlGetReadlineName
553 </verb></tscreen>
554 (All those names are just Haskellised versions of what you
555 will see in the GNU readline documentation.)
556
557 %************************************************************************
558 %*                                                                      *
559 <sect2>The @Regexp@ and @MatchPS@ interfaces
560 <label id="Regexp">
561 <p>
562 <nidx>Regex library (GHC syslib)</nidx>
563 <nidx>MatchPS library (GHC syslib)</nidx>
564 <nidx>regular-expressions library</nidx>
565 %*                                                                      *
566 %************************************************************************
567
568 (Sigbjorn Finne supplied the regular-expressions interface.)
569
570 The @Regex@ library provides quite direct interface to the GNU
571 regular-expression library, for doing manipulation on
572 @PackedString@s.  You probably need to see the GNU documentation
573 if you are operating at this level.
574
575 The datatypes and functions that @Regex@ provides are:
576 <tscreen><verb>
577 data PatBuffer  # just a bunch of bytes (mutable)
578
579 data REmatch
580  = REmatch (Array Int GroupBounds)  -- for $1, ... $n
581            GroupBounds              -- for $` (everything before match)
582            GroupBounds              -- for $& (entire matched string)
583            GroupBounds              -- for $' (everything after)
584            GroupBounds              -- for $+ (matched by last bracket)
585
586 -- GroupBounds hold the interval where a group
587 -- matched inside a string, e.g.
588 --
589 -- matching "reg(exp)" "a regexp" returns the pair (5,7) for the
590 -- (exp) group. (PackedString indices start from 0)
591
592 type GroupBounds = (Int, Int)
593
594 re_compile_pattern
595         :: PackedString         -- pattern to compile
596         -> Bool                 -- True <=> assume single-line mode
597         -> Bool                 -- True <=> case-insensitive
598         -> PrimIO PatBuffer
599
600 re_match :: PatBuffer           -- compiled regexp
601          -> PackedString        -- string to match
602          -> Int                 -- start position
603          -> Bool                -- True <=> record results in registers
604          -> PrimIO (Maybe REmatch)
605
606 -- Matching on 2 strings is useful when you're dealing with multiple
607 -- buffers, which is something that could prove useful for
608 -- PackedStrings, as we don't want to stuff the contents of a file
609 -- into one massive heap chunk, but load (smaller chunks) on demand.
610
611 re_match2 :: PatBuffer          -- 2-string version
612           -> PackedString
613           -> PackedString
614           -> Int
615           -> Int
616           -> Bool
617           -> PrimIO (Maybe REmatch)
618
619 re_search :: PatBuffer          -- compiled regexp
620           -> PackedString       -- string to search
621           -> Int                -- start index
622           -> Int                -- stop index
623           -> Bool               -- True <=> record results in registers
624           -> PrimIO (Maybe REmatch)
625
626 re_search2 :: PatBuffer         -- Double buffer search
627            -> PackedString
628            -> PackedString
629            -> Int               -- start index
630            -> Int               -- range (?)
631            -> Int               -- stop index
632            -> Bool              -- True <=> results in registers
633            -> PrimIO (Maybe REmatch)
634 </verb></tscreen>
635
636 The @MatchPS@ module provides Perl-like ``higher-level'' facilities
637 to operate on @PackedStrings@.  The regular expressions in
638 question are in Perl syntax.  The ``flags'' on various functions can
639 include: @i@ for case-insensitive, @s@ for single-line mode, and
640 @g@ for global.  (It's probably worth your time to peruse the
641 source code...)
642
643 <tscreen><verb>
644 matchPS :: PackedString    -- regexp
645         -> PackedString    -- string to match
646         -> [Char]          -- flags
647         -> Maybe REmatch   -- info about what matched and where
648
649 searchPS :: PackedString    -- regexp
650          -> PackedString    -- string to match
651          -> [Char]          -- flags
652          -> Maybe REmatch
653
654 -- Perl-like match-and-substitute:
655 substPS :: PackedString     -- regexp
656         -> PackedString     -- replacement
657         -> [Char]           -- flags
658         -> PackedString     -- string
659         -> PackedString
660
661 -- same as substPS, but no prefix and suffix:
662 replacePS :: PackedString  -- regexp
663           -> PackedString  -- replacement
664           -> [Char]        -- flags
665           -> PackedString  -- string
666           -> PackedString
667
668 match2PS :: PackedString   -- regexp
669          -> PackedString   -- string1 to match
670          -> PackedString   -- string2 to match
671          -> [Char]         -- flags
672          -> Maybe REmatch
673
674 search2PS :: PackedString  -- regexp
675           -> PackedString  -- string to match
676           -> PackedString  -- string to match
677           -> [Char]        -- flags
678           -> Maybe REmatch
679
680 -- functions to pull the matched pieces out of an REmatch:
681
682 getMatchesNo    :: REmatch -> Int
683 getMatchedGroup :: REmatch -> Int -> PackedString -> PackedString
684 getWholeMatch   :: REmatch -> PackedString -> PackedString
685 getLastMatch    :: REmatch -> PackedString -> PackedString
686 getAfterMatch   :: REmatch -> PackedString -> PackedString
687
688 -- (reverse) brute-force string matching;
689 -- Perl equivalent is index/rindex:
690 findPS, rfindPS :: PackedString -> PackedString -> Maybe Int
691
692 -- Equivalent to Perl "chop" (off the last character, if any):
693 chopPS :: PackedString -> PackedString
694
695 -- matchPrefixPS: tries to match as much as possible of strA starting
696 -- from the beginning of strB (handy when matching fancy literals in
697 -- parsers):
698 matchPrefixPS :: PackedString -> PackedString -> Int
699 </verb></tscreen>
700
701 %************************************************************************
702 %*                                                                      *
703 <sect2>Network-interface toolkit---@Socket@ and @SocketPrim@
704 <label id="Socket">
705 <p>
706 <nidx>SocketPrim interface (GHC syslib)</nidx>
707 <nidx>Socket interface (GHC syslib)</nidx>
708 <nidx>network-interface library</nidx>
709 <nidx>sockets library</nidx>
710 <nidx>BSD sockets library</nidx>
711 %*                                                                      *
712 %************************************************************************
713
714 (Darren Moffat supplied the network-interface toolkit.)
715
716 Your best bet for documentation is to look at the code---really!--- 
717 normally in @fptools/ghc/lib/misc/{BSD,Socket,SocketPrim@.lhs}.
718
719 The @BSD@ module provides functions to get at system-database info;
720 pretty straightforward if you're into this sort of thing:
721 <tscreen><verb>
722 getHostName         :: IO String
723
724 getServiceByName    :: ServiceName -> IO ServiceEntry
725 getServicePortNumber:: ServiceName -> IO PortNumber
726 getServiceEntry     :: IO ServiceEntry
727 setServiceEntry     :: Bool -> IO ()
728 endServiceEntry     :: IO ()
729
730 getProtocolByName   :: ProtocolName -> IO ProtocolEntry
731 getProtocolByNumber :: ProtocolNumber -> IO ProtcolEntry
732 getProtocolNumber   :: ProtocolName -> ProtocolNumber
733 getProtocolEntry    :: IO ProtocolEntry
734 setProtocolEntry    :: Bool -> IO ()
735 endProtocolEntry    :: IO ()
736
737 getHostByName       :: HostName -> IO HostEntry
738 getHostByAddr       :: Family -> HostAddress -> IO HostEntry
739 getHostEntry        :: IO HostEntry
740 setHostEntry        :: Bool -> IO ()
741 endHostEntry        :: IO ()
742 </verb></tscreen>
743
744 The @SocketPrim@ interface provides quite direct access to the
745 socket facilities in a BSD Unix system, including all the
746 complications.  We hope you don't need to use it!  See the source if
747 needed...
748
749 The @Socket@ interface is a ``higher-level'' interface to sockets,
750 and it is what we recommend.  Please tell us if the facilities it
751 offers are inadequate to your task!
752
753 The interface is relatively modest:
754 <tscreen><verb>
755 connectTo       :: Hostname -> PortID -> IO Handle
756 listenOn        :: PortID -> IO Socket
757
758 accept          :: Socket -> IO (Handle, HostName)
759 sendTo          :: Hostname -> PortID -> String -> IO ()
760
761 recvFrom        :: Hostname -> PortID -> IO String
762 socketPort      :: Socket -> IO PortID
763
764 data PortID     -- PortID is a non-abstract type
765   = Service String      -- Service Name eg "ftp"
766   | PortNumber Int      -- User defined Port Number
767   | UnixSocket String   -- Unix family socket in file system
768
769 type Hostname = String
770 </verb></tscreen>
771
772 Various examples of networking Haskell code are provided in
773 %@ghc/misc/examples/@, notably the @net???/Main.hs@ programs.