home *** CD-ROM | disk | FTP | other *** search
/ The Datafile PD-CD 5 / DATAFILE_PDCD5.iso / utilities / g / gofer / !Gofer / archives / Docs / appx_b < prev    next >
Encoding:
Text File  |  1993-02-12  |  29.1 KB  |  1,057 lines

  1.  
  2.  
  3. Introduction to Gofer          APPENDIX B: CONTENTS OF STANDARD PRELUDE
  4.  
  5.  
  6. APPENDIX B: CONTENTS OF STANDARD PRELUDE
  7.  
  8. --         __________   __________   __________   __________   ________
  9. --        /  _______/  /  ____   /  /  _______/  /  _______/  /  ____  \
  10. --       /  / _____   /  /   /  /  /  /______   /  /______   /  /___/  /
  11. --      /  / /_   /  /  /   /  /  /  _______/  /  _______/  /  __   __/
  12. --     /  /___/  /  /  /___/  /  /  /         /  /______   /  /  \  \ 
  13. --    /_________/  /_________/  /__/         /_________/  /__/    \__\
  14. --
  15. --    Functional programming environment, Version 2.28
  16. --    Copyright Mark P Jones 1991-1993.
  17. --
  18. --    Standard prelude for use of overloaded values using type classes.
  19. --    Based on the Haskell standard prelude version 1.2.
  20.  
  21. help = "press :? for a list of commands"
  22.  
  23. -- Operator precedence table: -----------------------------------------------
  24.  
  25. infixl 9 !!
  26. infixr 9 .
  27. infixr 8 ^
  28. infixl 7 *
  29. infix  7 /, `div`, `quot`, `rem`, `mod`
  30. infixl 6 +, -
  31. infix  5 \\
  32. infixr 5 ++, :
  33. infix  4 ==, /=, <, <=, >=, >
  34. infix  4 `elem`, `notElem`
  35. infixr 3 &&
  36. infixr 2 ||
  37. infixr 0 $
  38.  
  39. -- Standard combinators: ----------------------------------------------------
  40.  
  41. primitive strict "primStrict" :: (a -> b) -> a -> b
  42.  
  43. const          :: a -> b -> a
  44. const k x       = k
  45.  
  46. id             :: a -> a
  47. id    x         = x
  48.  
  49. curry          :: ((a,b) -> c) -> a -> b -> c
  50. curry f a b     =  f (a,b)
  51.  
  52. uncurry        :: (a -> b -> c) -> (a,b) -> c
  53. uncurry f (a,b) = f a b
  54.  
  55. fst            :: (a,b) -> a
  56. fst (x,_)       = x
  57.  
  58. snd            :: (a,b) -> b
  59. snd (_,y)       = y
  60.  
  61. fst3           :: (a,b,c) -> a
  62.  
  63.  
  64.                                       97
  65.  
  66.  
  67.  
  68.  
  69. Introduction to Gofer          APPENDIX B: CONTENTS OF STANDARD PRELUDE
  70.  
  71.  
  72. fst3 (x,_,_)    = x
  73.  
  74. snd3           :: (a,b,c) -> b
  75. snd3 (_,x,_)    = x
  76.  
  77. thd3           :: (a,b,c) -> c
  78. thd3 (_,_,x)    = x
  79.  
  80. (.)           :: (b -> c) -> (a -> b) -> (a -> c)
  81. (f . g) x       = f (g x)
  82.  
  83. flip           :: (a -> b -> c) -> b -> a -> c
  84. flip  f x y     = f y x
  85.  
  86. ($)            :: (a -> b) -> a -> b     -- pronounced as `apply' elsewhere
  87. f $ x           = f x
  88.  
  89. -- Boolean functions: -------------------------------------------------------
  90.  
  91. (&&), (||)     :: Bool -> Bool -> Bool
  92. False && x      = False
  93. True  && x      = x
  94.  
  95. False || x      = x
  96. True  || x      = True
  97.  
  98. not            :: Bool -> Bool
  99. not True        = False
  100. not False       = True
  101.  
  102. and, or        :: [Bool] -> Bool
  103. and             = foldr (&&) True
  104. or              = foldr (||) False
  105.  
  106. any, all       :: (a -> Bool) -> [a] -> Bool
  107. any p           = or  . map p
  108. all p           = and . map p
  109.  
  110. otherwise      :: Bool
  111. otherwise       = True
  112.  
  113. -- Character functions: -----------------------------------------------------
  114.  
  115. primitive ord "primCharToInt" :: Char -> Int
  116. primitive chr "primIntToChar" :: Int -> Char
  117.  
  118. isAscii, isControl, isPrint, isSpace            :: Char -> Bool
  119. isUpper, isLower, isAlpha, isDigit, isAlphanum  :: Char -> Bool
  120.  
  121. isAscii c     =  ord c < 128
  122.  
  123. isControl c   =  c < ' '    ||  c == '\DEL'
  124.  
  125. isPrint c     =  c >= ' '   &&  c <= '~'
  126.  
  127. isSpace c     =  c == ' '   || c == '\t'  || c == '\n'  || c == '\r'  ||
  128.  
  129.  
  130.                                       98
  131.  
  132.  
  133.  
  134.  
  135. Introduction to Gofer          APPENDIX B: CONTENTS OF STANDARD PRELUDE
  136.  
  137.  
  138.                                c == '\f'  || c == '\v'
  139.  
  140. isUpper c     =  c >= 'A'   &&  c <= 'Z'
  141. isLower c     =  c >= 'a'   &&  c <= 'z'
  142.  
  143. isAlpha c     =  isUpper c  ||  isLower c
  144. isDigit c     =  c >= '0'   &&  c <= '9'
  145. isAlphanum c  =  isAlpha c  ||  isDigit c
  146.  
  147.  
  148. toUpper, toLower      :: Char -> Char
  149.  
  150. toUpper c | isLower c  = chr (ord c - ord 'a' + ord 'A')
  151.           | otherwise  = c
  152.  
  153. toLower c | isUpper c  = chr (ord c - ord 'A' + ord 'a')
  154.           | otherwise  = c
  155.  
  156. minChar, maxChar      :: Char
  157. minChar                = chr 0
  158. maxChar                = chr 255
  159.  
  160. -- Standard type classes: ---------------------------------------------------
  161.  
  162. class Eq a where
  163.     (==), (/=) :: a -> a -> Bool
  164.     x /= y      = not (x == y)
  165.  
  166. class Eq a => Ord a where
  167.     (<), (<=), (>), (>=) :: a -> a -> Bool
  168.     max, min             :: a -> a -> a
  169.  
  170.     x <  y            = x <= y && x /= y
  171.     x >= y            = y <= x
  172.     x >  y            = y < x
  173.  
  174.     max x y | x >= y  = x
  175.             | y >= x  = y
  176.     min x y | x <= y  = x
  177.             | y <= x  = y
  178.  
  179. class Ord a => Ix a where
  180.     range   :: (a,a) -> [a]
  181.     index   :: (a,a) -> a -> Int
  182.     inRange :: (a,a) -> a -> Bool
  183.  
  184. class Ord a => Enum a where
  185.     enumFrom       :: a -> [a]              -- [n..]
  186.     enumFromThen   :: a -> a -> [a]         -- [n,m..]
  187.     enumFromTo     :: a -> a -> [a]         -- [n..m]
  188.     enumFromThenTo :: a -> a -> a -> [a]    -- [n,n'..m]
  189.  
  190.     enumFromTo n m        = takeWhile (m>=) (enumFrom n)
  191.     enumFromThenTo n n' m = takeWhile ((if n'>=n then (>=) else (<=)) m)
  192.                                       (enumFromThen n n')
  193.  
  194.  
  195.  
  196.                                       99
  197.  
  198.  
  199.  
  200.  
  201. Introduction to Gofer          APPENDIX B: CONTENTS OF STANDARD PRELUDE
  202.  
  203.  
  204. class (Eq a, Text a) => Num a where         -- simplified numeric class
  205.     (+), (-), (*), (/) :: a -> a -> a
  206.     negate             :: a -> a
  207.     fromInteger           :: Int -> a
  208.  
  209. -- Type class instances: ----------------------------------------------------
  210.  
  211. primitive primEqInt    "primEqInt",
  212.       primLeInt    "primLeInt"   :: Int -> Int -> Bool
  213. primitive primPlusInt  "primPlusInt",
  214.       primMinusInt "primMinusInt",
  215.       primDivInt   "primDivInt",
  216.       primMulInt   "primMulInt"  :: Int -> Int -> Int
  217. primitive primNegInt   "primNegInt"  :: Int -> Int
  218.  
  219. instance Eq ()  where () == () = True
  220. instance Ord () where () <= () = True
  221.  
  222. instance Eq Int  where (==) = primEqInt
  223.  
  224. instance Ord Int where (<=) = primLeInt
  225.  
  226. instance Ix Int where
  227.     range (m,n)      = [m..n]
  228.     index (m,n) i    = i - m
  229.     inRange (m,n) i  = m <= i && i <= n
  230.  
  231. instance Enum Int where
  232.     enumFrom n       = iterate (1+) n
  233.     enumFromThen n m = iterate ((m-n)+) n
  234.  
  235. instance Num Int where
  236.     (+)           = primPlusInt
  237.     (-)           = primMinusInt
  238.     (*)           = primMulInt
  239.     (/)           = primDivInt
  240.     negate        = primNegInt
  241.     fromInteger x = x
  242.  
  243. {- PC version off -}
  244. primitive primEqFloat    "primEqFloat",
  245.           primLeFloat    "primLeFloat"    :: Float -> Float -> Bool
  246. primitive primPlusFloat  "primPlusFloat", 
  247.           primMinusFloat "primMinusFloat", 
  248.           primDivFloat   "primDivFloat",
  249.           primMulFloat   "primMulFloat"   :: Float -> Float -> Float 
  250. primitive primNegFloat   "primNegFloat"   :: Float -> Float
  251. primitive primIntToFloat "primIntToFloat" :: Int -> Float
  252.  
  253. instance Eq Float where (==) = primEqFloat
  254.  
  255. instance Ord Float where (<=) = primLeFloat
  256.  
  257. instance Enum Float where
  258.     enumFrom n       = iterate (1.0+) n
  259.     enumFromThen n m = iterate ((m-n)+) n
  260.  
  261.  
  262.                                       100
  263.  
  264.  
  265.  
  266.  
  267. Introduction to Gofer          APPENDIX B: CONTENTS OF STANDARD PRELUDE
  268.  
  269.  
  270. instance Num Float where
  271.     (+)         = primPlusFloat
  272.     (-)         = primMinusFloat
  273.     (*)         = primMulFloat
  274.     (/)         = primDivFloat 
  275.     negate      = primNegFloat
  276.     fromInteger = primIntToFloat
  277.  
  278. primitive sin "primSinFloat",  asin  "primAsinFloat",
  279.           cos "primCosFloat",  acos  "primAcosFloat",
  280.       tan "primTanFloat",  atan  "primAtanFloat",
  281.           log "primLogFloat",  log10 "primLog10Float",
  282.       exp "primExpFloat",  sqrt  "primSqrtFloat" :: Float -> Float
  283. primitive atan2    "primAtan2Float" :: Float -> Float -> Float
  284. primitive truncate "primFloatToInt" :: Float -> Int
  285.  
  286. pi :: Float
  287. pi  = 3.1415926535
  288.  
  289. {- PC version on -}
  290.  
  291. primitive primEqChar   "primEqChar",
  292.       primLeChar   "primLeChar"  :: Char -> Char -> Bool
  293.  
  294. instance Eq Char  where (==) = primEqChar   -- c == d  =  ord c == ord d
  295.  
  296. instance Ord Char where (<=) = primLeChar   -- c <= d  =  ord c <= ord d
  297.  
  298. instance Ix Char where
  299.     range (c,c')      = [c..c']
  300.     index (c,c') ci   = ord ci - ord c
  301.     inRange (c,c') ci = ord c <= i && i <= ord c' where i = ord ci
  302.  
  303. instance Enum Char where
  304.     enumFrom c        = map chr [ord c .. ord maxChar]
  305.     enumFromThen c c' = map chr [ord c, ord c' .. ord lastChar]
  306.                         where lastChar = if c' < c then minChar else maxChar
  307.  
  308. instance Eq a => Eq [a] where
  309.     []     == []     =  True
  310.     []     == (y:ys) =  False
  311.     (x:xs) == []     =  False
  312.     (x:xs) == (y:ys) =  x==y && xs==ys
  313.  
  314. instance Ord a => Ord [a] where
  315.     []     <= _      =  True
  316.     (_:_)  <= []     =  False
  317.     (x:xs) <= (y:ys) =  x<y || (x==y && xs<=ys)
  318.  
  319. instance (Eq a, Eq b) => Eq (a,b) where
  320.     (x,y) == (u,v)  =  x==u && y==v
  321.  
  322. instance (Ord a, Ord b) => Ord (a,b) where
  323.     (x,y) <= (u,v)  = x<u  ||  (x==u && y<=v)
  324.  
  325. instance Eq Bool where
  326.  
  327.  
  328.                                       101
  329.  
  330.  
  331.  
  332.  
  333. Introduction to Gofer          APPENDIX B: CONTENTS OF STANDARD PRELUDE
  334.  
  335.  
  336.     True  == True   =  True
  337.     False == False  =  True
  338.     _     == _      =  False
  339.  
  340. instance Ord Bool where
  341.     False <= x      = True
  342.     True  <= x      = x
  343.  
  344. -- Standard numerical functions: --------------------------------------------
  345.  
  346. primitive div    "primDivInt",
  347.       quot   "primQuotInt",
  348.           rem    "primRemInt",
  349.           mod    "primModInt"    :: Int -> Int -> Int
  350.  
  351. subtract  :: Num a => a -> a -> a
  352. subtract   = flip (-)
  353.  
  354. even, odd :: Int -> Bool
  355. even x     = x `rem` 2 == 0
  356. odd        = not . even
  357.  
  358. gcd       :: Int -> Int -> Int
  359. gcd x y    = gcd' (abs x) (abs y)
  360.              where gcd' x 0 = x
  361.                    gcd' x y = gcd' y (x `rem` y)
  362.  
  363. lcm       :: Int -> Int -> Int
  364. lcm _ 0    = 0
  365. lcm 0 _    = 0
  366. lcm x y    = abs ((x `quot` gcd x y) * y)
  367.  
  368. (^)       :: Num a => a -> Int -> a
  369. x ^ 0      = fromInteger 1
  370. x ^ (n+1)  = f x n x
  371.              where f _ 0 y = y
  372.                    f x n y = g x n where
  373.                              g x n | even n    = g (x*x) (n`quot`2)
  374.                                    | otherwise = f x (n-1) (x*y)
  375.  
  376. abs                     :: (Num a, Ord a) => a -> a
  377. abs x | x>=fromInteger 0 = x
  378.       | otherwise        = -x
  379.  
  380. signum            :: (Num a, Ord a) => a -> Int
  381. signum x
  382.       | x==fromInteger 0 = 0
  383.       | x> fromInteger 0 = 1
  384.       | otherwise        = -1
  385.  
  386. sum, product    :: Num a => [a] -> a
  387. sum              = foldl' (+) (fromInteger 0)
  388. product          = foldl' (*) (fromInteger 1)
  389.  
  390. sums, products    :: Num a => [a] -> [a]
  391. sums             = scanl (+) (fromInteger 0)
  392.  
  393.  
  394.                                       102
  395.  
  396.  
  397.  
  398.  
  399. Introduction to Gofer          APPENDIX B: CONTENTS OF STANDARD PRELUDE
  400.  
  401.  
  402. products         = scanl (*) (fromInteger 1)
  403.  
  404. -- Standard list processing functions: --------------------------------------
  405.  
  406. head             :: [a] -> a
  407. head (x:_)        = x
  408.  
  409. last             :: [a] -> a
  410. last [x]          = x
  411. last (_:xs)       = last xs
  412.  
  413. tail             :: [a] -> [a]
  414. tail (_:xs)       = xs
  415.  
  416. init             :: [a] -> [a]
  417. init [x]          = []
  418. init (x:xs)       = x : init xs
  419.  
  420. (++)             :: [a] -> [a] -> [a]    -- append lists.  Associative with
  421. []     ++ ys      = ys                   -- left and right identity [].
  422. (x:xs) ++ ys      = x:(xs++ys)
  423.  
  424. genericLength    :: Num a => [b] -> a
  425. genericLength     = foldl' (\n _ -> n + fromInteger 1) (fromInteger 0)
  426.  
  427. length         :: [a] -> Int           -- calculate length of list
  428. length            = foldl' (\n _ -> n+1) 0
  429.  
  430. (!!)             :: [a] -> Int -> a      -- xs!!n selects the nth element of
  431. (x:_)  !! 0       = x                    -- the list xs (first element xs!!0)
  432. (_:xs) !! (n+1)   = xs !! n              -- for any n < length xs.
  433.  
  434. iterate          :: (a -> a) -> a -> [a] -- generate the infinite list
  435. iterate f x       = x : iterate f (f x)  -- [x, f x, f (f x), ...
  436.  
  437. repeat           :: a -> [a]             -- generate the infinite list
  438. repeat x          = xs where xs = x:xs   -- [x, x, x, x, ...
  439.  
  440. cycle            :: [a] -> [a]           -- generate the infinite list
  441. cycle xs          = xs' where xs'=xs++xs'-- xs ++ xs ++ xs ++ ...
  442.  
  443. copy             :: Int -> a -> [a]      -- make list of n copies of x
  444. copy n x          = take n xs where xs = x:xs
  445.  
  446. nub              :: Eq a => [a] -> [a]   -- remove duplicates from list
  447. nub []            = []
  448. nub (x:xs)        = x : nub (filter (x/=) xs)
  449.  
  450. reverse          :: [a] -> [a]           -- reverse elements of list
  451. reverse           = foldl (flip (:)) []
  452.  
  453. elem, notElem    :: Eq a => a -> [a] -> Bool
  454. elem              = any . (==)           -- test for membership in list
  455. notElem           = all . (/=)           -- test for non-membership
  456.  
  457. maximum, minimum :: Ord a => [a] -> a
  458.  
  459.  
  460.                                       103
  461.  
  462.  
  463.  
  464.  
  465. Introduction to Gofer          APPENDIX B: CONTENTS OF STANDARD PRELUDE
  466.  
  467.  
  468. maximum           = foldl1 max          -- max element in non-empty list
  469. minimum           = foldl1 min          -- min element in non-empty list
  470.  
  471. concat           :: [[a]] -> [a]        -- concatenate list of lists
  472. concat            = foldr (++) []
  473.  
  474. transpose        :: [[a]] -> [[a]]      -- transpose list of lists
  475. transpose         = foldr
  476.                       (\xs xss -> zipWith (:) xs (xss ++ repeat []))
  477.                       []
  478.  
  479. -- null provides a simple and efficient way of determining whether a given
  480. -- list is empty, without using (==) and hence avoiding a constraint of the
  481. -- form Eq [a].
  482.  
  483. null             :: [a] -> Bool
  484. null []           = True
  485. null (_:_)        = False
  486.  
  487. -- (\\) is used to remove the first occurrence of each element in the second
  488. -- list from the first list.  It is a kind of inverse of (++) in the sense
  489. -- that  (xs ++ ys) \\ xs = ys for any finite list xs of proper values xs.
  490.  
  491. (\\)             :: Eq a => [a] -> [a] -> [a]
  492. (\\)              = foldl del
  493.                     where []     `del` _  = []
  494.                           (x:xs) `del` y
  495.                              | x == y     = xs
  496.                              | otherwise  = x : xs `del` y
  497.  
  498.  
  499. -- map f xs applies the function f to each element of the list xs returning
  500. -- the corresponding list of results.  filter p xs returns the sublist of xs
  501. -- containing those elements which satisfy the predicate p.
  502.  
  503. map              :: (a -> b) -> [a] -> [b]
  504. map f []          = []
  505. map f (x:xs)      = f x : map f xs
  506.  
  507. filter           :: (a -> Bool) -> [a] -> [a]
  508. filter _ []       = []
  509. filter p (x:xs)
  510.     | p x         = x : xs'
  511.     | otherwise   = xs'
  512.                   where xs' = filter p xs
  513.  
  514. -- Fold primitives:  The foldl and scanl functions, variants foldl1 and
  515. -- scanl1 for non-empty lists, and strict variants foldl' scanl' describe
  516. -- common patterns of recursion over lists.  Informally:
  517. --
  518. --  foldl f a [x1, x2, ..., xn]  = f (...(f (f a x1) x2)...) xn
  519. --                               = (...((a `f` x1) `f` x2)...) `f` xn
  520. -- etc...
  521. --
  522. -- The functions foldr, scanr and variants foldr1, scanr1 are duals of these
  523. -- functions:
  524.  
  525.  
  526.                                       104
  527.  
  528.  
  529.  
  530.  
  531. Introduction to Gofer          APPENDIX B: CONTENTS OF STANDARD PRELUDE
  532.  
  533.  
  534. -- e.g.  foldr f a xs = foldl (flip f) a (reverse xs)  for finite lists xs.
  535.  
  536. foldl            :: (a -> b -> a) -> a -> [b] -> a
  537. foldl f z []      = z
  538. foldl f z (x:xs)  = foldl f (f z x) xs
  539.  
  540. foldl1           :: (a -> a -> a) -> [a] -> a
  541. foldl1 f (x:xs)   = foldl f x xs
  542.  
  543. foldl'           :: (a -> b -> a) -> a -> [b] -> a
  544. foldl' f a []     =  a
  545. foldl' f a (x:xs) =  strict (foldl' f) (f a x) xs
  546.  
  547. scanl            :: (a -> b -> a) -> a -> [b] -> [a]
  548. scanl f q xs      = q : (case xs of
  549.                          []   -> []
  550.                          x:xs -> scanl f (f q x) xs)
  551.  
  552. scanl1           :: (a -> a -> a) -> [a] -> [a]
  553. scanl1 f (x:xs)   = scanl f x xs
  554.  
  555. scanl'           :: (a -> b -> a) -> a -> [b] -> [a]
  556. scanl' f q xs     = q : (case xs of
  557.                          []   -> []
  558.                          x:xs -> strict (scanl' f) (f q x) xs)
  559.  
  560. foldr            :: (a -> b -> b) -> b -> [a] -> b
  561. foldr f z []      = z
  562. foldr f z (x:xs)  = f x (foldr f z xs)
  563.  
  564. foldr1           :: (a -> a -> a) -> [a] -> a
  565. foldr1 f [x]      = x
  566. foldr1 f (x:xs)   = f x (foldr1 f xs)
  567.  
  568. scanr            :: (a -> b -> b) -> b -> [a] -> [b]
  569. scanr f q0 []     = [q0]
  570. scanr f q0 (x:xs) = f x q : qs
  571.                     where qs@(q:_) = scanr f q0 xs
  572.  
  573. scanr1           :: (a -> a -> a) -> [a] -> [a]
  574. scanr1 f [x]      = [x]
  575. scanr1 f (x:xs)   = f x q : qs
  576.                     where qs@(q:_) = scanr1 f xs
  577.  
  578. -- List breaking functions:
  579. --
  580. --   take n xs       returns the first n elements of xs
  581. --   drop n xs       returns the remaining elements of xs
  582. --   splitAt n xs    = (take n xs, drop n xs)
  583. --
  584. --   takeWhile p xs  returns the longest initial segment of xs whose
  585. --                   elements satisfy p
  586. --   dropWhile p xs  returns the remaining portion of the list
  587. --   span p xs       = (takeWhile p xs, dropWhile p xs)
  588. --
  589. --   takeUntil p xs  returns the list of elements upto and including the
  590.  
  591.  
  592.                                       105
  593.  
  594.  
  595.  
  596.  
  597. Introduction to Gofer          APPENDIX B: CONTENTS OF STANDARD PRELUDE
  598.  
  599.  
  600. --                   first element of xs which satisfies p
  601.  
  602. take                :: Int -> [a] -> [a]
  603. take 0     _         = []
  604. take _     []        = []
  605. take (n+1) (x:xs)    = x : take n xs
  606.  
  607. drop                :: Int -> [a] -> [a]
  608. drop 0     xs        = xs
  609. drop _     []        = []
  610. drop (n+1) (_:xs)    = drop n xs
  611.  
  612. splitAt             :: Int -> [a] -> ([a], [a])
  613. splitAt 0     xs     = ([],xs)
  614. splitAt _     []     = ([],[])
  615. splitAt (n+1) (x:xs) = (x:xs',xs'') where (xs',xs'') = splitAt n xs
  616.  
  617. takeWhile           :: (a -> Bool) -> [a] -> [a]
  618. takeWhile p []       = []
  619. takeWhile p (x:xs)
  620.          | p x       = x : takeWhile p xs
  621.          | otherwise = []
  622.  
  623. takeUntil           :: (a -> Bool) -> [a] -> [a]
  624. takeUntil p []       = []
  625. takeUntil p (x:xs)
  626.        | p x         = [x]
  627.        | otherwise   = x : takeUntil p xs
  628.  
  629. dropWhile           :: (a -> Bool) -> [a] -> [a]
  630. dropWhile p []       = []
  631. dropWhile p xs@(x:xs')
  632.          | p x       = dropWhile p xs'
  633.          | otherwise = xs
  634.  
  635. span, break         :: (a -> Bool) -> [a] -> ([a],[a])
  636. span p []            = ([],[])
  637. span p xs@(x:xs')
  638.          | p x       = let (ys,zs) = span p xs' in (x:ys,zs)
  639.          | otherwise = ([],xs)
  640. break p              = span (not . p)
  641.  
  642. -- Text processing:
  643. --   lines s     returns the list of lines in the string s.
  644. --   words s     returns the list of words in the string s.
  645. --   unlines ls  joins the list of lines ls into a single string
  646. --               with lines separated by newline characters.
  647. --   unwords ws  joins the list of words ws into a single string
  648. --               with words separated by spaces.
  649.  
  650. lines     :: String -> [String]
  651. lines ""   = []
  652. lines s    = l : (if null s' then [] else lines (tail s'))
  653.              where (l, s') = break ('\n'==) s
  654.  
  655. words     :: String -> [String]
  656.  
  657.  
  658.                                       106
  659.  
  660.  
  661.  
  662.  
  663. Introduction to Gofer          APPENDIX B: CONTENTS OF STANDARD PRELUDE
  664.  
  665.  
  666. words s    = case dropWhile isSpace s of
  667.                   "" -> []
  668.                   s' -> w : words s''
  669.                         where (w,s'') = break isSpace s'
  670.  
  671. unlines   :: [String] -> String
  672. unlines    = concat . map (\l -> l ++ "\n")
  673.  
  674. unwords   :: [String] -> String
  675. unwords [] = []
  676. unwords ws = foldr1 (\w s -> w ++ ' ':s) ws
  677.  
  678. -- Merging and sorting lists:
  679.  
  680. merge               :: Ord a => [a] -> [a] -> [a] 
  681. merge []     ys      = ys
  682. merge xs     []      = xs
  683. merge (x:xs) (y:ys)
  684.         | x <= y     = x : merge xs (y:ys)
  685.         | otherwise  = y : merge (x:xs) ys
  686.  
  687. sort                :: Ord a => [a] -> [a]
  688. sort                 = foldr insert []
  689.  
  690. insert              :: Ord a => a -> [a] -> [a]
  691. insert x []          = [x]
  692. insert x (y:ys)
  693.         | x <= y     = x:y:ys
  694.         | otherwise  = y:insert x ys
  695.  
  696. qsort               :: Ord a => [a] -> [a]
  697. qsort []             = []
  698. qsort (x:xs)         = qsort [ u | u<-xs, u<x ] ++
  699.                              [ x ] ++
  700.                        qsort [ u | u<-xs, u>=x ]
  701.  
  702. -- zip and zipWith families of functions:
  703.  
  704. zip  :: [a] -> [b] -> [(a,b)]
  705. zip   = zipWith  (\a b -> (a,b))
  706.  
  707. zip3 :: [a] -> [b] -> [c] -> [(a,b,c)]
  708. zip3  = zipWith3 (\a b c -> (a,b,c))
  709.  
  710. zip4 :: [a] -> [b] -> [c] -> [d] -> [(a,b,c,d)]
  711. zip4  = zipWith4 (\a b c d -> (a,b,c,d))
  712.  
  713. zip5 :: [a] -> [b] -> [c] -> [d] -> [e] -> [(a,b,c,d,e)]
  714. zip5  = zipWith5 (\a b c d e -> (a,b,c,d,e))
  715.  
  716. zip6 :: [a] -> [b] -> [c] -> [d] -> [e] -> [f] -> [(a,b,c,d,e,f)]
  717. zip6  = zipWith6 (\a b c d e f -> (a,b,c,d,e,f))
  718.  
  719. zip7 :: [a] -> [b] -> [c] -> [d] -> [e] -> [f] -> [g] -> [(a,b,c,d,e,f,g)]
  720. zip7  = zipWith7 (\a b c d e f g -> (a,b,c,d,e,f,g))
  721.  
  722.  
  723.  
  724.                                       107
  725.  
  726.  
  727.  
  728.  
  729. Introduction to Gofer          APPENDIX B: CONTENTS OF STANDARD PRELUDE
  730.  
  731.  
  732. zipWith                  :: (a->b->c) -> [a]->[b]->[c]
  733. zipWith z (a:as) (b:bs)   = z a b : zipWith z as bs
  734. zipWith _ _      _        = []
  735.  
  736. zipWith3                 :: (a->b->c->d) -> [a]->[b]->[c]->[d]
  737. zipWith3 z (a:as) (b:bs) (c:cs)
  738.                           = z a b c : zipWith3 z as bs cs
  739. zipWith3 _ _ _ _          = []
  740.  
  741. zipWith4                 :: (a->b->c->d->e) -> [a]->[b]->[c]->[d]->[e]
  742. zipWith4 z (a:as) (b:bs) (c:cs) (d:ds)
  743.                           = z a b c d : zipWith4 z as bs cs ds
  744. zipWith4 _ _ _ _ _        = []
  745.  
  746. zipWith5                 :: (a->b->c->d->e->f) -> [a]->[b]->[c]->[d]->[e]->[f]
  747. zipWith5 z (a:as) (b:bs) (c:cs) (d:ds) (e:es)
  748.                           = z a b c d e : zipWith5 z as bs cs ds es
  749. zipWith5 _ _ _ _ _ _      = []
  750.  
  751. zipWith6                 :: (a->b->c->d->e->f->g)
  752.                             -> [a]->[b]->[c]->[d]->[e]->[f]->[g]
  753. zipWith6 z (a:as) (b:bs) (c:cs) (d:ds) (e:es) (f:fs)
  754.                           = z a b c d e f : zipWith6 z as bs cs ds es fs
  755. zipWith6 _ _ _ _ _ _ _    = []
  756.  
  757. zipWith7                 :: (a->b->c->d->e->f->g->h)
  758.                              -> [a]->[b]->[c]->[d]->[e]->[f]->[g]->[h]
  759. zipWith7 z (a:as) (b:bs) (c:cs) (d:ds) (e:es) (f:fs) (g:gs)
  760.                           = z a b c d e f g : zipWith7 z as bs cs ds es fs gs
  761. zipWith7 _ _ _ _ _ _ _ _  = []
  762.  
  763. unzip                    :: [(a,b)] -> ([a],[b])
  764. unzip                     = foldr (\(a,b) ~(as,bs) -> (a:as, b:bs)) ([], [])
  765.  
  766. -- Formatted output: --------------------------------------------------------
  767.  
  768. primitive primPrint "primPrint"  :: Int -> a -> String -> String
  769.  
  770. show'       :: a -> String
  771. show' x      = primPrint 0 x []
  772.  
  773. cjustify, ljustify, rjustify :: Int -> String -> String
  774.  
  775. cjustify n s = space halfm ++ s ++ space (m - halfm)
  776.                where m     = n - length s
  777.                      halfm = m `div` 2
  778. ljustify n s = s ++ space (n - length s)
  779. rjustify n s = space (n - length s) ++ s
  780.  
  781. space       :: Int -> String
  782. space n      = copy n ' '
  783.  
  784. layn        :: [String] -> String
  785. layn         = lay 1 where lay _ []     = []
  786.                            lay n (x:xs) = rjustify 4 (show n) ++ ") "
  787.                                            ++ x ++ "\n" ++ lay (n+1) xs
  788.  
  789.  
  790.                                       108
  791.  
  792.  
  793.  
  794.  
  795. Introduction to Gofer          APPENDIX B: CONTENTS OF STANDARD PRELUDE
  796.  
  797.  
  798. -- Miscellaneous: -----------------------------------------------------------
  799.  
  800. until                  :: (a -> Bool) -> (a -> a) -> a -> a
  801. until p f x | p x       = x
  802.             | otherwise = until p f (f x)
  803.  
  804. until'                 :: (a -> Bool) -> (a -> a) -> a -> [a]
  805. until' p f              = takeUntil p . iterate f
  806.  
  807. primitive error "primError" :: String -> a
  808.  
  809. undefined              :: a
  810. undefined | False       = undefined
  811.  
  812. asTypeOf               :: a -> a -> a
  813. x `asTypeOf` _          = x
  814.  
  815. -- A trimmed down version of the Haskell Text class: ------------------------
  816.  
  817. type  ShowS   = String -> String
  818.  
  819. class Text a where 
  820.     showsPrec      :: Int -> a -> ShowS
  821.     showList       :: [a] -> ShowS
  822.  
  823.     showsPrec       = primPrint
  824.     showList []     = showString "[]"
  825.     showList (x:xs) = showChar '[' . shows x . showl xs
  826.                       where showl []     = showChar ']'
  827.                             showl (x:xs) = showChar ',' . shows x . showl xs
  828.  
  829. shows      :: Text a => a -> ShowS
  830. shows       = showsPrec 0
  831.  
  832. show       :: Text a => a -> String
  833. show x      = shows x ""
  834.  
  835. showChar   :: Char -> ShowS
  836. showChar    = (:)
  837.  
  838. showString :: String -> ShowS
  839. showString  = (++)
  840.  
  841. instance Text () where
  842.     showsPrec d ()    = showString "()"
  843.  
  844. instance Text Bool where
  845.     showsPrec d True  = showString "True"
  846.     showsPrec d False = showString "False"
  847.  
  848. primitive primShowsInt "primShowsInt" :: Int -> Int -> String -> String
  849. instance Text Int where showsPrec = primShowsInt
  850.  
  851. {- PC version off -}
  852. primitive primShowsFloat "primShowsFloat" :: Int -> Float -> String -> String
  853. instance Text Float where showsPrec = primShowsFloat
  854.  
  855.  
  856.                                       109
  857.  
  858.  
  859.  
  860.  
  861. Introduction to Gofer          APPENDIX B: CONTENTS OF STANDARD PRELUDE
  862.  
  863.  
  864. {- PC version on -}
  865.  
  866. instance Text Char where
  867.     showsPrec p c = showString [q, c, q] where q = '\''
  868.     showList cs   = showChar '"' . showl cs
  869.                     where showl ""       = showChar '"'
  870.                           showl ('"':cs) = showString "\\\"" . showl cs
  871.                           showl (c:cs)   = showChar c . showl cs
  872.               -- Haskell has   showLitChar c . showl cs
  873.  
  874. instance Text a => Text [a]  where
  875.     showsPrec p = showList
  876.  
  877. instance (Text a, Text b) => Text (a,b) where
  878.     showsPrec p (x,y) = showChar '(' . shows x . showChar ',' .
  879.                                        shows y . showChar ')'
  880.  
  881. -- I/O functions and definitions: -------------------------------------------
  882.  
  883. stdin         =  "stdin"
  884. stdout        =  "stdout"
  885. stderr        =  "stderr"
  886. stdecho       =  "stdecho"
  887.  
  888. {- The Dialogue, Request, Response and IOError datatypes are now builtin:
  889. data Request  =  -- file system requests:
  890.                 ReadFile      String         
  891.               | WriteFile     String String
  892.               | AppendFile    String String
  893.                  -- channel system requests:
  894.               | ReadChan      String 
  895.               | AppendChan    String String
  896.                  -- environment requests:
  897.               | Echo          Bool
  898.           | GetArgs
  899.           | GetProgName
  900.           | GetEnv        String
  901.  
  902. data Response = Success
  903.               | Str     String 
  904.               | Failure IOError
  905.           | StrList [String]
  906.  
  907. data IOError  = WriteError   String
  908.               | ReadError    String
  909.               | SearchError  String
  910.               | FormatError  String
  911.               | OtherError   String
  912.  
  913. type Dialogue    =  [Response] -> [Request]
  914. -}
  915.  
  916. type SuccCont    =                Dialogue
  917. type StrCont     =  String     -> Dialogue
  918. type StrListCont =  [String]   -> Dialogue
  919. type FailCont    =  IOError    -> Dialogue
  920.  
  921.  
  922.                                       110
  923.  
  924.  
  925.  
  926.  
  927. Introduction to Gofer          APPENDIX B: CONTENTS OF STANDARD PRELUDE
  928.  
  929.  
  930.  
  931. done            ::                                                Dialogue
  932. readFile        :: String ->           FailCont -> StrCont     -> Dialogue
  933. writeFile       :: String -> String -> FailCont -> SuccCont    -> Dialogue
  934. appendFile      :: String -> String -> FailCont -> SuccCont    -> Dialogue
  935. readChan        :: String ->           FailCont -> StrCont     -> Dialogue
  936. appendChan      :: String -> String -> FailCont -> SuccCont    -> Dialogue
  937. echo            :: Bool ->             FailCont -> SuccCont    -> Dialogue
  938. getArgs         ::                     FailCont -> StrListCont -> Dialogue
  939. getProgName     ::               FailCont -> StrCont     -> Dialogue
  940. getEnv        :: String ->           FailCont -> StrCont     -> Dialogue
  941.  
  942. done resps    =  []
  943. readFile name fail succ resps =
  944.      (ReadFile name) : strDispatch fail succ resps
  945. writeFile name contents fail succ resps =
  946.     (WriteFile name contents) : succDispatch fail succ resps
  947. appendFile name contents fail succ resps =
  948.     (AppendFile name contents) : succDispatch fail succ resps
  949. readChan name fail succ resps =
  950.     (ReadChan name) : strDispatch fail succ resps
  951. appendChan name contents fail succ resps =
  952.     (AppendChan name contents) : succDispatch fail succ resps
  953. echo bool fail succ resps =
  954.     (Echo bool) : succDispatch fail succ resps
  955. getArgs fail succ resps =
  956.     GetArgs : strListDispatch fail succ resps
  957. getProgName fail succ resps =
  958.     GetProgName : strDispatch fail succ resps
  959. getEnv name fail succ resps =
  960.     (GetEnv name) : strDispatch fail succ resps
  961.  
  962. strDispatch fail succ (resp:resps) = 
  963.             case resp of Str val     -> succ val resps
  964.                          Failure msg -> fail msg resps
  965.  
  966. succDispatch fail succ (resp:resps) = 
  967.             case resp of Success     -> succ resps
  968.                          Failure msg -> fail msg resps
  969.  
  970. strListDispatch fail succ (resp:resps) =
  971.         case resp of StrList val -> succ val resps
  972.              Failure msg -> fail msg resps
  973.  
  974. abort           :: FailCont
  975. abort err        = done
  976.  
  977. exit            :: FailCont
  978. exit err         = appendChan stderr msg abort done
  979.                    where msg = case err of ReadError s   -> s
  980.                                            WriteError s  -> s
  981.                                            SearchError s -> s
  982.                                            FormatError s -> s
  983.                                            OtherError s  -> s
  984.  
  985. print           :: Text a => a -> Dialogue
  986.  
  987.  
  988.                                       111
  989.  
  990.  
  991.  
  992.  
  993. Introduction to Gofer          APPENDIX B: CONTENTS OF STANDARD PRELUDE
  994.  
  995.  
  996. print x          = appendChan stdout (show x) exit done
  997.  
  998. prints          :: Text a => a -> String -> Dialogue
  999. prints x s       = appendChan stdout (shows x s) exit done
  1000.  
  1001. interact    :: (String -> String) -> Dialogue
  1002. interact f     = readChan stdin exit
  1003.                 (\x -> appendChan stdout (f x) exit done)
  1004.  
  1005. run        :: (String -> String) -> Dialogue
  1006. run f         = echo False exit (interact f)
  1007.  
  1008. primitive primFopen "primFopen" :: String -> a -> (String -> a) -> a
  1009.  
  1010. openfile        :: String -> String
  1011. openfile f       = primFopen f (error ("can't open file "++f)) id
  1012.  
  1013. -- End of Gofer standard prelude: --------------------------------------------
  1014.  
  1015.  
  1016.  
  1017.  
  1018.  
  1019.  
  1020.  
  1021.  
  1022.  
  1023.  
  1024.  
  1025.  
  1026.  
  1027.  
  1028.  
  1029.  
  1030.  
  1031.  
  1032.  
  1033.  
  1034.  
  1035.  
  1036.  
  1037.  
  1038.  
  1039.  
  1040.  
  1041.  
  1042.  
  1043.  
  1044.  
  1045.  
  1046.  
  1047.  
  1048.  
  1049.  
  1050.  
  1051.  
  1052.  
  1053.  
  1054.                                       112
  1055.  
  1056.  
  1057.