home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / gofer230.zip / Progs / Gofer / Docs / appx_b < prev    next >
Text File  |  1994-06-23  |  30KB  |  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.30
  16. --    Copyright Mark P Jones 1991-1994.
  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 b@(m,n) i
  229.        | inRange b i = i - m
  230.        | otherwise   = error "index out of range"
  231.     inRange (m,n) i  = m <= i && i <= n
  232.  
  233. instance Enum Int where
  234.     enumFrom n       = iterate (1+) n
  235.     enumFromThen n m = iterate ((m-n)+) n
  236.  
  237. instance Num Int where
  238.     (+)           = primPlusInt
  239.     (-)           = primMinusInt
  240.     (*)           = primMulInt
  241.     (/)           = primDivInt
  242.     negate        = primNegInt
  243.     fromInteger x = x
  244.  
  245. {- PC version off -}
  246. primitive primEqFloat    "primEqFloat",
  247.           primLeFloat    "primLeFloat"    :: Float -> Float -> Bool
  248. primitive primPlusFloat  "primPlusFloat", 
  249.           primMinusFloat "primMinusFloat", 
  250.           primDivFloat   "primDivFloat",
  251.           primMulFloat   "primMulFloat"   :: Float -> Float -> Float 
  252. primitive primNegFloat   "primNegFloat"   :: Float -> Float
  253. primitive primIntToFloat "primIntToFloat" :: Int -> Float
  254.  
  255. instance Eq Float where (==) = primEqFloat
  256.  
  257. instance Ord Float where (<=) = primLeFloat
  258.  
  259. instance Enum Float where
  260.  
  261.  
  262.                                       100
  263.  
  264.  
  265.  
  266.  
  267. Introduction to Gofer          APPENDIX B: CONTENTS OF STANDARD PRELUDE
  268.  
  269.  
  270.     enumFrom n       = iterate (1.0+) n
  271.     enumFromThen n m = iterate ((m-n)+) n
  272.  
  273. instance Num Float where
  274.     (+)         = primPlusFloat
  275.     (-)         = primMinusFloat
  276.     (*)         = primMulFloat
  277.     (/)         = primDivFloat 
  278.     negate      = primNegFloat
  279.     fromInteger = primIntToFloat
  280.  
  281. primitive sin "primSinFloat",  asin  "primAsinFloat",
  282.           cos "primCosFloat",  acos  "primAcosFloat",
  283.       tan "primTanFloat",  atan  "primAtanFloat",
  284.           log "primLogFloat",  log10 "primLog10Float",
  285.       exp "primExpFloat",  sqrt  "primSqrtFloat" :: Float -> Float
  286. primitive atan2    "primAtan2Float" :: Float -> Float -> Float
  287. primitive truncate "primFloatToInt" :: Float -> Int
  288.  
  289. pi :: Float
  290. pi  = 3.1415926535
  291.  
  292. {- PC version on -}
  293.  
  294. primitive primEqChar   "primEqChar",
  295.       primLeChar   "primLeChar"  :: Char -> Char -> Bool
  296.  
  297. instance Eq Char  where (==) = primEqChar   -- c == d  =  ord c == ord d
  298.  
  299. instance Ord Char where (<=) = primLeChar   -- c <= d  =  ord c <= ord d
  300.  
  301. instance Ix Char where
  302.     range (c,c')      = [c..c']
  303.     index b@(m,n) i
  304.        | inRange b i  = ord i - ord m
  305.        | otherwise    = error "index out of range"
  306.     inRange (c,c') ci = ord c <= i && i <= ord c' where i = ord ci
  307.  
  308. instance Enum Char where
  309.     enumFrom c        = map chr [ord c .. ord maxChar]
  310.     enumFromThen c c' = map chr [ord c, ord c' .. ord lastChar]
  311.                         where lastChar = if c' < c then minChar else maxChar
  312.  
  313. instance Eq a => Eq [a] where
  314.     []     == []     =  True
  315.     []     == (y:ys) =  False
  316.     (x:xs) == []     =  False
  317.     (x:xs) == (y:ys) =  x==y && xs==ys
  318.  
  319. instance Ord a => Ord [a] where
  320.     []     <= _      =  True
  321.     (_:_)  <= []     =  False
  322.     (x:xs) <= (y:ys) =  x<y || (x==y && xs<=ys)
  323.  
  324. instance (Eq a, Eq b) => Eq (a,b) where
  325.     (x,y) == (u,v)  =  x==u && y==v
  326.  
  327.  
  328.                                       101
  329.  
  330.  
  331.  
  332.  
  333. Introduction to Gofer          APPENDIX B: CONTENTS OF STANDARD PRELUDE
  334.  
  335.  
  336. instance (Ord a, Ord b) => Ord (a,b) where
  337.     (x,y) <= (u,v)  = x<u  ||  (x==u && y<=v)
  338.  
  339. instance Eq Bool where
  340.     True  == True   =  True
  341.     False == False  =  True
  342.     _     == _      =  False
  343.  
  344. instance Ord Bool where
  345.     False <= x      = True
  346.     True  <= x      = x
  347.  
  348. -- Standard numerical functions: --------------------------------------------
  349.  
  350. primitive div    "primDivInt",
  351.       quot   "primQuotInt",
  352.           rem    "primRemInt",
  353.           mod    "primModInt"    :: Int -> Int -> Int
  354.  
  355. subtract  :: Num a => a -> a -> a
  356. subtract   = flip (-)
  357.  
  358. even, odd :: Int -> Bool
  359. even x     = x `rem` 2 == 0
  360. odd        = not . even
  361.  
  362. gcd       :: Int -> Int -> Int
  363. gcd x y    = gcd' (abs x) (abs y)
  364.              where gcd' x 0 = x
  365.                    gcd' x y = gcd' y (x `rem` y)
  366.  
  367. lcm       :: Int -> Int -> Int
  368. lcm _ 0    = 0
  369. lcm 0 _    = 0
  370. lcm x y    = abs ((x `quot` gcd x y) * y)
  371.  
  372. (^)       :: Num a => a -> Int -> a
  373. x ^ 0      = fromInteger 1
  374. x ^ (n+1)  = f x n x
  375.              where f _ 0 y = y
  376.                    f x n y = g x n where
  377.                              g x n | even n    = g (x*x) (n`quot`2)
  378.                                    | otherwise = f x (n-1) (x*y)
  379.  
  380. abs                     :: (Num a, Ord a) => a -> a
  381. abs x | x>=fromInteger 0 = x
  382.       | otherwise        = -x
  383.  
  384. signum            :: (Num a, Ord a) => a -> Int
  385. signum x
  386.       | x==fromInteger 0 = 0
  387.       | x> fromInteger 0 = 1
  388.       | otherwise        = -1
  389.  
  390. sum, product    :: Num a => [a] -> a
  391. sum              = foldl' (+) (fromInteger 0)
  392.  
  393.  
  394.                                       102
  395.  
  396.  
  397.  
  398.  
  399. Introduction to Gofer          APPENDIX B: CONTENTS OF STANDARD PRELUDE
  400.  
  401.  
  402. product          = foldl' (*) (fromInteger 1)
  403.  
  404. sums, products    :: Num a => [a] -> [a]
  405. sums             = scanl (+) (fromInteger 0)
  406. products         = scanl (*) (fromInteger 1)
  407.  
  408. -- Standard list processing functions: --------------------------------------
  409.  
  410. head             :: [a] -> a
  411. head (x:_)        = x
  412.  
  413. last             :: [a] -> a
  414. last [x]          = x
  415. last (_:xs)       = last xs
  416.  
  417. tail             :: [a] -> [a]
  418. tail (_:xs)       = xs
  419.  
  420. init             :: [a] -> [a]
  421. init [x]          = []
  422. init (x:xs)       = x : init xs
  423.  
  424. (++)             :: [a] -> [a] -> [a]    -- append lists.  Associative with
  425. []     ++ ys      = ys                   -- left and right identity [].
  426. (x:xs) ++ ys      = x:(xs++ys)
  427.  
  428. genericLength    :: Num a => [b] -> a
  429. genericLength     = foldl' (\n _ -> n + fromInteger 1) (fromInteger 0)
  430.  
  431. length         :: [a] -> Int           -- calculate length of list
  432. length            = foldl' (\n _ -> n+1) 0
  433.  
  434. (!!)             :: [a] -> Int -> a      -- xs!!n selects the nth element of
  435. (x:_)  !! 0       = x                    -- the list xs (first element xs!!0)
  436. (_:xs) !! (n+1)   = xs !! n              -- for any n < length xs.
  437.  
  438. iterate          :: (a -> a) -> a -> [a] -- generate the infinite list
  439. iterate f x       = x : iterate f (f x)  -- [x, f x, f (f x), ...
  440.  
  441. repeat           :: a -> [a]             -- generate the infinite list
  442. repeat x          = xs where xs = x:xs   -- [x, x, x, x, ...
  443.  
  444. cycle            :: [a] -> [a]           -- generate the infinite list
  445. cycle xs          = xs' where xs'=xs++xs'-- xs ++ xs ++ xs ++ ...
  446.  
  447. copy             :: Int -> a -> [a]      -- make list of n copies of x
  448. copy n x          = take n xs where xs = x:xs
  449.  
  450. nub              :: Eq a => [a] -> [a]   -- remove duplicates from list
  451. nub []            = []
  452. nub (x:xs)        = x : nub (filter (x/=) xs)
  453.  
  454. reverse          :: [a] -> [a]           -- reverse elements of list
  455. reverse           = foldl (flip (:)) []
  456.  
  457. elem, notElem    :: Eq a => a -> [a] -> Bool
  458.  
  459.  
  460.                                       103
  461.  
  462.  
  463.  
  464.  
  465. Introduction to Gofer          APPENDIX B: CONTENTS OF STANDARD PRELUDE
  466.  
  467.  
  468. elem              = any . (==)           -- test for membership in list
  469. notElem           = all . (/=)           -- test for non-membership
  470.  
  471. maximum, minimum :: Ord a => [a] -> a
  472. maximum           = foldl1 max          -- max element in non-empty list
  473. minimum           = foldl1 min          -- min element in non-empty list
  474.  
  475. concat           :: [[a]] -> [a]        -- concatenate list of lists
  476. concat            = foldr (++) []
  477.  
  478. transpose        :: [[a]] -> [[a]]      -- transpose list of lists
  479. transpose         = foldr
  480.                       (\xs xss -> zipWith (:) xs (xss ++ repeat []))
  481.                       []
  482.  
  483. -- null provides a simple and efficient way of determining whether a given
  484. -- list is empty, without using (==) and hence avoiding a constraint of the
  485. -- form Eq [a].
  486.  
  487. null             :: [a] -> Bool
  488. null []           = True
  489. null (_:_)        = False
  490.  
  491. -- (\\) is used to remove the first occurrence of each element in the second
  492. -- list from the first list.  It is a kind of inverse of (++) in the sense
  493. -- that  (xs ++ ys) \\ xs = ys for any finite list xs of proper values xs.
  494.  
  495. (\\)             :: Eq a => [a] -> [a] -> [a]
  496. (\\)              = foldl del
  497.                     where []     `del` _  = []
  498.                           (x:xs) `del` y
  499.                              | x == y     = xs
  500.                              | otherwise  = x : xs `del` y
  501.  
  502.  
  503. -- map f xs applies the function f to each element of the list xs returning
  504. -- the corresponding list of results.  filter p xs returns the sublist of xs
  505. -- containing those elements which satisfy the predicate p.
  506.  
  507. map              :: (a -> b) -> [a] -> [b]
  508. map f []          = []
  509. map f (x:xs)      = f x : map f xs
  510.  
  511. filter           :: (a -> Bool) -> [a] -> [a]
  512. filter _ []       = []
  513. filter p (x:xs)
  514.     | p x         = x : xs'
  515.     | otherwise   = xs'
  516.                   where xs' = filter p xs
  517.  
  518. -- Fold primitives:  The foldl and scanl functions, variants foldl1 and
  519. -- scanl1 for non-empty lists, and strict variants foldl' scanl' describe
  520. -- common patterns of recursion over lists.  Informally:
  521. --
  522. --  foldl f a [x1, x2, ..., xn]  = f (...(f (f a x1) x2)...) xn
  523. --                               = (...((a `f` x1) `f` x2)...) `f` xn
  524.  
  525.  
  526.                                       104
  527.  
  528.  
  529.  
  530.  
  531. Introduction to Gofer          APPENDIX B: CONTENTS OF STANDARD PRELUDE
  532.  
  533.  
  534. -- etc...
  535. --
  536. -- The functions foldr, scanr and variants foldr1, scanr1 are duals of these
  537. -- functions:
  538. -- e.g.  foldr f a xs = foldl (flip f) a (reverse xs)  for finite lists xs.
  539.  
  540. foldl            :: (a -> b -> a) -> a -> [b] -> a
  541. foldl f z []      = z
  542. foldl f z (x:xs)  = foldl f (f z x) xs
  543.  
  544. foldl1           :: (a -> a -> a) -> [a] -> a
  545. foldl1 f (x:xs)   = foldl f x xs
  546.  
  547. foldl'           :: (a -> b -> a) -> a -> [b] -> a
  548. foldl' f a []     =  a
  549. foldl' f a (x:xs) =  strict (foldl' f) (f a x) xs
  550.  
  551. scanl            :: (a -> b -> a) -> a -> [b] -> [a]
  552. scanl f q xs      = q : (case xs of
  553.                          []   -> []
  554.                          x:xs -> scanl f (f q x) xs)
  555.  
  556. scanl1           :: (a -> a -> a) -> [a] -> [a]
  557. scanl1 f (x:xs)   = scanl f x xs
  558.  
  559. scanl'           :: (a -> b -> a) -> a -> [b] -> [a]
  560. scanl' f q xs     = q : (case xs of
  561.                          []   -> []
  562.                          x:xs -> strict (scanl' f) (f q x) xs)
  563.  
  564. foldr            :: (a -> b -> b) -> b -> [a] -> b
  565. foldr f z []      = z
  566. foldr f z (x:xs)  = f x (foldr f z xs)
  567.  
  568. foldr1           :: (a -> a -> a) -> [a] -> a
  569. foldr1 f [x]      = x
  570. foldr1 f (x:xs)   = f x (foldr1 f xs)
  571.  
  572. scanr            :: (a -> b -> b) -> b -> [a] -> [b]
  573. scanr f q0 []     = [q0]
  574. scanr f q0 (x:xs) = f x q : qs
  575.                     where qs@(q:_) = scanr f q0 xs
  576.  
  577. scanr1           :: (a -> a -> a) -> [a] -> [a]
  578. scanr1 f [x]      = [x]
  579. scanr1 f (x:xs)   = f x q : qs
  580.                     where qs@(q:_) = scanr1 f xs
  581.  
  582. -- List breaking functions:
  583. --
  584. --   take n xs       returns the first n elements of xs
  585. --   drop n xs       returns the remaining elements of xs
  586. --   splitAt n xs    = (take n xs, drop n xs)
  587. --
  588. --   takeWhile p xs  returns the longest initial segment of xs whose
  589. --                   elements satisfy p
  590.  
  591.  
  592.                                       105
  593.  
  594.  
  595.  
  596.  
  597. Introduction to Gofer          APPENDIX B: CONTENTS OF STANDARD PRELUDE
  598.  
  599.  
  600. --   dropWhile p xs  returns the remaining portion of the list
  601. --   span p xs       = (takeWhile p xs, dropWhile p xs)
  602. --
  603. --   takeUntil p xs  returns the list of elements upto and including the
  604. --                   first element of xs which satisfies p
  605.  
  606. take                :: Int -> [a] -> [a]
  607. take 0     _         = []
  608. take _     []        = []
  609. take (n+1) (x:xs)    = x : take n xs
  610.  
  611. drop                :: Int -> [a] -> [a]
  612. drop 0     xs        = xs
  613. drop _     []        = []
  614. drop (n+1) (_:xs)    = drop n xs
  615.  
  616. splitAt             :: Int -> [a] -> ([a], [a])
  617. splitAt 0     xs     = ([],xs)
  618. splitAt _     []     = ([],[])
  619. splitAt (n+1) (x:xs) = (x:xs',xs'') where (xs',xs'') = splitAt n xs
  620.  
  621. takeWhile           :: (a -> Bool) -> [a] -> [a]
  622. takeWhile p []       = []
  623. takeWhile p (x:xs)
  624.          | p x       = x : takeWhile p xs
  625.          | otherwise = []
  626.  
  627. takeUntil           :: (a -> Bool) -> [a] -> [a]
  628. takeUntil p []       = []
  629. takeUntil p (x:xs)
  630.        | p x         = [x]
  631.        | otherwise   = x : takeUntil p xs
  632.  
  633. dropWhile           :: (a -> Bool) -> [a] -> [a]
  634. dropWhile p []       = []
  635. dropWhile p xs@(x:xs')
  636.          | p x       = dropWhile p xs'
  637.          | otherwise = xs
  638.  
  639. span, break         :: (a -> Bool) -> [a] -> ([a],[a])
  640. span p []            = ([],[])
  641. span p xs@(x:xs')
  642.          | p x       = let (ys,zs) = span p xs' in (x:ys,zs)
  643.          | otherwise = ([],xs)
  644. break p              = span (not . p)
  645.  
  646. -- Text processing:
  647. --   lines s     returns the list of lines in the string s.
  648. --   words s     returns the list of words in the string s.
  649. --   unlines ls  joins the list of lines ls into a single string
  650. --               with lines separated by newline characters.
  651. --   unwords ws  joins the list of words ws into a single string
  652. --               with words separated by spaces.
  653.  
  654. lines     :: String -> [String]
  655. lines ""   = []
  656.  
  657.  
  658.                                       106
  659.  
  660.  
  661.  
  662.  
  663. Introduction to Gofer          APPENDIX B: CONTENTS OF STANDARD PRELUDE
  664.  
  665.  
  666. lines s    = l : (if null s' then [] else lines (tail s'))
  667.              where (l, s') = break ('\n'==) s
  668.  
  669. words     :: String -> [String]
  670. words s    = case dropWhile isSpace s of
  671.                   "" -> []
  672.                   s' -> w : words s''
  673.                         where (w,s'') = break isSpace s'
  674.  
  675. unlines   :: [String] -> String
  676. unlines    = concat . map (\l -> l ++ "\n")
  677.  
  678. unwords   :: [String] -> String
  679. unwords [] = []
  680. unwords ws = foldr1 (\w s -> w ++ ' ':s) ws
  681.  
  682. -- Merging and sorting lists:
  683.  
  684. merge               :: Ord a => [a] -> [a] -> [a] 
  685. merge []     ys      = ys
  686. merge xs     []      = xs
  687. merge (x:xs) (y:ys)
  688.         | x <= y     = x : merge xs (y:ys)
  689.         | otherwise  = y : merge (x:xs) ys
  690.  
  691. sort                :: Ord a => [a] -> [a]
  692. sort                 = foldr insert []
  693.  
  694. insert              :: Ord a => a -> [a] -> [a]
  695. insert x []          = [x]
  696. insert x (y:ys)
  697.         | x <= y     = x:y:ys
  698.         | otherwise  = y:insert x ys
  699.  
  700. qsort               :: Ord a => [a] -> [a]
  701. qsort []             = []
  702. qsort (x:xs)         = qsort [ u | u<-xs, u<x ] ++
  703.                              [ x ] ++
  704.                        qsort [ u | u<-xs, u>=x ]
  705.  
  706. -- zip and zipWith families of functions:
  707.  
  708. zip  :: [a] -> [b] -> [(a,b)]
  709. zip   = zipWith  (\a b -> (a,b))
  710.  
  711. zip3 :: [a] -> [b] -> [c] -> [(a,b,c)]
  712. zip3  = zipWith3 (\a b c -> (a,b,c))
  713.  
  714. zip4 :: [a] -> [b] -> [c] -> [d] -> [(a,b,c,d)]
  715. zip4  = zipWith4 (\a b c d -> (a,b,c,d))
  716.  
  717. zip5 :: [a] -> [b] -> [c] -> [d] -> [e] -> [(a,b,c,d,e)]
  718. zip5  = zipWith5 (\a b c d e -> (a,b,c,d,e))
  719.  
  720. zip6 :: [a] -> [b] -> [c] -> [d] -> [e] -> [f] -> [(a,b,c,d,e,f)]
  721. zip6  = zipWith6 (\a b c d e f -> (a,b,c,d,e,f))
  722.  
  723.  
  724.                                       107
  725.  
  726.  
  727.  
  728.  
  729. Introduction to Gofer          APPENDIX B: CONTENTS OF STANDARD PRELUDE
  730.  
  731.  
  732. zip7 :: [a] -> [b] -> [c] -> [d] -> [e] -> [f] -> [g] -> [(a,b,c,d,e,f,g)]
  733. zip7  = zipWith7 (\a b c d e f g -> (a,b,c,d,e,f,g))
  734.  
  735.  
  736. zipWith                  :: (a->b->c) -> [a]->[b]->[c]
  737. zipWith z (a:as) (b:bs)   = z a b : zipWith z as bs
  738. zipWith _ _      _        = []
  739.  
  740. zipWith3                 :: (a->b->c->d) -> [a]->[b]->[c]->[d]
  741. zipWith3 z (a:as) (b:bs) (c:cs)
  742.                           = z a b c : zipWith3 z as bs cs
  743. zipWith3 _ _ _ _          = []
  744.  
  745. zipWith4                 :: (a->b->c->d->e) -> [a]->[b]->[c]->[d]->[e]
  746. zipWith4 z (a:as) (b:bs) (c:cs) (d:ds)
  747.                           = z a b c d : zipWith4 z as bs cs ds
  748. zipWith4 _ _ _ _ _        = []
  749.  
  750. zipWith5                 :: (a->b->c->d->e->f) -> [a]->[b]->[c]->[d]->[e]->[f]
  751. zipWith5 z (a:as) (b:bs) (c:cs) (d:ds) (e:es)
  752.                           = z a b c d e : zipWith5 z as bs cs ds es
  753. zipWith5 _ _ _ _ _ _      = []
  754.  
  755. zipWith6                 :: (a->b->c->d->e->f->g)
  756.                             -> [a]->[b]->[c]->[d]->[e]->[f]->[g]
  757. zipWith6 z (a:as) (b:bs) (c:cs) (d:ds) (e:es) (f:fs)
  758.                           = z a b c d e f : zipWith6 z as bs cs ds es fs
  759. zipWith6 _ _ _ _ _ _ _    = []
  760.  
  761. zipWith7                 :: (a->b->c->d->e->f->g->h)
  762.                              -> [a]->[b]->[c]->[d]->[e]->[f]->[g]->[h]
  763. zipWith7 z (a:as) (b:bs) (c:cs) (d:ds) (e:es) (f:fs) (g:gs)
  764.                           = z a b c d e f g : zipWith7 z as bs cs ds es fs gs
  765. zipWith7 _ _ _ _ _ _ _ _  = []
  766.  
  767. unzip                    :: [(a,b)] -> ([a],[b])
  768. unzip                     = foldr (\(a,b) ~(as,bs) -> (a:as, b:bs)) ([], [])
  769.  
  770. -- Formatted output: --------------------------------------------------------
  771.  
  772. primitive primPrint "primPrint"  :: Int -> a -> String -> String
  773.  
  774. show'       :: a -> String
  775. show' x      = primPrint 0 x []
  776.  
  777. cjustify, ljustify, rjustify :: Int -> String -> String
  778.  
  779. cjustify n s = space halfm ++ s ++ space (m - halfm)
  780.                where m     = n - length s
  781.                      halfm = m `div` 2
  782. ljustify n s = s ++ space (n - length s)
  783. rjustify n s = space (n - length s) ++ s
  784.  
  785. space       :: Int -> String
  786. space n      = copy n ' '
  787.  
  788.  
  789.  
  790.                                       108
  791.  
  792.  
  793.  
  794.  
  795. Introduction to Gofer          APPENDIX B: CONTENTS OF STANDARD PRELUDE
  796.  
  797.  
  798. layn        :: [String] -> String
  799. layn         = lay 1 where lay _ []     = []
  800.                            lay n (x:xs) = rjustify 4 (show n) ++ ") "
  801.                                            ++ x ++ "\n" ++ lay (n+1) xs
  802.  
  803. -- Miscellaneous: -----------------------------------------------------------
  804.  
  805. until                  :: (a -> Bool) -> (a -> a) -> a -> a
  806. until p f x | p x       = x
  807.             | otherwise = until p f (f x)
  808.  
  809. until'                 :: (a -> Bool) -> (a -> a) -> a -> [a]
  810. until' p f              = takeUntil p . iterate f
  811.  
  812. primitive error "primError" :: String -> a
  813.  
  814. undefined              :: a
  815. undefined | False       = undefined
  816.  
  817. asTypeOf               :: a -> a -> a
  818. x `asTypeOf` _          = x
  819.  
  820. -- A trimmed down version of the Haskell Text class: ------------------------
  821.  
  822. type  ShowS   = String -> String
  823.  
  824. class Text a where 
  825.     showsPrec      :: Int -> a -> ShowS
  826.     showList       :: [a] -> ShowS
  827.  
  828.     showsPrec       = primPrint
  829.     showList []     = showString "[]"
  830.     showList (x:xs) = showChar '[' . shows x . showl xs
  831.                       where showl []     = showChar ']'
  832.                             showl (x:xs) = showChar ',' . shows x . showl xs
  833.  
  834. shows      :: Text a => a -> ShowS
  835. shows       = showsPrec 0
  836.  
  837. show       :: Text a => a -> String
  838. show x      = shows x ""
  839.  
  840. showChar   :: Char -> ShowS
  841. showChar    = (:)
  842.  
  843. showString :: String -> ShowS
  844. showString  = (++)
  845.  
  846. instance Text () where
  847.     showsPrec d ()    = showString "()"
  848.  
  849. instance Text Bool where
  850.     showsPrec d True  = showString "True"
  851.     showsPrec d False = showString "False"
  852.  
  853. primitive primShowsInt "primShowsInt" :: Int -> Int -> String -> String
  854.  
  855.  
  856.                                       109
  857.  
  858.  
  859.  
  860.  
  861. Introduction to Gofer          APPENDIX B: CONTENTS OF STANDARD PRELUDE
  862.  
  863.  
  864. instance Text Int where showsPrec = primShowsInt
  865.  
  866. {- PC version off -}
  867. primitive primShowsFloat "primShowsFloat" :: Int -> Float -> String -> String
  868. instance Text Float where showsPrec = primShowsFloat
  869. {- PC version on -}
  870.  
  871. instance Text Char where
  872.     showsPrec p c = showString [q, c, q] where q = '\''
  873.     showList cs   = showChar '"' . showl cs
  874.                     where showl ""       = showChar '"'
  875.                           showl ('"':cs) = showString "\\\"" . showl cs
  876.                           showl (c:cs)   = showChar c . showl cs
  877.               -- Haskell has   showLitChar c . showl cs
  878.  
  879. instance Text a => Text [a]  where
  880.     showsPrec p = showList
  881.  
  882. instance (Text a, Text b) => Text (a,b) where
  883.     showsPrec p (x,y) = showChar '(' . shows x . showChar ',' .
  884.                                        shows y . showChar ')'
  885.  
  886. -- I/O functions and definitions: -------------------------------------------
  887.  
  888. stdin         =  "stdin"
  889. stdout        =  "stdout"
  890. stderr        =  "stderr"
  891. stdecho       =  "stdecho"
  892.  
  893. {- The Dialogue, Request, Response and IOError datatypes are now builtin:
  894. data Request  =  -- file system requests:
  895.                 ReadFile      String         
  896.               | WriteFile     String String
  897.               | AppendFile    String String
  898.                  -- channel system requests:
  899.               | ReadChan      String 
  900.               | AppendChan    String String
  901.                  -- environment requests:
  902.               | Echo          Bool
  903.           | GetArgs
  904.           | GetProgName
  905.           | GetEnv        String
  906.  
  907. data Response = Success
  908.               | Str     String 
  909.               | Failure IOError
  910.           | StrList [String]
  911.  
  912. data IOError  = WriteError   String
  913.               | ReadError    String
  914.               | SearchError  String
  915.               | FormatError  String
  916.               | OtherError   String
  917.  
  918. type Dialogue    =  [Response] -> [Request]
  919. -}
  920.  
  921.  
  922.                                       110
  923.  
  924.  
  925.  
  926.  
  927. Introduction to Gofer          APPENDIX B: CONTENTS OF STANDARD PRELUDE
  928.  
  929.  
  930. type SuccCont    =                Dialogue
  931. type StrCont     =  String     -> Dialogue
  932. type StrListCont =  [String]   -> Dialogue
  933. type FailCont    =  IOError    -> Dialogue
  934.  
  935. done            ::                                                Dialogue
  936. readFile        :: String ->           FailCont -> StrCont     -> Dialogue
  937. writeFile       :: String -> String -> FailCont -> SuccCont    -> Dialogue
  938. appendFile      :: String -> String -> FailCont -> SuccCont    -> Dialogue
  939. readChan        :: String ->           FailCont -> StrCont     -> Dialogue
  940. appendChan      :: String -> String -> FailCont -> SuccCont    -> Dialogue
  941. echo            :: Bool ->             FailCont -> SuccCont    -> Dialogue
  942. getArgs         ::                     FailCont -> StrListCont -> Dialogue
  943. getProgName     ::               FailCont -> StrCont     -> Dialogue
  944. getEnv        :: String ->           FailCont -> StrCont     -> Dialogue
  945.  
  946. done resps    =  []
  947. readFile name fail succ resps =
  948.      (ReadFile name) : strDispatch fail succ resps
  949. writeFile name contents fail succ resps =
  950.     (WriteFile name contents) : succDispatch fail succ resps
  951. appendFile name contents fail succ resps =
  952.     (AppendFile name contents) : succDispatch fail succ resps
  953. readChan name fail succ resps =
  954.     (ReadChan name) : strDispatch fail succ resps
  955. appendChan name contents fail succ resps =
  956.     (AppendChan name contents) : succDispatch fail succ resps
  957. echo bool fail succ resps =
  958.     (Echo bool) : succDispatch fail succ resps
  959. getArgs fail succ resps =
  960.     GetArgs : strListDispatch fail succ resps
  961. getProgName fail succ resps =
  962.     GetProgName : strDispatch fail succ resps
  963. getEnv name fail succ resps =
  964.     (GetEnv name) : strDispatch fail succ resps
  965.  
  966. strDispatch fail succ (resp:resps) = 
  967.             case resp of Str val     -> succ val resps
  968.                          Failure msg -> fail msg resps
  969.  
  970. succDispatch fail succ (resp:resps) = 
  971.             case resp of Success     -> succ resps
  972.                          Failure msg -> fail msg resps
  973.  
  974. strListDispatch fail succ (resp:resps) =
  975.         case resp of StrList val -> succ val resps
  976.              Failure msg -> fail msg resps
  977.  
  978. abort           :: FailCont
  979. abort err        = done
  980.  
  981. exit            :: FailCont
  982. exit err         = appendChan stderr msg abort done
  983.                    where msg = case err of ReadError s   -> s
  984.                                            WriteError s  -> s
  985.                                            SearchError s -> s
  986.  
  987.  
  988.                                       111
  989.  
  990.  
  991.  
  992.  
  993. Introduction to Gofer          APPENDIX B: CONTENTS OF STANDARD PRELUDE
  994.  
  995.  
  996.                                            FormatError s -> s
  997.                                            OtherError s  -> s
  998.  
  999. print           :: Text a => a -> Dialogue
  1000. print x          = appendChan stdout (show x) exit done
  1001.  
  1002. prints          :: Text a => a -> String -> Dialogue
  1003. prints x s       = appendChan stdout (shows x s) exit done
  1004.  
  1005. interact    :: (String -> String) -> Dialogue
  1006. interact f     = readChan stdin exit
  1007.                 (\x -> appendChan stdout (f x) exit done)
  1008.  
  1009. run        :: (String -> String) -> Dialogue
  1010. run f         = echo False exit (interact f)
  1011.  
  1012. primitive primFopen "primFopen" :: String -> a -> (String -> a) -> a
  1013.  
  1014. openfile        :: String -> String
  1015. openfile f       = primFopen f (error ("can't open file "++f)) id
  1016.  
  1017. -- End of Gofer standard prelude: --------------------------------------------
  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.