1 %************************************************************************
3 \section[syslibs]{System libraries}
4 \index{system libraries}
5 \index{libraries, system}
7 %************************************************************************
9 We intend to provide more and more ready-to-use Haskell code, so that
10 every program doesn't have to invent everything from scratch.
12 At the moment, we supply a part of the HBC library, as well as the
13 beginnings of one of our own (``GHC library'').
15 If you provide a \tr{-syslib <name>}\index{-syslib <name> option} option,
16 then the interfaces for that library will come into scope (and may be
17 \tr{import}ed), and the code will be added in at link time.
19 %************************************************************************
21 \subsection[GHC-library]{The GHC system library}
25 %************************************************************************
27 We have started to put together a ``GHC system library.''
29 At the moment, the library is made of generally-useful bits of the
32 To use this library, just give a \tr{-syslib ghc}\index{-syslib ghc option}
33 option to GHC, both for compiling and linking.
35 %************************************************************************
37 \subsubsection[Bag]{The @Bag@ type}
38 \index{Bag module (GHC syslib)}
40 %************************************************************************
42 A {\em bag} is an unordered collection of elements which may contain
43 duplicates. To use, \tr{import Bag}.
47 unitBag :: elt -> Bag elt
49 unionBags :: Bag elt -> Bag elt -> Bag elt
50 unionManyBags :: [Bag elt] -> Bag elt
51 snocBag :: Bag elt -> elt -> Bag elt
53 elemBag :: Eq elt => elt -> Bag elt -> Bool
54 isEmptyBag :: Bag elt -> Bool
55 filterBag :: (elt -> Bool) -> Bag elt -> Bag elt
56 partitionBag :: (elt -> Bool) -> Bag elt-> (Bag elt, Bag elt)
57 -- returns the elements that do/don't satisfy the predicate
59 listToBag :: [elt] -> Bag elt
60 bagToList :: Bag elt -> [elt]
63 %************************************************************************
65 \subsubsection[BitSet]{The @BitSet@ type}
66 \index{BitSet module (GHC syslib)}
68 %************************************************************************
70 Bit sets are a fast implementation of sets of integers ranging from 0
71 to one less than the number of bits in a machine word (typically 31).
72 If any element exceeds the maximum value for a particular machine
73 architecture, the results of these operations are undefined. You have
74 been warned. [``If you put any safety checks in this code, I will have
78 mkBS :: [Int] -> BitSet
79 listBS :: BitSet -> [Int]
81 singletonBS :: Int -> BitSet
83 unionBS :: BitSet -> BitSet -> BitSet
84 minusBS :: BitSet -> BitSet -> BitSet
85 elementBS :: Int -> BitSet -> Bool
86 intersectBS :: BitSet -> BitSet -> BitSet
88 isEmptyBS :: BitSet -> Bool
91 %************************************************************************
93 \subsubsection[FiniteMap]{The @FiniteMap@ type}
94 \index{FiniteMap module (GHC syslib)}
96 %************************************************************************
98 What functional programmers call a {\em finite map}, everyone else
99 calls a {\em lookup table}.
101 Out code is derived from that in this paper:
104 "Efficient sets: a balancing act"
105 Journal of functional programming 3(4) Oct 1993, pages 553-562
107 Guess what? The implementation uses balanced trees.
111 emptyFM :: FiniteMap key elt
112 singletonFM :: key -> elt -> FiniteMap key elt
113 listToFM :: Ord key => [(key,elt)] -> FiniteMap key elt
114 -- In the case of duplicates, the last is taken
116 -- ADDING AND DELETING
117 -- Throws away any previous binding
118 -- In the list case, the items are added starting with the
119 -- first one in the list
120 addToFM :: Ord key => FiniteMap key elt -> key -> elt -> FiniteMap key elt
121 addListToFM :: Ord key => FiniteMap key elt -> [(key,elt)] -> FiniteMap key elt
123 -- Combines with previous binding
124 addToFM_C :: Ord key => (elt -> elt -> elt)
125 -> FiniteMap key elt -> key -> elt
127 addListToFM_C :: Ord key => (elt -> elt -> elt)
128 -> FiniteMap key elt -> [(key,elt)]
131 -- Deletion doesn't complain if you try to delete something
133 delFromFM :: Ord key => FiniteMap key elt -> key -> FiniteMap key elt
134 delListFromFM :: Ord key => FiniteMap key elt -> [key] -> FiniteMap key elt
137 -- Bindings in right argument shadow those in the left
138 plusFM :: Ord key => FiniteMap key elt -> FiniteMap key elt
141 -- Combines bindings for the same thing with the given function
142 plusFM_C :: Ord key => (elt -> elt -> elt)
143 -> FiniteMap key elt -> FiniteMap key elt -> FiniteMap key elt
145 minusFM :: Ord key => FiniteMap key elt -> FiniteMap key elt -> FiniteMap key elt
146 -- (minusFM a1 a2) deletes from a1 any bindings which are bound in a2
148 intersectFM :: Ord key => FiniteMap key elt -> FiniteMap key elt -> FiniteMap key elt
149 intersectFM_C :: Ord key => (elt -> elt -> elt)
150 -> FiniteMap key elt -> FiniteMap key elt -> FiniteMap key elt
152 -- MAPPING, FOLDING, FILTERING
153 foldFM :: (key -> elt -> a -> a) -> a -> FiniteMap key elt -> a
154 mapFM :: (key -> elt1 -> elt2) -> FiniteMap key elt1 -> FiniteMap key elt2
155 filterFM :: Ord key => (key -> elt -> Bool)
156 -> FiniteMap key elt -> FiniteMap key elt
159 sizeFM :: FiniteMap key elt -> Int
160 isEmptyFM :: FiniteMap key elt -> Bool
162 elemFM :: Ord key => key -> FiniteMap key elt -> Bool
163 lookupFM :: Ord key => FiniteMap key elt -> key -> Maybe elt
165 :: Ord key => FiniteMap key elt -> elt -> key -> elt
166 -- lookupWithDefaultFM supplies a "default" elt
167 -- to return for an unmapped key
170 fmToList :: FiniteMap key elt -> [(key,elt)]
171 keysFM :: FiniteMap key elt -> [key]
172 eltsFM :: FiniteMap key elt -> [elt]
175 %************************************************************************
177 \subsubsection[ListSetOps]{The @ListSetOps@ type}
178 \index{ListSetOps module (GHC syslib)}
180 %************************************************************************
182 Just a few set-sounding operations on lists. If you want sets, use
186 unionLists :: Eq a => [a] -> [a] -> [a]
187 intersectLists :: Eq a => [a] -> [a] -> [a]
188 minusList :: Eq a => [a] -> [a] -> [a]
189 disjointLists :: Eq a => [a] -> [a] -> Bool
190 intersectingLists :: Eq a => [a] -> [a] -> Bool
193 %************************************************************************
195 \subsubsection[Maybes]{The @Maybes@ type}
196 \index{Maybes module (GHC syslib)}
198 %************************************************************************
200 Note: a \tr{Maybe} type is nearly inevitable in Haskell~1.3.
201 You should use this module with \tr{-fhaskell-1.3}.
203 Two non-abstract types:
205 data Maybe a = Nothing | Just a -- Prelude; re-exported
206 data MaybeErr val err = Succeeded val | Failed err
209 Some operations to do with \tr{Maybe} (some commentary follows):
211 maybeToBool :: Maybe a -> Bool -- Nothing => False; Just => True
212 catMaybes :: [Maybe a] -> [a]
213 allMaybes :: [Maybe a] -> Maybe [a]
214 firstJust :: [Maybe a] -> Maybe a
215 findJust :: (a -> Maybe b) -> [a] -> Maybe b
217 assocMaybe :: Eq a => [(a,b)] -> a -> Maybe b
218 mkLookupFun :: (key -> key -> Bool) -- Equality predicate
219 -> [(key,val)] -- The assoc list
220 -> (key -> Maybe val) -- A lookup fun to use
223 thenMaybe :: Maybe a -> (a -> Maybe b) -> Maybe b
224 returnMaybe :: a -> Maybe a
226 mapMaybe :: (a -> Maybe b) -> [a] -> Maybe [b]
229 @catMaybes@ takes a list of @Maybe@s and returns a list of the
230 contents of all the @Just@s in it.
232 @allMaybes@ collects a list of @Justs@ into a single @Just@, returning
233 @Nothing@ if there are any @Nothings@.
235 @firstJust@ takes a list of @Maybes@ and returns the
236 first @Just@ if there is one, or @Nothing@ otherwise.
238 @assocMaybe@ looks up in an association list, returning
239 @Nothing@ if it fails.
241 Now, some operations to do with \tr{MaybeErr} (comments follow):
243 -- a monad thing (surprise, surprise)
244 thenMaB :: MaybeErr a err -> (a -> MaybeErr b err) -> MaybeErr b err
245 returnMaB :: val -> MaybeErr val err
246 failMaB :: err -> MaybeErr val err
248 listMaybeErrs :: [MaybeErr val err] -> MaybeErr [val] [err]
249 foldlMaybeErrs :: (acc -> input -> MaybeErr acc err)
252 -> MaybeErr acc [err]
255 @listMaybeErrs@ takes a list of @MaybeErrs@ and, if they all succeed,
256 returns a @Succeeded@ of a list of their values. If any fail, it
257 returns a @Failed@ of the list of all the errors in the list.
259 @foldlMaybeErrs@ works along a list, carrying an accumulator; it
260 applies the given function to the accumulator and the next list item,
261 accumulating any errors that occur.
263 %************************************************************************
265 \subsubsection[PackedString]{The @_PackedString@ type}
266 \index{PackedString module (GHC syslib)}
268 %************************************************************************
270 The type \tr{_PackedString} is built-in, i.e., no
271 special action (other than a \tr{-fglasgow-exts} flag) is required to
274 The documentation here describes the {\em built-in} functions.
276 You may also access this code as a system library and {\em not} use
277 the \tr{-fglasgow-exts} flag. Just do \tr{import PackedString},
278 heave in your \tr{-syslib ghc}, and drop off the leading underscores
281 We still may change this interface (again).
283 The basic type and functions which are available are:
287 _packString :: [Char] -> _PackedString
288 _packStringST :: [Char] -> _ST s _PackedString
289 _packCString :: _Addr -> _PackedString
290 _packCBytes :: Int -> _Addr -> _PackedString
291 _packCBytesST :: Int -> _Addr -> _ST s _PackedString
292 _packBytesForC :: [Char] -> _ByteArray Int
293 _packBytesForCST :: [Char] -> _ST s (_ByteArray Int)
294 _byteArrayToPS :: _ByteArray Int -> _PackedString
295 _psToByteArray :: _PackedString -> _ByteArray Int
297 _unpackPS :: _PackedString -> [Char]
300 We also provide a wad of list-manipulation-like functions:
302 _nilPS :: _PackedString
303 _consPS :: Char -> _PackedString -> _PackedString
305 _headPS :: _PackedString -> Char
306 _tailPS :: _PackedString -> _PackedString
307 _nullPS :: _PackedString -> Bool
308 _appendPS :: _PackedString -> _PackedString -> _PackedString
309 _lengthPS :: _PackedString -> Int
310 _indexPS :: _PackedString -> Int -> Char
311 -- 0-origin indexing into the string
312 _mapPS :: (Char -> Char) -> _PackedString -> _PackedString {-or String?-}
313 _filterPS :: (Char -> Bool) -> _PackedString -> _PackedString {-or String?-}
314 _foldlPS :: (a -> Char -> a) -> a -> _PackedString -> a
315 _foldrPS :: (Char -> a -> a) -> a -> _PackedString -> a
316 _takePS :: Int -> _PackedString -> _PackedString
317 _dropPS :: Int -> _PackedString -> _PackedString
318 _splitAtPS :: Int -> _PackedString -> (_PackedString, _PackedString)
319 _takeWhilePS:: (Char -> Bool) -> _PackedString -> _PackedString
320 _dropWhilePS:: (Char -> Bool) -> _PackedString -> _PackedString
321 _spanPS :: (Char -> Bool) -> _PackedString -> (_PackedString, _PackedString)
322 _breakPS :: (Char -> Bool) -> _PackedString -> (_PackedString, _PackedString)
323 _linesPS :: _PackedString -> [_PackedString]
324 _wordsPS :: _PackedString -> [_PackedString]
325 _reversePS :: _PackedString -> _PackedString
326 _concatPS :: [_PackedString] -> _PackedString
328 _substrPS :: _PackedString -> Int -> Int -> _PackedString
329 -- pluck out a piece of a _PS
330 -- start and end chars you want; both 0-origin-specified
333 %************************************************************************
335 \subsubsection[Pretty]{The @Pretty@ type}
336 \index{Pretty module (GHC syslib)}
338 %************************************************************************
340 This is the pretty-printer that we use in GHC.
345 ppShow :: Int{-width-} -> Pretty -> [Char]
347 pp'SP :: Pretty -- "comma space"
348 ppComma :: Pretty -- ,
349 ppEquals :: Pretty -- =
350 ppLbrack :: Pretty -- [
351 ppLparen :: Pretty -- (
352 ppNil :: Pretty -- nothing
353 ppRparen :: Pretty -- )
354 ppRbrack :: Pretty -- ]
355 ppSP :: Pretty -- space
356 ppSemi :: Pretty -- ;
358 ppChar :: Char -> Pretty
359 ppDouble :: Double -> Pretty
360 ppFloat :: Float -> Pretty
361 ppInt :: Int -> Pretty
362 ppInteger :: Integer -> Pretty
363 ppRational :: Rational -> Pretty
364 ppStr :: [Char] -> Pretty
366 ppAbove :: Pretty -> Pretty -> Pretty
367 ppAboves :: [Pretty] -> Pretty
368 ppBeside :: Pretty -> Pretty -> Pretty
369 ppBesides :: [Pretty] -> Pretty
370 ppCat :: [Pretty] -> Pretty
371 ppHang :: Pretty -> Int -> Pretty -> Pretty
372 ppInterleave :: Pretty -> [Pretty] -> Pretty -- spacing between
373 ppIntersperse :: Pretty -> [Pretty] -> Pretty -- no spacing between
374 ppNest :: Int -> Pretty -> Pretty
375 ppSep :: [Pretty] -> Pretty
378 %************************************************************************
380 \subsubsection[Set]{The @Set@ type}
381 \index{Set module (GHC syslib)}
383 %************************************************************************
385 Our implementation of {\em sets} (key property: no duplicates) is just
386 a variant of the \tr{FiniteMap} module.
389 mkSet :: Ord a => [a] -> Set a
390 setToList :: Set a -> [a]
392 singletonSet :: a -> Set a
394 union :: Ord a => Set a -> Set a -> Set a
395 unionManySets :: Ord a => [Set a] -> Set a
396 intersect :: Ord a => Set a -> Set a -> Set a
397 minusSet :: Ord a => Set a -> Set a -> Set a
398 mapSet :: Ord a => (b -> a) -> Set b -> Set a
400 elementOf :: Ord a => a -> Set a -> Bool
401 isEmptySet :: Set a -> Bool
404 %************************************************************************
406 \subsubsection[Util]{The @Util@ type}
407 \index{Util module (GHC syslib)}
409 %************************************************************************
411 Stuff that has been useful to use in writing the compiler. Don't be
412 too surprised if this stuff moves/gets-renamed/etc.
415 -- general list processing
416 forall :: (a -> Bool) -> [a] -> Bool
417 exists :: (a -> Bool) -> [a] -> Bool
418 zipEqual :: [a] -> [b] -> [(a,b)]
419 nOfThem :: Int -> a -> [a]
420 lengthExceeds :: [a] -> Int -> Bool
421 isSingleton :: [a] -> Bool
424 assoc :: Eq a => String -> [(a, b)] -> a -> b
426 -- duplicate handling
427 hasNoDups :: Eq a => [a] -> Bool
428 equivClasses :: (a -> a -> _CMP_TAG) -> [a] -> [[a]]
429 runs :: (a -> a -> Bool) -> [a] -> [[a]]
430 removeDups :: (a -> a -> _CMP_TAG) -> [a] -> ([a], [[a]])
432 -- sorting (don't complain of no choice...)
433 quicksort :: (a -> a -> Bool) -> [a] -> [a]
434 sortLt :: (a -> a -> Bool) -> [a] -> [a]
435 stableSortLt :: (a -> a -> Bool) -> [a] -> [a]
436 mergesort :: (a -> a -> _CMP_TAG) -> [a] -> [a]
437 mergeSort :: Ord a => [a] -> [a]
438 naturalMergeSort :: Ord a => [a] -> [a]
439 mergeSortLe :: Ord a => [a] -> [a]
440 naturalMergeSortLe :: Ord a => [a] -> [a]
442 -- transitive closures
443 transitiveClosure :: (a -> [a]) -- Successor function
444 -> (a -> a -> Bool) -- Equality predicate
446 -> [a] -- The transitive closure
448 -- accumulating (Left, Right, Bi-directional)
449 mapAccumL :: (acc -> x -> (acc, y))
450 -- Function of elt of input list and
451 -- accumulator, returning new accumulator and
452 -- elt of result list
453 -> acc -- Initial accumulator
455 -> (acc, [y]) -- Final accumulator and result list
457 mapAccumR :: (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y])
459 mapAccumB :: (accl -> accr -> x -> (accl, accr,y))
460 -> accl -> accr -> [x]
464 cmpString :: String -> String -> _CMP_TAG
466 -- this type is built-in
467 data _CMP_TAG = _LT | _EQ | _GT
470 applyToPair :: ((a -> c), (b -> d)) -> (a, b) -> (c, d)
471 applyToFst :: (a -> c) -> (a, b) -> (c, b)
472 applyToSnd :: (b -> d) -> (a, b) -> (a, d)
473 foldPair :: (a->a->a, b->b->b) -> (a, b) -> [(a, b)] -> (a, b)
474 unzipWith :: (a -> b -> c) -> [(a, b)] -> [c]
477 %************************************************************************
479 \subsection[C-interfaces]{Interfaces to C libraries}
480 \index{C library interfaces}
481 \index{interfaces, C library}
483 %************************************************************************
485 The GHC system library (\tr{-syslib ghc}) also provides interfaces to
486 several useful C libraries, mostly from the GNU project.
488 %************************************************************************
490 \subsubsection[Readline]{The @Readline@ interface}
491 \index{Readline library (GHC syslib)}
492 \index{command-line editing library}
494 %************************************************************************
496 (Darren Moffat supplied the \tr{Readline} interface.)
498 The \tr{Readline} module is a straightforward interface to the GNU
499 Readline library. As such, you will need to look at the GNU
500 documentation (and have a \tr{libreadline.a} file around somewhere...)
502 You'll need to link any Readlining program with \tr{-lreadline -ltermcap},
503 besides the usual \tr{-syslib ghc} (and \tr{-fhaskell-1.3}).
505 The main function you'll use is:
507 readline :: String{-the prompt-} -> IO String
510 If you want to mess around with Full Readline G(l)ory, we also
513 rlInitialize, addHistory,
515 rlBindKey, rlAddDefun, RlCallbackFunction(..),
517 rlGetLineBuffer, rlSetLineBuffer, rlGetPoint, rlSetPoint, rlGetEnd,
518 rlSetEnd, rlGetMark, rlSetMark, rlSetDone, rlPendingInput,
520 rlPrompt, rlTerminalName, rlSetReadlineName, rlGetReadlineName
522 (All those names are just Haskellised versions of what you
523 will see in the GNU readline documentation.)
525 %************************************************************************
527 \subsubsection[Regexp]{The @Regexp@ and @MatchPS@ interfaces}
528 \index{Regex library (GHC syslib)}
529 \index{MatchPS library (GHC syslib)}
530 \index{regular-expressions library}
532 %************************************************************************
534 (Sigbjorn Finne supplied the regular-expressions interface.)
536 The \tr{Regex} library provides quite direct interface to the GNU
537 regular-expression library, for doing manipulation on
538 \tr{_PackedString}s. You probably need to see the GNU documentation
539 if you are operating at this level.
541 The datatypes and functions that \tr{Regex} provides are:
543 data PatBuffer # just a bunch of bytes (mutable)
546 = REmatch (Array Int GroupBounds) -- for $1, ... $n
547 GroupBounds -- for $` (everything before match)
548 GroupBounds -- for $& (entire matched string)
549 GroupBounds -- for $' (everything after)
550 GroupBounds -- for $+ (matched by last bracket)
552 -- GroupBounds hold the interval where a group
553 -- matched inside a string, e.g.
555 -- matching "reg(exp)" "a regexp" returns the pair (5,7) for the
556 -- (exp) group. (_PackedString indices start from 0)
558 type GroupBounds = (Int, Int)
561 :: _PackedString -- pattern to compile
562 -> Bool -- True <=> assume single-line mode
563 -> Bool -- True <=> case-insensitive
566 re_match :: PatBuffer -- compiled regexp
567 -> _PackedString -- string to match
568 -> Int -- start position
569 -> Bool -- True <=> record results in registers
570 -> PrimIO (Maybe REmatch)
572 -- Matching on 2 strings is useful when you're dealing with multiple
573 -- buffers, which is something that could prove useful for
574 -- PackedStrings, as we don't want to stuff the contents of a file
575 -- into one massive heap chunk, but load (smaller chunks) on demand.
577 re_match2 :: PatBuffer -- 2-string version
583 -> PrimIO (Maybe REmatch)
585 re_search :: PatBuffer -- compiled regexp
586 -> _PackedString -- string to search
587 -> Int -- start index
589 -> Bool -- True <=> record results in registers
590 -> PrimIO (Maybe REmatch)
592 re_search2 :: PatBuffer -- Double buffer search
595 -> Int -- start index
598 -> Bool -- True <=> results in registers
599 -> PrimIO (Maybe REmatch)
602 The \tr{MatchPS} module provides Perl-like ``higher-level'' facilities
603 to operate on \tr{_PackedStrings}. The regular expressions in
604 question are in Perl syntax. The ``flags'' on various functions can
605 include: \tr{i} for case-insensitive, \tr{s} for single-line mode, and
606 \tr{g} for global. (It's probably worth your time to peruse the
610 matchPS :: _PackedString -- regexp
611 -> _PackedString -- string to match
613 -> Maybe REmatch -- info about what matched and where
615 searchPS :: _PackedString -- regexp
616 -> _PackedString -- string to match
620 -- Perl-like match-and-substitute:
621 substPS :: _PackedString -- regexp
622 -> _PackedString -- replacement
624 -> _PackedString -- string
627 -- same as substPS, but no prefix and suffix:
628 replacePS :: _PackedString -- regexp
629 -> _PackedString -- replacement
631 -> _PackedString -- string
634 match2PS :: _PackedString -- regexp
635 -> _PackedString -- string1 to match
636 -> _PackedString -- string2 to match
640 search2PS :: _PackedString -- regexp
641 -> _PackedString -- string to match
642 -> _PackedString -- string to match
646 -- functions to pull the matched pieces out of an REmatch:
648 getMatchesNo :: REmatch -> Int
649 getMatchedGroup :: REmatch -> Int -> _PackedString -> _PackedString
650 getWholeMatch :: REmatch -> _PackedString -> _PackedString
651 getLastMatch :: REmatch -> _PackedString -> _PackedString
652 getAfterMatch :: REmatch -> _PackedString -> _PackedString
654 -- (reverse) brute-force string matching;
655 -- Perl equivalent is index/rindex:
656 findPS, rfindPS :: _PackedString -> _PackedString -> Maybe Int
658 -- Equivalent to Perl "chop" (off the last character, if any):
659 chopPS :: _PackedString -> _PackedString
661 -- matchPrefixPS: tries to match as much as possible of strA starting
662 -- from the beginning of strB (handy when matching fancy literals in
664 matchPrefixPS :: _PackedString -> _PackedString -> Int
667 %************************************************************************
669 \subsubsection[Socket]{Network-interface toolkit---@Socket@ and @SocketPrim@}
670 \index{SocketPrim interface (GHC syslib)}
671 \index{Socket interface (GHC syslib)}
672 \index{network-interface library}
673 \index{sockets library}
674 \index{BSD sockets library}
676 %************************************************************************
678 (Darren Moffat supplied the network-interface toolkit.)
680 Your best bet for documentation is to look at the code---really!---
681 normally in \tr{ghc/lib/ghc/{BSD,Socket,SocketPrim}.lhs}.
683 The \tr{BSD} module provides functions to get at system-database info;
684 pretty straightforward if you're into this sort of thing:
686 getHostName :: IO String
688 getServiceByName :: ServiceName -> IO ServiceEntry
689 getServicePortNumber:: ServiceName -> IO PortNumber
690 getServiceEntry :: IO ServiceEntry
691 setServiceEntry :: Bool -> IO ()
692 endServiceEntry :: IO ()
694 getProtocolByName :: ProtocolName -> IO ProtocolEntry
695 getProtocolByNumber :: ProtocolNumber -> IO ProtcolEntry
696 getProtocolNumber :: ProtocolName -> ProtocolNumber
697 getProtocolEntry :: IO ProtocolEntry
698 setProtocolEntry :: Bool -> IO ()
699 endProtocolEntry :: IO ()
701 getHostByName :: HostName -> IO HostEntry
702 getHostByAddr :: Family -> HostAddress -> IO HostEntry
703 getHostEntry :: IO HostEntry
704 setHostEntry :: Bool -> IO ()
705 endHostEntry :: IO ()
708 The \tr{SocketPrim} interface provides quite direct access to the
709 socket facilities in a BSD Unix system, including all the
710 complications. We hope you don't need to use it! See the source if
713 The \tr{Socket} interface is a ``higher-level'' interface to sockets,
714 and it is what we recommend. Please tell us if the facilities it
715 offers are inadequate to your task!
717 The interface is relatively modest:
719 connectTo :: Hostname -> PortID -> IO Handle
720 listenOn :: PortID -> IO Socket
722 accept :: Socket -> IO (Handle, HostName)
723 sendTo :: Hostname -> PortID -> String -> IO ()
725 recvFrom :: Hostname -> PortID -> IO String
726 socketPort :: Socket -> IO PortID
728 data PortID -- PortID is a non-abstract type
729 = Service String -- Service Name eg "ftp"
730 | PortNumber Int -- User defined Port Number
731 | UnixSocket String -- Unix family socket in file system
733 type Hostname = String
736 Various examples of networking Haskell code are provided in
737 \tr{ghc/misc/examples/}, notably the \tr{net???/Main.hs} programs.
739 %************************************************************************
741 \subsection[HBC-library]{The HBC system library}
742 \index{HBC system library}
743 \index{system library, HBC}
745 %************************************************************************
747 This documentation is stolen directly from the HBC distribution. The
748 modules that GHC does not support (because they require HBC-specific
749 extensions) are omitted.
753 \index{Either module (HBC library)}%
754 A binary sum data type:
756 data Either a b = Left a | Right b
758 The constructor \tr{Left} is typically used for errors; it can be
759 renamed to \tr{Wrong} on import.
762 \index{Maybe module (HBC library)}%
763 A type for failure or success:
765 data Maybe a = Nothing | Just a
766 thenM :: Maybe a -> (a -> Maybe b) -> Maybe b
767 -- apply a function that may fail
771 \index{Option module (HBC library)}%
772 An alias for \tr{Maybe}:
774 data Option a = None | Some a
775 thenO :: Option a -> (a -> Option b) -> Option b
778 \item[\tr{ListUtil}:]
779 \index{ListUtil module (HBC library)}%
780 Various useful functions involving lists that are missing from the
783 assoc :: (Eq c) => (a -> b) -> b -> [(c, a)] -> c -> b
784 -- assoc f d l k looks for k in the association list l, if it
785 -- is found f is applied to the value, otherwise d is returned.
786 concatMap :: (a -> [b]) -> [a] -> [b]
787 -- flattening map (LML's concmap)
788 unfoldr :: (a -> (b, a)) -> (a -> Bool) -> a -> [b]
789 -- unfoldr f p x repeatedly applies f to x until (p x) holds.
790 -- (f x) should give a list element and a new x.
791 mapAccuml :: (a -> b -> (a, c)) -> a -> [b] -> (a, [c])
792 -- mapAccuml f s l maps f over l, but also threads the state s
793 -- through (LML's mapstate).
794 union :: (Eq a) => [a] -> [a] -> [a]
795 -- union of two lists
796 intersection :: (Eq a) => [a] -> [a] -> [a]
797 -- intersection of two lists
798 chopList :: ([a] -> (b, [a])) -> [a] -> [b]
800 assocDef :: (Eq a) => [(a, b)] -> b -> a -> b
802 lookup :: (Eq a) => [(a, b)] -> a -> Option b
803 -- lookup l k looks for the key k in the association list l
804 -- and returns an optional value
805 tails :: [a] -> [[a]]
806 -- return all the tails of a list
807 rept :: (Integral a) => a -> b -> [b]
808 -- repeat a value a number of times
809 groupEq :: (a->a->Bool) -> [a] -> [[a]]
810 -- group list elements according to an equality predicate
811 group :: (Eq a) => [a] -> [[a]]
812 -- group according to} ==
813 readListLazily :: (Text a) => String -> [a]
814 -- read a list in a lazy fashion
818 \index{Pretty module (HBC library)}%
819 John Hughes's pretty printing library.
821 type Context = (Bool, Int, Int, Int)
822 type IText = Context -> [String]
823 text :: String -> IText -- just text
824 (~.) :: IText -> IText -> IText -- horizontal composition
825 (^.) :: IText -> IText -> IText -- vertical composition
826 separate :: [IText] -> IText -- separate by spaces
827 nest :: Int -> IText -> IText -- indent
828 pretty :: Int -> Int -> IText -> String -- format it
832 \index{QSort module (HBC library)}%
833 A sort function using quicksort.
835 sortLe :: (a -> a -> Bool) -> [a] -> [a]
836 -- sort le l sorts l with le as less than predicate
837 sort :: (Ord a) => [a] -> [a]
838 -- sort l sorts l using the Ord class
842 \index{Random module (HBC library)}%
845 randomInts :: Int -> Int -> [Int]
846 -- given two seeds gives a list of random Int
847 randomDoubles :: Int -> Int -> [Double]
848 -- random Double with uniform distribution in (0,1)
849 normalRandomDoubles :: Int -> Int -> [Double]
850 -- random Double with normal distribution, mean 0, variance 1
854 Simple tracing. (Note: This comes with GHC anyway.)
856 trace :: String -> a -> a -- trace x y prints x and returns y
860 \index{Miranda module (HBC library)}%
861 Functions found in the Miranda library.
862 (Note: Miranda is a registered trade mark of Research Software Ltd.)
865 \index{Word module (HBC library)}
866 Bit manipulation. (GHC doesn't implement absolutely all of this.
867 And don't count on @Word@ being 32 bits on a Alpha...)
870 bitAnd :: a -> a -> a -- bitwise and
871 bitOr :: a -> a -> a -- bitwise or
872 bitXor :: a -> a -> a -- bitwise xor
873 bitCompl :: a -> a -- bitwise negation
874 bitRsh :: a -> Int -> a -- bitwise right shift
875 bitLsh :: a -> Int -> a -- bitwise left shift
876 bitSwap :: a -> a -- swap word halves
877 bit0 :: a -- word with least significant bit set
878 bitSize :: a -> Int -- number of bits in a word
880 data Byte -- 8 bit quantity
881 data Short -- 16 bit quantity
882 data Word -- 32 bit quantity
884 instance Bits Byte, Bits Short, Bits Word
885 instance Eq Byte, Eq Short, Eq Word
886 instance Ord Byte, Ord Short, Ord Word
887 instance Text Byte, Text Short, Text Word
888 instance Num Byte, Num Short, Num Word
889 wordToShorts :: Word -> [Short] -- convert a Word to two Short
890 wordToBytes :: Word -> [Byte] -- convert a Word to four Byte
891 bytesToString :: [Byte] -> String -- convert a list of Byte to a String (bit by bit)
892 wordToInt :: Word -> Int -- convert a Word to Int
893 shortToInt :: Short -> Int -- convert a Short to Int
894 byteToInt :: Byte -> Int -- convert a Byte to Int
898 \index{Time module (HBC library)}%
899 Manipulate time values (a Double with seconds since 1970).
901 -- year mon day hour min sec dec-sec weekday
902 data Time = Time Int Int Int Int Int Int Double Int
903 dblToTime :: Double -> Time -- convert a Double to a Time
904 timeToDbl :: Time -> Double -- convert a Time to a Double
905 timeToString :: Time -> String -- convert a Time to a readable String
909 \index{Hash module (HBC library)}%
912 class Hashable a where
913 hash :: a -> Int -- hash a value, return an Int
914 -- instances for all Prelude types
915 hashToMax :: (Hashable a) => Int -> a -> Int -- hash into interval [0..x-1]
918 \item[\tr{NameSupply}:]
919 \index{NameSupply module (HBC library)}%
920 Functions to generate unique names (Int).
923 initialNameSupply :: NameSupply
924 -- The initial name supply (may be different every
925 -- time the program is run.
926 splitNameSupply :: NameSupply -> (NameSupply,NameSupply)
927 -- split the namesupply into two
928 getName :: NameSupply -> Name
929 -- get the name associated with a name supply
933 \index{Parse module (HBC library)}%
934 Higher order functions to build parsers. With a little care these
935 combinators can be used to build efficient parsers with good error
938 infixr 8 +.+ , ..+ , +..
939 infix 6 `act` , >>> , `into` , .>
940 infixr 4 ||| , ||! , |!!
942 type Parser a b = a -> Int -> ParseResult a b
943 (|||) :: Parser a b -> Parser a b -> Parser a b
945 (||!) :: Parser a b -> Parser a b -> Parser a b
946 -- Alternative, but with committed choice
947 (|!!) :: Parser a b -> Parser a b -> Parser a b
948 -- Alternative, but with committed choice
949 (+.+) :: Parser a b -> Parser a c -> Parser a (b,c)
951 (..+) :: Parser a b -> Parser a c -> Parser a c
952 -- Sequence, throw away first part
953 (+..) :: Parser a b -> Parser a c -> Parser a b
954 -- Sequence, throw away second part
955 act :: Parser a b -> (b->c) -> Parser a c
957 (>>>) :: Parser a (b,c) -> (b->c->d) -> Parser a d
958 -- Action on two items
959 (.>) :: Parser a b -> c -> Parse a c
960 -- Action ignoring value
961 into :: Parser a b -> (b -> Parser a c) -> Parser a c
962 -- Use a produced value in a parser.
963 succeed b :: Parser a b
964 -- Always succeeds without consuming a token
967 many :: Parser a b -> Parser a [b]
969 many1 :: Parser a b -> Parser a [b]
971 count :: Parser a b -> Int -> Parser a [b]
972 -- Parse an exact number of items
973 sepBy1 :: Parser a b -> Parser a c -> Parser a [b]
974 -- Non-empty sequence of items separated by something
975 sepBy :: Parser a b -> Parser a c -> Parser a [b]
976 -- Sequence of items separated by something
977 lit :: (Eq a, Text a) => a -> Parser [a] a
978 -- Recognise a literal token from a list of tokens
979 litp :: String -> (a->Bool) -> Parser [a] a
980 -- Recognise a token with a predicate.
981 -- The string is a description for error messages.
982 testp :: String -> (a -> Bool) -> (Parser b a) -> Parser b a
983 -- Test a semantic value.
984 token :: (a -> Either String (b, a)) -> Parser a b
985 -- General token recogniser.
986 parse :: Parser a b -> a -> Either ([String], a) [(b, a)]
987 -- Do a parse. Return either error (possible tokens and rest
988 -- of tokens) or all possible parses.
989 sParse :: (Text a) => (Parser [a] b) -> [a] -> Either String b
990 -- Simple parse. Return error message or result.
993 %%%simpleLex :: String -> [String] -- A simple (but useful) lexical analyzer
996 \index{Native module (HBC library)}%
997 Functions to convert the primitive types \tr{Int}, \tr{Float}, and \tr{Double} to
998 their native representation as a list of bytes (\tr{Char}). If such a list
999 is read/written to a file it will have the same format as when, e.g.,
1000 C read/writes the same kind of data.
1002 type Bytes = [Char] -- A byte stream is just a list of characters
1004 class Native a where
1005 showBytes :: a -> Bytes -> Bytes
1006 -- prepend the representation of an item the a byte stream
1007 listShowBytes :: [a] -> Bytes -> Bytes
1008 -- prepend the representation of a list of items to a stream
1009 -- (may be more efficient than repeating showBytes).
1010 readBytes :: Bytes -> Maybe (a, Bytes)
1011 -- get an item from the stream and return the rest,
1012 -- or fail if the stream is to short.
1013 listReadBytes :: Int -> Bytes -> Maybe ([a], Bytes)
1014 -- read n items from a stream.
1017 instance Native Float
1018 instance Native Double
1019 instance (Native a, Native b) => Native (a,b)
1020 -- juxtaposition of the two items
1021 instance (Native a, Native b, Native c) => Native (a, b, c)
1022 -- juxtaposition of the three items
1023 instance (Native a) => Native [a]
1024 -- an item count in an Int followed by the items
1026 shortIntToBytes :: Int -> Bytes -> Bytes
1027 -- Convert an Int to what corresponds to a short in C.
1028 bytesToShortInt :: Bytes -> Maybe (Int, Bytes)
1029 -- Get a short from a byte stream and convert to an Int.
1031 showB :: (Native a) => a -> Bytes -- Simple interface to showBytes.
1032 readB :: (Native a) => Bytes -> a -- Simple interface to readBytes.
1036 \index{Number module (HBC library)}%
1037 Simple numbers that belong to all numeric classes and behave like
1038 a naive user would expect (except that printing is still ugly).
1039 (NB: GHC does not provide a magic way to use \tr{Numbers} everywhere,
1040 but you should be able to do it with normal \tr{import}ing and
1043 data Number -- The type itself.
1044 instance ... -- All reasonable instances.
1045 isInteger :: Number -> Bool -- Test if a Number is an integer.