home *** CD-ROM | disk | FTP | other *** search
/ ftp.uni-stuttgart.de/pub/systems/acorn/ / Acorn.tar / Acorn / acornet / dev / gofer.spk / !Gofer / preludes / ccprel next >
Text File  |  1993-02-18  |  30KB  |  916 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 
  482. -- second list from the first list.  It is a kind of inverse of (++) in 
  483. -- the sense that  (xs ++ ys) \\ xs = ys for any finite list xs of 
  484. -- proper values xs.
  485.  
  486. (\\)             :: Eq a => [a] -> [a] -> [a]
  487. (\\)              = foldl del
  488.                     where []     `del` _  = []
  489.                           (x:xs) `del` y
  490.                              | x == y     = xs
  491.                              | otherwise  = x : xs `del` y
  492.  
  493. -- Fold primitives:  The foldl and scanl functions, variants foldl1 and
  494. -- scanl1 for non-empty lists, and strict variants foldl' scanl' describe
  495. -- common patterns of recursion over lists.  Informally:
  496. --
  497. --  foldl f a [x1, x2, ..., xn]  = f (...(f (f a x1) x2)...) xn
  498. --                               = (...((a `f` x1) `f` x2)...) `f` xn
  499. -- etc...
  500. --
  501. -- The functions foldr, scanr and variants foldr1, scanr1 are duals of 
  502. -- these functions:
  503. -- e.g.  foldr f a xs = foldl (flip f) a (reverse xs)  for finite lists xs.
  504.  
  505. foldl            :: (a -> b -> a) -> a -> [b] -> a
  506. foldl f z []      = z
  507. foldl f z (x:xs)  = foldl f (f z x) xs
  508.  
  509. foldl1           :: (a -> a -> a) -> [a] -> a
  510. foldl1 f (x:xs)   = foldl f x xs
  511.  
  512. foldl'           :: (a -> b -> a) -> a -> [b] -> a
  513. foldl' f a []     =  a
  514. foldl' f a (x:xs) =  strict (foldl' f) (f a x) xs
  515.  
  516. scanl            :: (a -> b -> a) -> a -> [b] -> [a]
  517. scanl f q xs      = q : (case xs of
  518.                          []   -> []
  519.                          x:xs -> scanl f (f q x) xs)
  520.  
  521. scanl1           :: (a -> a -> a) -> [a] -> [a]
  522. scanl1 f (x:xs)   = scanl f x xs
  523.  
  524. scanl'           :: (a -> b -> a) -> a -> [b] -> [a]
  525. scanl' f q xs     = q : (case xs of
  526.                          []   -> []
  527.                          x:xs -> strict (scanl' f) (f q x) xs)
  528.  
  529. foldr            :: (a -> b -> b) -> b -> [a] -> b
  530. foldr f z []      = z
  531. foldr f z (x:xs)  = f x (foldr f z xs)
  532.  
  533. foldr1           :: (a -> a -> a) -> [a] -> a
  534. foldr1 f [x]      = x
  535. foldr1 f (x:xs)   = f x (foldr1 f xs)
  536.  
  537. scanr            :: (a -> b -> b) -> b -> [a] -> [b]
  538. scanr f q0 []     = [q0]
  539. scanr f q0 (x:xs) = f x q : qs
  540.                     where qs@(q:_) = scanr f q0 xs
  541.  
  542. scanr1           :: (a -> a -> a) -> [a] -> [a]
  543. scanr1 f [x]      = [x]
  544. scanr1 f (x:xs)   = f x q : qs
  545.                     where qs@(q:_) = scanr1 f xs
  546.  
  547. -- List breaking functions:
  548. --
  549. --   take n xs       returns the first n elements of xs
  550. --   drop n xs       returns the remaining elements of xs
  551. --   splitAt n xs    = (take n xs, drop n xs)
  552. --
  553. --   takeWhile p xs  returns the longest initial segment of xs whose
  554. --                   elements satisfy p
  555. --   dropWhile p xs  returns the remaining portion of the list
  556. --   span p xs       = (takeWhile p xs, dropWhile p xs)
  557. --
  558. --   takeUntil p xs  returns the list of elements upto and including the
  559. --                   first element of xs which satisfies p
  560.  
  561. take                :: Int -> [a] -> [a]
  562. take 0     _         = []
  563. take _     []        = []
  564. take (n+1) (x:xs)    = x : take n xs
  565.  
  566. drop                :: Int -> [a] -> [a]
  567. drop 0     xs        = xs
  568. drop _     []        = []
  569. drop (n+1) (_:xs)    = drop n xs
  570.  
  571. splitAt             :: Int -> [a] -> ([a], [a])
  572. splitAt 0     xs     = ([],xs)
  573. splitAt _     []     = ([],[])
  574. splitAt (n+1) (x:xs) = (x:xs',xs'') where (xs',xs'') = splitAt n xs
  575.  
  576. takeWhile           :: (a -> Bool) -> [a] -> [a]
  577. takeWhile p []       = []
  578. takeWhile p (x:xs)
  579.          | p x       = x : takeWhile p xs
  580.          | otherwise = []
  581.  
  582. takeUntil           :: (a -> Bool) -> [a] -> [a]
  583. takeUntil p []       = []
  584. takeUntil p (x:xs)
  585.        | p x         = [x]
  586.        | otherwise   = x : takeUntil p xs
  587.  
  588. dropWhile           :: (a -> Bool) -> [a] -> [a]
  589. dropWhile p []       = []
  590. dropWhile p xs@(x:xs')
  591.          | p x       = dropWhile p xs'
  592.          | otherwise = xs
  593.  
  594. span, break         :: (a -> Bool) -> [a] -> ([a],[a])
  595. span p []            = ([],[])
  596. span p xs@(x:xs')
  597.          | p x       = let (ys,zs) = span p xs' in (x:ys,zs)
  598.          | otherwise = ([],xs)
  599. break p              = span (not . p)
  600.  
  601. -- Text processing:
  602. --   lines s     returns the list of lines in the string s.
  603. --   words s     returns the list of words in the string s.
  604. --   unlines ls  joins the list of lines ls into a single string
  605. --               with lines separated by newline characters.
  606. --   unwords ws  joins the list of words ws into a single string
  607. --               with words separated by spaces.
  608.  
  609. lines     :: String -> [String]
  610. lines ""   = []
  611. lines s    = l : (if null s' then [] else lines (tail s'))
  612.              where (l, s') = break ('\n'==) s
  613.  
  614. words     :: String -> [String]
  615. words s    = case dropWhile isSpace s of
  616.                   "" -> []
  617.                   s' -> w : words s''
  618.                         where (w,s'') = break isSpace s'
  619.  
  620. unlines   :: [String] -> String
  621. unlines    = concat . map (\l -> l ++ "\n")
  622.  
  623. unwords   :: [String] -> String
  624. unwords [] = []
  625. unwords ws = foldr1 (\w s -> w ++ ' ':s) ws
  626.  
  627. -- Merging and sorting lists:
  628.  
  629. merge               :: Ord a => [a] -> [a] -> [a] 
  630. merge []     ys      = ys
  631. merge xs     []      = xs
  632. merge (x:xs) (y:ys)
  633.         | x <= y     = x : merge xs (y:ys)
  634.         | otherwise  = y : merge (x:xs) ys
  635.  
  636. sort                :: Ord a => [a] -> [a]
  637. sort                 = foldr insert []
  638.  
  639. insert              :: Ord a => a -> [a] -> [a]
  640. insert x []          = [x]
  641. insert x (y:ys)
  642.         | x <= y     = x:y:ys
  643.         | otherwise  = y:insert x ys
  644.  
  645. qsort               :: Ord a => [a] -> [a]
  646. qsort []             = []
  647. qsort (x:xs)         = qsort [ u | u<-xs, u<x ] ++
  648.                              [ x ] ++
  649.                        qsort [ u | u<-xs, u>=x ]
  650.  
  651. -- zip and zipWith families of functions:
  652.  
  653. zip  :: [a] -> [b] -> [(a,b)]
  654. zip   = zipWith  (\a b -> (a,b))
  655.  
  656. zip3 :: [a] -> [b] -> [c] -> [(a,b,c)]
  657. zip3  = zipWith3 (\a b c -> (a,b,c))
  658.  
  659. zip4 :: [a] -> [b] -> [c] -> [d] -> [(a,b,c,d)]
  660. zip4  = zipWith4 (\a b c d -> (a,b,c,d))
  661.  
  662. zip5 :: [a] -> [b] -> [c] -> [d] -> [e] -> [(a,b,c,d,e)]
  663. zip5  = zipWith5 (\a b c d e -> (a,b,c,d,e))
  664.  
  665. zip6 :: [a] -> [b] -> [c] -> [d] -> [e] -> [f] -> [(a,b,c,d,e,f)]
  666. zip6  = zipWith6 (\a b c d e f -> (a,b,c,d,e,f))
  667.  
  668. zip7 :: [a] -> [b] -> [c] -> [d] -> [e] -> [f] -> [g] -> [(a,b,c,d,e,f,g)]
  669. zip7  = zipWith7 (\a b c d e f g -> (a,b,c,d,e,f,g))
  670.  
  671.  
  672. zipWith                  :: (a->b->c) -> [a]->[b]->[c]
  673. zipWith z (a:as) (b:bs)   = z a b : zipWith z as bs
  674. zipWith _ _      _        = []
  675.  
  676. zipWith3                 :: (a->b->c->d) -> [a]->[b]->[c]->[d]
  677. zipWith3 z (a:as) (b:bs) (c:cs)
  678.                           = z a b c : zipWith3 z as bs cs
  679. zipWith3 _ _ _ _          = []
  680.  
  681. zipWith4                 :: (a->b->c->d->e) -> [a]->[b]->[c]->[d]->[e]
  682. zipWith4 z (a:as) (b:bs) (c:cs) (d:ds)
  683.                           = z a b c d : zipWith4 z as bs cs ds
  684. zipWith4 _ _ _ _ _        = []
  685.  
  686. zipWith5              :: (a->b->c->d->e->f) -> [a]->[b]->[c]->[d]->[e]->[f]
  687. zipWith5 z (a:as) (b:bs) (c:cs) (d:ds) (e:es)
  688.                           = z a b c d e : zipWith5 z as bs cs ds es
  689. zipWith5 _ _ _ _ _ _      = []
  690.  
  691. zipWith6                 :: (a->b->c->d->e->f->g)
  692.                             -> [a]->[b]->[c]->[d]->[e]->[f]->[g]
  693. zipWith6 z (a:as) (b:bs) (c:cs) (d:ds) (e:es) (f:fs)
  694.                           = z a b c d e f : zipWith6 z as bs cs ds es fs
  695. zipWith6 _ _ _ _ _ _ _    = []
  696.  
  697. zipWith7                 :: (a->b->c->d->e->f->g->h)
  698.                              -> [a]->[b]->[c]->[d]->[e]->[f]->[g]->[h]
  699. zipWith7 z (a:as) (b:bs) (c:cs) (d:ds) (e:es) (f:fs) (g:gs)
  700.                        = z a b c d e f g : zipWith7 z as bs cs ds es fs gs
  701. zipWith7 _ _ _ _ _ _ _ _  = []
  702.  
  703. unzip                    :: [(a,b)] -> ([a],[b])
  704. unzip                   = foldr (\(a,b) ~(as,bs) -> (a:as, b:bs)) ([], [])
  705.  
  706. -- Formatted output: ------------------------------------------------------
  707.  
  708. primitive primPrint "primPrint"  :: Int -> a -> String -> String
  709.  
  710. show'       :: a -> String
  711. show' x      = primPrint 0 x []
  712.  
  713. cjustify, ljustify, rjustify :: Int -> String -> String
  714.  
  715. cjustify n s = space halfm ++ s ++ space (m - halfm)
  716.                where m     = n - length s
  717.                      halfm = m `div` 2
  718. ljustify n s = s ++ space (n - length s)
  719. rjustify n s = space (n - length s) ++ s
  720.  
  721. space       :: Int -> String
  722. space n      = copy n ' '
  723.  
  724. layn        :: [String] -> String
  725. layn         = lay 1 where lay _ []     = []
  726.                            lay n (x:xs) = rjustify 4 (show n) ++ ") "
  727.                                            ++ x ++ "\n" ++ lay (n+1) xs
  728.  
  729. -- Miscellaneous: ---------------------------------------------------------
  730.  
  731. until                  :: (a -> Bool) -> (a -> a) -> a -> a
  732. until p f x | p x       = x
  733.             | otherwise = until p f (f x)
  734.  
  735. until'                 :: (a -> Bool) -> (a -> a) -> a -> [a]
  736. until' p f              = takeUntil p . iterate f
  737.  
  738. primitive error "primError" :: String -> a
  739.  
  740. undefined              :: a
  741. undefined | False       = undefined
  742.  
  743. asTypeOf               :: a -> a -> a
  744. x `asTypeOf` _          = x
  745.  
  746. -- A trimmed down version of the Haskell Text class: ---------------------
  747.  
  748. type  ShowS   = String -> String
  749.  
  750. class Text a where 
  751.     showsPrec      :: Int -> a -> ShowS
  752.     showList       :: [a] -> ShowS
  753.  
  754.     showsPrec       = primPrint
  755.     showList []     = showString "[]"
  756.     showList (x:xs) = showChar '[' . shows x . showl xs
  757.                     where showl []     = showChar ']'
  758.                           showl (x:xs) = showChar ',' . shows x . showl xs
  759.  
  760. shows      :: Text a => a -> ShowS
  761. shows       = showsPrec 0
  762.  
  763. show       :: Text a => a -> String
  764. show x      = shows x ""
  765.  
  766. showChar   :: Char -> ShowS
  767. showChar    = (:)
  768.  
  769. showString :: String -> ShowS
  770. showString  = (++)
  771.  
  772. instance Text () where
  773.     showsPrec d ()    = showString "()"
  774.  
  775. instance Text Bool where
  776.     showsPrec d True  = showString "True"
  777.     showsPrec d False = showString "False"
  778.  
  779. primitive primShowsInt "primShowsInt" :: Int -> Int -> String -> String
  780. instance Text Int where showsPrec = primShowsInt
  781.  
  782. {- PC version off -}
  783. primitive primShowsFloat "primShowsFloat" :: 
  784.                      Int -> Float -> String -> String
  785. instance Text Float where showsPrec = primShowsFloat
  786. {- PC version on -}
  787.  
  788. instance Text Char where
  789.     showsPrec p c = showString [q, c, q] where q = '\''
  790.     showList cs   = showChar '"' . showl cs
  791.                     where showl ""       = showChar '"'
  792.                           showl ('"':cs) = showString "\\\"" . showl cs
  793.                           showl (c:cs)   = showChar c . showl cs
  794.                           -- Haskell has   showLitChar c . showl cs
  795.  
  796. instance Text a => Text [a]  where
  797.     showsPrec p = showList
  798.  
  799. instance (Text a, Text b) => Text (a,b) where
  800.     showsPrec p (x,y) = showChar '(' . shows x . showChar ',' .
  801.                                        shows y . showChar ')'
  802.  
  803. -- I/O functions and definitions: -----------------------------------------
  804.  
  805. stdin         =  "stdin"
  806. stdout        =  "stdout"
  807. stderr        =  "stderr"
  808. stdecho       =  "stdecho"
  809.  
  810. {- The Dialogue, Request, Response and IOError datatypes are now builtin:
  811. data Request  =  -- file system requests:
  812.                 ReadFile      String         
  813.               | WriteFile     String String
  814.               | AppendFile    String String
  815.                  -- channel system requests:
  816.               | ReadChan      String 
  817.               | AppendChan    String String
  818.                  -- environment requests:
  819.               | Echo          Bool
  820.               | GetArgs
  821.               | GetProgName
  822.               | GetEnv        String
  823.  
  824. data Response = Success
  825.               | Str     String 
  826.               | Failure IOError
  827.               | StrList [String]
  828.  
  829. data IOError  = WriteError   String
  830.               | ReadError    String
  831.               | SearchError  String
  832.               | FormatError  String
  833.               | OtherError   String
  834.  
  835. type Dialogue    =  [Response] -> [Request]
  836. -}
  837.  
  838. type SuccCont    =                Dialogue
  839. type StrCont     =  String     -> Dialogue
  840. type StrListCont =  [String]   -> Dialogue
  841. type FailCont    =  IOError    -> Dialogue
  842.  
  843. done            ::                                                Dialogue
  844. readFile        :: String ->           FailCont -> StrCont     -> Dialogue
  845. writeFile       :: String -> String -> FailCont -> SuccCont    -> Dialogue
  846. appendFile      :: String -> String -> FailCont -> SuccCont    -> Dialogue
  847. readChan        :: String ->           FailCont -> StrCont     -> Dialogue
  848. appendChan      :: String -> String -> FailCont -> SuccCont    -> Dialogue
  849. echo            :: Bool ->             FailCont -> SuccCont    -> Dialogue
  850. getArgs         ::                     FailCont -> StrListCont -> Dialogue
  851. getProgName     ::                     FailCont -> StrCont     -> Dialogue
  852. getEnv          :: String ->           FailCont -> StrCont     -> Dialogue
  853.  
  854. done resps    =  []
  855. readFile name fail succ resps =
  856.      (ReadFile name) : strDispatch fail succ resps
  857. writeFile name contents fail succ resps =
  858.     (WriteFile name contents) : succDispatch fail succ resps
  859. appendFile name contents fail succ resps =
  860.     (AppendFile name contents) : succDispatch fail succ resps
  861. readChan name fail succ resps =
  862.     (ReadChan name) : strDispatch fail succ resps
  863. appendChan name contents fail succ resps =
  864.     (AppendChan name contents) : succDispatch fail succ resps
  865. echo bool fail succ resps =
  866.     (Echo bool) : succDispatch fail succ resps
  867. getArgs fail succ resps =
  868.     GetArgs : strListDispatch fail succ resps
  869. getProgName fail succ resps =
  870.     GetProgName : strDispatch fail succ resps
  871. getEnv name fail succ resps =
  872.     (GetEnv name) : strDispatch fail succ resps
  873.  
  874. strDispatch fail succ (resp:resps) = 
  875.             case resp of Str val     -> succ val resps
  876.                          Failure msg -> fail msg resps
  877.  
  878. succDispatch fail succ (resp:resps) = 
  879.             case resp of Success     -> succ resps
  880.                          Failure msg -> fail msg resps
  881.  
  882. strListDispatch fail succ (resp:resps) =
  883.             case resp of StrList val -> succ val resps
  884.                          Failure msg -> fail msg resps
  885.  
  886. abort           :: FailCont
  887. abort err        = done
  888.  
  889. exit            :: FailCont
  890. exit err         = appendChan stderr msg abort done
  891.                    where msg = case err of ReadError s   -> s
  892.                                            WriteError s  -> s
  893.                                            SearchError s -> s
  894.                                            FormatError s -> s
  895.                                            OtherError s  -> s
  896.  
  897. print           :: Text a => a -> Dialogue
  898. print x          = appendChan stdout (show x) exit done
  899.  
  900. prints          :: Text a => a -> String -> Dialogue
  901. prints x s       = appendChan stdout (shows x s) exit done
  902.  
  903. interact        :: (String -> String) -> Dialogue
  904. interact f       = readChan stdin exit
  905.                             (\x -> appendChan stdout (f x) exit done)
  906.  
  907. run             :: (String -> String) -> Dialogue
  908. run f            = echo False exit (interact f)
  909.  
  910. primitive primFopen "primFopen" :: String -> a -> (String -> a) -> a
  911.  
  912. openfile        :: String -> String
  913. openfile f       = primFopen f (error ("can't open file "++f)) id
  914.  
  915. -- End of Gofer standard prelude: -----------------------------------------
  916.