home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / gofer230.zip / Progs / Gofer / Lib / standard.prelude < prev   
Text File  |  1994-06-23  |  28KB  |  864 lines

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