[project @ 1999-10-12 14:50:07 by simonmar]
[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 (misc 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 (misc 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 (misc 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 (misc 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 @Memo@ library
243 <label id="memo-library">
244 <p>
245 <nidx>Memo (misc syslib)</nidx>
246 %*                                                                      *
247 %************************************************************************
248
249 The @Memo@ library provides fast polymorphic memo functions using hash
250 tables.  The interface is:
251
252 <tscreen><verb>
253 memo :: (a -> b) -> a -> b
254 </verb></tscreen>
255
256 So, for example, @memo f@ is a version of @f@ that caches the results
257 of previous calls.  
258
259 The searching is very fast, being based on pointer equality.  One
260 consequence of this is that the caching will only be effective if
261 <em/exactly the same argument is passed again to the memoised
262 function/.  This means not just a copy of a previous argument, but the
263 same instance.  It's not useful to memoise integer functions using
264 this interface, because integers are generally copied a lot and two
265 instances of '27' are unlikely to refer to the same object.
266
267 This memoisation library works well when the keys are large (or even
268 infinite).
269
270 The memo table implementation uses weak pointers and stable names (see
271 the GHC/Hugs library document) to avoid space leaks and allow hashing
272 for arbitrary Haskell objects.  NOTE: while individual memo table
273 entries will be garbage collected if the associated key becomes
274 garbage, the memo table itself will not be collected if the function
275 becomes garbage.  We plan to fix this in a future version.
276
277 There's another version of @memo@ if you want to explicitly give a
278 size for the hash table (the default size is 1001 buckets):
279
280 <tscreen><verb>
281 memo_sized :: Int -> (a -> b) -> a -> b
282 </verb></tscreen>
283
284 %************************************************************************
285 %*                                                                      *
286 <sect2>The @PackedString@ type
287 <label id="PackedString">
288 <p>
289 <nidx>PackedString module (misc syslib)</nidx>
290 %*                                                                      *
291 %************************************************************************
292
293 You need to @import PackedString@ and heave in your
294 @-syslib ghc@ to use @PackedString@s.
295
296 The basic type and functions available are:
297 <tscreen><verb>
298 data PackedString -- abstract
299
300 packString          :: [Char] -> PackedString
301 packStringST        :: [Char] -> ST s PackedString
302 packCBytesST        :: Int -> Addr -> ST s PackedString
303 packBytesForCST     :: [Char] -> ST s (ByteArray Int)
304 byteArrayToPS       :: ByteArray Int -> PackedString
305 unsafeByteArrayToPS :: ByteArray a   -> Int -> PackedString
306 psToByteArray       :: PackedString -> ByteArray Int
307 psToByteArrayST     :: PackedString -> ST s (ByteArray Int)
308
309 unpackPS        :: PackedString -> [Char]
310 </verb></tscreen>
311
312 We also provide a wad of list-manipulation-like functions:
313 <tscreen><verb>
314 nilPS       :: PackedString
315 consPS      :: Char -> PackedString -> PackedString
316
317 headPS      :: PackedString -> Char
318 tailPS      :: PackedString -> PackedString
319 nullPS      :: PackedString -> Bool
320 appendPS    :: PackedString -> PackedString -> PackedString
321 lengthPS    :: PackedString -> Int
322 indexPS     :: PackedString -> Int -> Char
323             -- 0-origin indexing into the string
324 mapPS       :: (Char -> Char) -> PackedString -> PackedString
325 filterPS    :: (Char -> Bool) -> PackedString -> PackedString
326 foldlPS     :: (a -> Char -> a) -> a -> PackedString -> a
327 foldrPS     :: (Char -> a -> a) -> a -> PackedString -> a
328 takePS      :: Int -> PackedString -> PackedString
329 dropPS      :: Int -> PackedString -> PackedString
330 splitAtPS   :: Int -> PackedString -> (PackedString, PackedString)
331 takeWhilePS :: (Char -> Bool) -> PackedString -> PackedString
332 dropWhilePS :: (Char -> Bool) -> PackedString -> PackedString
333 spanPS      :: (Char -> Bool) -> PackedString -> (PackedString, PackedString)
334 breakPS     :: (Char -> Bool) -> PackedString -> (PackedString, PackedString)
335 linesPS     :: PackedString -> [PackedString]
336 wordsPS     :: PackedString -> [PackedString]
337 reversePS   :: PackedString -> PackedString
338 concatPS    :: [PackedString] -> PackedString
339 elemPS      :: Char -> PackedString -> Bool
340   -- Perl-style split&join
341 splitPS     :: Char -> PackedString -> [PackedString]
342 splitWithPS :: (Char -> Bool) -> PackedString -> [PackedString]
343 joinPS      :: PackedString -> [PackedString] -> PackedString
344
345 substrPS   :: PackedString -> Int -> Int -> PackedString
346            -- pluck out a piece of a PackedString
347            -- start and end chars you want; both 0-origin-specified
348 </verb></tscreen>
349
350 %************************************************************************
351 %*                                                                      *
352 <sect2>The @Set@ type
353 <label id="Set">
354 <p>
355 <nidx>Set module (misc syslib)</nidx>
356 %*                                                                      *
357 %************************************************************************
358
359 Our implementation of <em>sets</em> (key property: no duplicates) is just
360 a variant of the @FiniteMap@ module.
361
362 <tscreen><verb>
363 data Set        -- abstract
364                 -- instance of: Eq
365
366 emptySet        :: Set a
367 mkSet           :: Ord a => [a]  -> Set a
368 setToList       :: Set a -> [a]
369 unitSet         :: a -> Set a
370 singletonSet    :: a -> Set a  -- deprecated, use unitSet.
371
372 union           :: Ord a => Set a -> Set a -> Set a
373 unionManySets   :: Ord a => [Set a] -> Set a
374 minusSet        :: Ord a => Set a -> Set a -> Set a
375 mapSet          :: Ord a => (b -> a) -> Set b -> Set a
376 intersect       :: Ord a => Set a -> Set a -> Set a
377
378 elementOf       :: Ord a => a -> Set a -> Bool
379 isEmptySet      :: Set a -> Bool
380
381 cardinality     :: Set a -> Int
382
383 </verb></tscreen>
384
385 %************************************************************************
386 %*                                                                      *
387 <sect2>The @BitSet@ interface
388 <label id="BitSet">
389 <p>
390 <nidx>Bitset interface (misc syslib)</nidx>
391 %*                                                                      *
392 %************************************************************************
393
394 Bit sets are a fast implementation of sets of integers ranging from 0
395 to one less than the number of bits in a machine word (typically 31).
396 If any element exceeds the maximum value for a particular machine
397 architecture, the results of these operations are undefined.  You have
398 been warned. 
399
400 <tscreen><verb>
401 data BitSet   -- abstract
402               -- instance of:
403
404 emptyBS       :: BitSet
405 mkBS          :: [Int] -> BitSet
406 unitBS        :: Int -> BitSet
407 unionBS       :: BitSet -> BitSet -> BitSet
408 minusBS       :: BitSet -> BitSet -> BitSet
409 isEmptyBS     :: BitSet -> Bool
410 intersectBS   :: BitSet -> BitSet -> BitSet
411 elementBS     :: Int -> BitSet -> Bool
412 listBS        :: BitSet -> [Int]
413 </verb></tscreen>
414
415 %************************************************************************
416 %*                                                                      *
417 <sect2>The @Util@ type
418 <label id="Util">
419 <p>
420 <nidx>Util module (misc syslib)</nidx>
421 %*                                                                      *
422 %************************************************************************
423
424 Stuff that has been generally useful to use in writing the compiler.
425 Don't be too surprised if this stuff moves/gets-renamed/etc.
426
427 <tscreen><verb>
428 -- general list processing
429 forall          :: (a -> Bool) -> [a] -> Bool
430 exists          :: (a -> Bool) -> [a] -> Bool
431
432 nOfThem         :: Int -> a -> [a]
433 lengthExceeds   :: [a] -> Int -> Bool
434 isSingleton     :: [a] -> Bool
435
436 --paranoid zip'ing (equal length lists)
437 zipEqual        :: [a] -> [b] -> [(a,b)]
438 zipWithEqual    :: String -> (a->b->c) -> [a]->[b]->[c]
439 zipWith3Equal   :: String -> (a->b->c->d) -> [a]->[b]->[c]->[d]
440 zipWith4Equal   :: String -> (a->b->c->d->e) -> [a]->[b]->[c]->[d]->[e]
441 -- lazy in second argument
442 zipLazy :: [a] -> [b] -> [(a,b)]
443
444 mapAndUnzip :: (a -> (b, c)) -> [a] -> ([b], [c])
445 mapAndUnzip3 :: (a -> (b, c, d)) -> [a] -> ([b], [c], [d])
446
447 -- prefix and suffix matching on lists of characters.
448 startsWith :: {-prefix-}String -> String -> Maybe String
449 endsWith   :: {-suffix-}String -> String -> Maybe String
450
451 -- association lists
452 assoc       :: Eq a => String -> [(a, b)] -> a -> b
453
454 -- duplicate handling
455 hasNoDups    :: Eq a => [a] -> Bool
456 equivClasses :: (a -> a -> Ordering) -> [a] -> [[a]]
457 runs         :: (a -> a -> Bool)     -> [a] -> [[a]]
458 removeDups   :: (a -> a -> Ordering) -> [a] -> ([a], [[a]])
459
460 -- sorting (don't complain of no choice...)
461 quicksort          :: (a -> a -> Bool)     -> [a] -> [a]
462 sortLt             :: (a -> a -> Bool)     -> [a] -> [a]
463 stableSortLt       :: (a -> a -> Bool)     -> [a] -> [a]
464 mergesort          :: (a -> a -> _CMP_TAG) -> [a] -> [a]
465 mergeSort          :: Ord a => [a] -> [a]
466 naturalMergeSort   :: Ord a => [a] -> [a]
467 mergeSortLe        :: Ord a => [a] -> [a]
468 naturalMergeSortLe :: Ord a => [a] -> [a]
469
470 -- transitive closures
471 transitiveClosure :: (a -> [a])         -- Successor function
472                   -> (a -> a -> Bool)   -- Equality predicate
473                   -> [a] 
474                   -> [a]                -- The transitive closure
475
476 -- accumulating (Left, Right, Bi-directional)
477 mapAccumL :: (acc -> x -> (acc, y))
478                         -- Function of elt of input list and
479                         -- accumulator, returning new accumulator and
480                         -- elt of result list
481           -> acc        -- Initial accumulator
482           -> [x]        -- Input list
483           -> (acc, [y]) -- Final accumulator and result list
484
485 mapAccumR :: (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y])
486
487 mapAccumB :: (accl -> accr -> x -> (accl, accr,y))
488           -> accl -> accr -> [x]
489           -> (accl, accr, [y])
490
491 --list comparison with explicit element comparer.
492 cmpList :: (a -> a -> Ordering) -> [a] -> [a] -> Ordering
493
494 -- pairs
495 applyToPair :: ((a -> c), (b -> d)) -> (a, b) -> (c, d)
496 applyToFst  :: (a -> c) -> (a, b) -> (c, b)
497 applyToSnd  :: (b -> d) -> (a, b) -> (a, d)
498 foldPair    :: (a->a->a, b->b->b) -> (a, b) -> [(a, b)] -> (a, b)
499 unzipWith   :: (a -> b -> c) -> [(a, b)] -> [c]
500 </verb></tscreen>
501
502 %************************************************************************
503 %*                                                                      *
504 <sect1>Interfaces to C libraries
505 <label id="C-interfaces">
506 <p>
507 <nidx>C library interfaces</nidx>
508 <nidx>interfaces, C library</nidx>
509 %*                                                                      *
510 %************************************************************************
511
512 The GHC system library (@-syslib misc@) also provides interfaces to
513 several useful C libraries, mostly from the GNU project.
514
515 %************************************************************************
516 %*                                                                      *
517 <sect2>The @Readline@ interface
518 <label id="Readline">
519 <p>
520 <nidx>Readline library (misc syslib)</nidx>
521 <nidx>command-line editing library</nidx>
522 %*                                                                      *
523 %************************************************************************
524
525 (Darren Moffat supplied the @Readline@ interface.)
526
527 The @Readline@ module is a straightforward interface to the GNU
528 Readline library.  As such, you will need to look at the GNU
529 documentation (and have a @libreadline.a@ file around somewhere...)
530
531 You'll need to link any Readlining program with @-lreadline -ltermcap@,
532 besides the usual @-syslib ghc@ (and @-fhaskell-1.3@).
533
534 The main function you'll use is:
535 <tscreen><verb>
536 readline :: String{-the prompt-} -> IO String
537 </verb></tscreen>
538
539 If you want to mess around with Full Readline G(l)ory, we also
540 provide:
541 <tscreen><verb>
542 rlInitialize, addHistory,
543
544 rlBindKey, rlAddDefun, RlCallbackFunction(..),
545
546 rlGetLineBuffer, rlSetLineBuffer, rlGetPoint, rlSetPoint, rlGetEnd,
547 rlSetEnd, rlGetMark, rlSetMark, rlSetDone, rlPendingInput,
548
549 rlPrompt, rlTerminalName, rlSetReadlineName, rlGetReadlineName
550 </verb></tscreen>
551 (All those names are just Haskellised versions of what you
552 will see in the GNU readline documentation.)
553
554 %************************************************************************
555 %*                                                                      *
556 <sect2>The @Regex@ and @MatchPS@ interfaces
557 <label id="Regex">
558 <p>
559 <nidx>Regex library (misc syslib)</nidx>
560 <nidx>MatchPS library (misc syslib)</nidx>
561 <nidx>regular-expressions library</nidx>
562 %*                                                                      *
563 %************************************************************************
564
565 (Sigbjorn Finne supplied the regular-expressions interface.)
566
567 The @Regex@ library provides quite direct interface to the GNU
568 regular-expression library, for doing manipulation on @PackedString@s.
569 You probably need to see the GNU documentation if you are operating at
570 this level.  Alternatively, you can use the simpler and higher-level
571 @RegexString@ interface.
572
573 The datatypes and functions that @Regex@ provides are:
574 <tscreen><verb>
575 data PatBuffer  # just a bunch of bytes (mutable)
576
577 data REmatch
578  = REmatch (Array Int GroupBounds)  -- for $1, ... $n
579            GroupBounds              -- for $` (everything before match)
580            GroupBounds              -- for $& (entire matched string)
581            GroupBounds              -- for $' (everything after)
582            GroupBounds              -- for $+ (matched by last bracket)
583
584 -- GroupBounds hold the interval where a group
585 -- matched inside a string, e.g.
586 --
587 -- matching "reg(exp)" "a regexp" returns the pair (5,7) for the
588 -- (exp) group. (PackedString indices start from 0)
589
590 type GroupBounds = (Int, Int)
591
592 re_compile_pattern
593         :: PackedString         -- pattern to compile
594         -> Bool                 -- True <=> assume single-line mode
595         -> Bool                 -- True <=> case-insensitive
596         -> PrimIO PatBuffer
597
598 re_match :: PatBuffer           -- compiled regexp
599          -> PackedString        -- string to match
600          -> Int                 -- start position
601          -> Bool                -- True <=> record results in registers
602          -> PrimIO (Maybe REmatch)
603
604 -- Matching on 2 strings is useful when you're dealing with multiple
605 -- buffers, which is something that could prove useful for
606 -- PackedStrings, as we don't want to stuff the contents of a file
607 -- into one massive heap chunk, but load (smaller chunks) on demand.
608
609 re_match2 :: PatBuffer          -- 2-string version
610           -> PackedString
611           -> PackedString
612           -> Int
613           -> Int
614           -> Bool
615           -> PrimIO (Maybe REmatch)
616
617 re_search :: PatBuffer          -- compiled regexp
618           -> PackedString       -- string to search
619           -> Int                -- start index
620           -> Int                -- stop index
621           -> Bool               -- True <=> record results in registers
622           -> PrimIO (Maybe REmatch)
623
624 re_search2 :: PatBuffer         -- Double buffer search
625            -> PackedString
626            -> PackedString
627            -> Int               -- start index
628            -> Int               -- range (?)
629            -> Int               -- stop index
630            -> Bool              -- True <=> results in registers
631            -> PrimIO (Maybe REmatch)
632 </verb></tscreen>
633
634 The @MatchPS@ module provides Perl-like ``higher-level'' facilities
635 to operate on @PackedStrings@.  The regular expressions in
636 question are in Perl syntax.  The ``flags'' on various functions can
637 include: @i@ for case-insensitive, @s@ for single-line mode, and
638 @g@ for global.  (It's probably worth your time to peruse the
639 source code...)
640
641 <tscreen><verb>
642 matchPS :: PackedString    -- regexp
643         -> PackedString    -- string to match
644         -> [Char]          -- flags
645         -> Maybe REmatch   -- info about what matched and where
646
647 searchPS :: PackedString    -- regexp
648          -> PackedString    -- string to match
649          -> [Char]          -- flags
650          -> Maybe REmatch
651
652 -- Perl-like match-and-substitute:
653 substPS :: PackedString     -- regexp
654         -> PackedString     -- replacement
655         -> [Char]           -- flags
656         -> PackedString     -- string
657         -> PackedString
658
659 -- same as substPS, but no prefix and suffix:
660 replacePS :: PackedString  -- regexp
661           -> PackedString  -- replacement
662           -> [Char]        -- flags
663           -> PackedString  -- string
664           -> PackedString
665
666 match2PS :: PackedString   -- regexp
667          -> PackedString   -- string1 to match
668          -> PackedString   -- string2 to match
669          -> [Char]         -- flags
670          -> Maybe REmatch
671
672 search2PS :: PackedString  -- regexp
673           -> PackedString  -- string to match
674           -> PackedString  -- string to match
675           -> [Char]        -- flags
676           -> Maybe REmatch
677
678 -- functions to pull the matched pieces out of an REmatch:
679
680 getMatchesNo    :: REmatch -> Int
681 getMatchedGroup :: REmatch -> Int -> PackedString -> PackedString
682 getWholeMatch   :: REmatch -> PackedString -> PackedString
683 getLastMatch    :: REmatch -> PackedString -> PackedString
684 getAfterMatch   :: REmatch -> PackedString -> PackedString
685
686 -- (reverse) brute-force string matching;
687 -- Perl equivalent is index/rindex:
688 findPS, rfindPS :: PackedString -> PackedString -> Maybe Int
689
690 -- Equivalent to Perl "chop" (off the last character, if any):
691 chopPS :: PackedString -> PackedString
692
693 -- matchPrefixPS: tries to match as much as possible of strA starting
694 -- from the beginning of strB (handy when matching fancy literals in
695 -- parsers):
696 matchPrefixPS :: PackedString -> PackedString -> Int
697 </verb></tscreen>
698
699 %************************************************************************
700 %*                                                                      *
701 <sect2>The @RegexString@ interface
702 <label id="RegexString">
703 <p>
704 <nidx>RegexString library (misc syslib)</nidx>
705 <nidx>regular-expressions library</nidx>
706 %*                                                                      *
707 %************************************************************************
708
709 (Simon Marlow supplied the String Regex wrapper.)
710
711 For simple regular expression operations, the @Regex@ library is a
712 little heavyweight.  @RegexString@ permits regex matching on ordinary
713 Haskell @String@s.
714
715 The datatypes and functions that @RegexString@ provides are:
716 <tscreen><verb>
717 data Regex              -- a compiled regular expression
718
719 mkRegex
720         :: String       -- regexp to compile
721         -> Regex        -- compiled regexp
722
723 matchRegex
724         :: Regex        -- compiled regexp
725         -> String       -- string to match
726         -> Maybe [String] -- text of $1, $2, ... (if matched)
727 </verb></tscreen>
728
729 %************************************************************************
730 %*                                                                      *
731 <sect2>Network-interface toolkit---@Socket@ and @SocketPrim@
732 <label id="Socket">
733 <p>
734 <nidx>SocketPrim interface (misc syslib)</nidx>
735 <nidx>Socket interface (misc syslib)</nidx>
736 <nidx>network-interface library</nidx>
737 <nidx>sockets library</nidx>
738 <nidx>BSD sockets library</nidx>
739 %*                                                                      *
740 %************************************************************************
741
742 (Darren Moffat supplied the initial version of this library.)
743
744 Your best bet for documentation is to look at the code---really!--- 
745 normally in @fptools/ghc/lib/misc/{BSD,Socket,SocketPrim@.lhs}.
746
747 The @BSD@ module provides functions to get at system-database info;
748 pretty straightforward if you're into this sort of thing:
749 <tscreen><verb>
750 getHostName         :: IO String
751
752 getServiceByName    :: ServiceName -> IO ServiceEntry
753 getServicePortNumber:: ServiceName -> IO PortNumber
754 getServiceEntry     :: IO ServiceEntry
755 setServiceEntry     :: Bool -> IO ()
756 endServiceEntry     :: IO ()
757
758 getProtocolByName   :: ProtocolName -> IO ProtocolEntry
759 getProtocolByNumber :: ProtocolNumber -> IO ProtcolEntry
760 getProtocolNumber   :: ProtocolName -> ProtocolNumber
761 getProtocolEntry    :: IO ProtocolEntry
762 setProtocolEntry    :: Bool -> IO ()
763 endProtocolEntry    :: IO ()
764
765 getHostByName       :: HostName -> IO HostEntry
766 getHostByAddr       :: Family -> HostAddress -> IO HostEntry
767 getHostEntry        :: IO HostEntry
768 setHostEntry        :: Bool -> IO ()
769 endHostEntry        :: IO ()
770 </verb></tscreen>
771
772 The @SocketPrim@ interface provides quite direct access to the
773 socket facilities in a BSD Unix system, including all the
774 complications.  We hope you don't need to use it!  See the source if
775 needed...
776
777 The @Socket@ interface is a ``higher-level'' interface to sockets,
778 and it is what we recommend.  Please tell us if the facilities it
779 offers are inadequate to your task!
780
781 The interface is relatively modest:
782 <tscreen><verb>
783 connectTo       :: Hostname -> PortID -> IO Handle
784 listenOn        :: PortID -> IO Socket
785
786 accept          :: Socket -> IO (Handle, HostName)
787 sendTo          :: Hostname -> PortID -> String -> IO ()
788
789 recvFrom        :: Hostname -> PortID -> IO String
790 socketPort      :: Socket -> IO PortID
791
792 data PortID     -- PortID is a non-abstract type
793   = Service String        -- Service Name eg "ftp"
794   | PortNumber PortNumber -- User defined Port Number
795   | UnixSocket String     -- Unix family socket in file system
796
797 type Hostname = String
798
799  -- 16-bit value (stored in network byte order).
800 data PortNumber
801  -- instance of: Eq, Num, Show.
802
803 mkPortNumber :: Int -> PortNumber
804 </verb></tscreen>
805
806 Various examples of networking Haskell code are provided in
807 %@ghc/misc/examples/@, notably the @net???/Main.hs@ programs.
808
809 %************************************************************************
810 %*                                                                      *
811 <sect2>The @Select@ interface
812 <label id="Select">
813 <p>
814 <nidx>Select interface (misc syslib)</nidx>
815 %*                                                                      *
816 %************************************************************************
817
818 The <tt/Select/ interface provides a Haskell wrapper for the <tt/select()/
819 OS call supplied by many modern UNIX variants. <tt/Select/ exports the
820 following:
821
822 <tscreen><verb>
823 type TimeOut = Maybe Int
824   -- Nothing => wait indefinitely.
825   -- Just x | x >= 0    => block waiting for 'x' micro seconds.
826   --        | otherwise => block waiting for '-x' micro seconds.
827
828 hSelect :: [Handle]
829         -> [Handle]
830         -> [Handle]
831         -> TimeOut
832         -> IO SelectResult
833
834 type SelectResult 
835  = ( [Handle]  -- input  handles ready
836    , [Handle]  -- output handles ready
837    , [Handle]  -- exc.   handles ready
838    )
839
840 </verb></tscreen>
841
842 Here's an example of how it could be used:
843
844 <tscreen><verb>
845 module Main(main) where
846
847 import Select
848 import IO
849
850 main :: IO ()
851 main = do
852   hSetBuffering stdin NoBuffering
853   putStrLn "waiting for input to appear"
854   hSelect [stdin] [] [] Nothing
855   putStrLn "input ready, let's try reading"
856   x <- getChar
857   print x
858
859 </verb></tscreen>
860
861 where the call to <tt/hSelect/ makes the process go to sleep
862 until there's input available on <tt/stdin/.
863
864 Notice that this particular use of <tt/hSelect/ is now really a no-op
865 with GHC compiled code, as its implementation of IO will take care to
866 avoid blocking the process (i.e., all running Haskell threads), and
867 call <tt/select()/ for you, if needs be. However, <tt/hSelect/ exposes
868 functionality that is useful in other contexts (e.g., you want to 
869 wait for input on two <tt/Handles/ for 3 seconds, but no longer.)
870