home *** CD-ROM | disk | FTP | other *** search
/ ARM Club 1 / ARM_CLUB_CD.iso / contents / apps / languages / progs / gopher / !Gofer / archives / Preludes / cc next >
Encoding:
Text File  |  1993-02-12  |  28.7 KB  |  914 lines

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