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