Prelude.curry 53 KB
Newer Older
Björn Peemöller 's avatar
Björn Peemöller committed
1
----------------------------------------------------------------------------
2 3 4
--- The standard prelude of Curry (with type classes).
--- All top-level functions, data types, classes and methods defined
--- in this module are always available in any Curry program.
5 6
---
--- @category general
Björn Peemöller 's avatar
Björn Peemöller committed
7
----------------------------------------------------------------------------
8
{-# LANGUAGE CPP #-}
Björn Peemöller 's avatar
Björn Peemöller committed
9 10
{-# OPTIONS_CYMAKE -Wno-incomplete-patterns -Wno-overlapping #-}

11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
module Prelude
  (
    -- classes and overloaded functions
    Eq(..)
  , elem, notElem, lookup
  , Ord(..)
  , Show(..), ShowS, print, shows, showChar, showString, showParen
  , Read (..), ReadS, lex, read, reads, readParen
  , Bounded (..), Enum (..), boundedEnumFrom, boundedEnumFromThen
  , asTypeOf
  , Num(..), Fractional(..), Real(..), Integral(..)
  -- data types
  , Bool (..) , Char (..) , Int (..) , Float (..), String , Ordering (..)
  , Success, Maybe (..), Either (..), IO (..), IOError (..)
  , DET
  -- functions
  , (.), id, const, curry, uncurry, flip, until, seq, ensureNotFree
  , ensureSpine, ($), ($!), ($!!), ($#), ($##), error
  , failed, (&&), (||), not, otherwise, if_then_else, solve
  , fst, snd, head, tail, null, (++), length, (!!), map, foldl, foldl1
  , foldr, foldr1, filter, zip, zip3, zipWith, zipWith3, unzip, unzip3
  , concat, concatMap, iterate, repeat, replicate, take, drop, splitAt
  , takeWhile, dropWhile, span, break, lines, unlines, words, unwords
  , reverse, and, or, any, all
  , ord, chr, (=:=), success, (&), (&>), maybe
  , either, (>>=), return, (>>), done, putChar, getChar, readFile
  , writeFile, appendFile
  , putStr, putStrLn, getLine, userError, ioError, showError
  , catch, doSolve, sequenceIO, sequenceIO_, mapIO
  , mapIO_, (?), anyOf, unknown
  , when, unless, forIO, forIO_, liftIO, foldIO
  , normalForm, groundNormalForm, apply, cond, (=:<=)
  , enumFrom_, enumFromTo_, enumFromThen_, enumFromThenTo_, negate_, negateFloat
  , PEVAL
  , Monad(..)
  , Functor(..)
#ifdef __PAKCS__
  , (=:<<=), letrec
#endif
  ) where

Björn Peemöller 's avatar
Björn Peemöller committed
52

Björn Peemöller 's avatar
Björn Peemöller committed
53 54 55 56 57 58 59
-- Lines beginning with "--++" are part of the prelude
-- but cannot parsed by the compiler

-- Infix operator declarations:

infixl 9 !!
infixr 9 .
60
infixl 7 *, `div`, `mod`, `quot`, `rem`, /
Björn Peemöller 's avatar
Björn Peemöller committed
61 62 63
infixl 6 +, -
-- infixr 5 :                          -- declared together with list
infixr 5 ++
Björn Peemöller 's avatar
Björn Peemöller committed
64
infix  4 =:=, ==, /=, <, >, <=, >=, =:<=
65 66 67 68
#ifdef __PAKCS__
infix  4 =:<<=
#endif
infix  4 `elem`, `notElem`
Björn Peemöller 's avatar
Björn Peemöller committed
69 70 71
infixr 3 &&
infixr 2 ||
infixl 1 >>, >>=
72
infixr 0 $, $!, $!!, $#, $##, `seq`, &, &>, ?
Björn Peemöller 's avatar
Björn Peemöller committed
73

Björn Peemöller 's avatar
Björn Peemöller committed
74 75

-- externally defined types for numbers and characters
76 77 78
external data Int
external data Float
external data Char
Björn Peemöller 's avatar
Björn Peemöller committed
79

Björn Peemöller 's avatar
Björn Peemöller committed
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
type String = [Char]

-- Some standard combinators:

--- Function composition.
(.)   :: (b -> c) -> (a -> b) -> (a -> c)
f . g = \x -> f (g x)

--- Identity function.
id              :: a -> a
id x            = x

--- Constant function.
const           :: a -> _ -> a
const x _       = x

--- Converts an uncurried function to a curried function.
curry           :: ((a,b) -> c) -> a -> b -> c
curry f a b     =  f (a,b)

--- Converts an curried function to a function on pairs.
uncurry         :: (a -> b -> c) -> (a,b) -> c
uncurry f (a,b) = f a b

--- (flip f) is identical to f but with the order of arguments reversed.
flip            :: (a -> b -> c) -> b -> a -> c
flip  f x y     = f y x

--- Repeats application of a function until a predicate holds.
until          :: (a -> Bool) -> (a -> a) -> a -> a
until p f x     = if p x then x else until p f (f x)

--- Evaluates the first argument to head normal form (which could also
--- be a free variable) and returns the second argument.
seq     :: _ -> a -> a
Björn Peemöller 's avatar
Björn Peemöller committed
115
x `seq` y = const y $! x
Björn Peemöller 's avatar
Björn Peemöller committed
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132

--- Evaluates the argument to head normal form and returns it.
--- Suspends until the result is bound to a non-variable term.
ensureNotFree :: a -> a
ensureNotFree external

--- Evaluates the argument to spine form and returns it.
--- Suspends until the result is bound to a non-variable spine.
ensureSpine :: [a] -> [a]
ensureSpine l = ensureList (ensureNotFree l)
 where ensureList []     = []
       ensureList (x:xs) = x : ensureSpine xs

--- Right-associative application.
($)     :: (a -> b) -> a -> b
f $ x   = f x

Björn Peemöller 's avatar
Björn Peemöller committed
133 134
--- Right-associative application with strict evaluation of its argument
--- to head normal form.
Björn Peemöller 's avatar
Björn Peemöller committed
135
($!)    :: (a -> b) -> a -> b
Björn Peemöller 's avatar
Björn Peemöller committed
136
($!) external
Björn Peemöller 's avatar
Björn Peemöller committed
137 138 139 140

--- Right-associative application with strict evaluation of its argument
--- to normal form.
($!!)   :: (a -> b) -> a -> b
Björn Peemöller 's avatar
Björn Peemöller committed
141
($!!) external
Björn Peemöller 's avatar
Björn Peemöller committed
142 143 144 145 146 147 148 149 150

--- Right-associative application with strict evaluation of its argument
--- to a non-variable term.
($#)    :: (a -> b) -> a -> b
f $# x  = f $! (ensureNotFree x)

--- Right-associative application with strict evaluation of its argument
--- to ground normal form.
($##)   :: (a -> b) -> a -> b
Björn Peemöller 's avatar
Björn Peemöller committed
151
($##) external
Björn Peemöller 's avatar
Björn Peemöller committed
152 153 154 155 156 157 158 159 160 161

--- Aborts the execution with an error message.
error :: String -> _
error x = prim_error $## x

prim_error    :: String -> _
prim_error external

--- A non-reducible polymorphic function.
--- It is useful to express a failure in a search branch of the execution.
Björn Peemöller 's avatar
Björn Peemöller committed
162 163
--- It could be defined by: `failed = head []`
failed :: _
Björn Peemöller 's avatar
Björn Peemöller committed
164 165 166 167 168 169
failed external


-- Boolean values
-- already defined as builtin, since it is required for if-then-else
data Bool = False | True
170
 deriving (Eq, Ord, Show, Read)
Björn Peemöller 's avatar
Björn Peemöller committed
171 172 173 174 175

--- Sequential conjunction on Booleans.
(&&)            :: Bool -> Bool -> Bool
True  && x      = x
False && _      = False
Björn Peemöller 's avatar
Björn Peemöller committed
176

Björn Peemöller 's avatar
Björn Peemöller committed
177 178 179 180 181

--- Sequential disjunction on Booleans.
(||)            :: Bool -> Bool -> Bool
True  || _      = True
False || x      = x
Björn Peemöller 's avatar
Björn Peemöller committed
182

Björn Peemöller 's avatar
Björn Peemöller committed
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198

--- Negation on Booleans.
not             :: Bool -> Bool
not True        = False
not False       = True

--- Useful name for the last condition in a sequence of conditional equations.
otherwise       :: Bool
otherwise       = True


--- The standard conditional. It suspends if the condition is a free variable.
if_then_else           :: Bool -> a -> a -> a
if_then_else b t f = case b of True  -> t
                               False -> f

Björn Peemöller 's avatar
Björn Peemöller committed
199 200 201 202 203 204
--- Enforce a Boolean condition to be true.
--- The computation fails if the argument evaluates to `False`.
solve :: Bool -> Bool
solve True = True

--- Conditional expression.
205
--- An expression like `(c &> e)` is evaluated by evaluating the first
Björn Peemöller 's avatar
Björn Peemöller committed
206 207
--- argument to `True` and then evaluating `e`.
--- The expression has no value if the condition does not evaluate to `True`.
208 209
(&>) :: Bool -> a -> a
True &> x = x
Björn Peemöller 's avatar
Björn Peemöller committed
210

211 212 213 214 215 216 217 218 219 220 221 222 223
--- The equational constraint.
--- `(e1 =:= e2)` is satisfiable if both sides `e1` and `e2` can be
--- reduced to a unifiable data term (i.e., a term without defined
--- function symbols).
(=:=)   :: a -> a -> Bool
(=:=) external

--- Concurrent conjunction.
--- An expression like `(c1 & c2)` is evaluated by evaluating
--- the `c1` and `c2` in a concurrent manner.
(&)     :: Bool -> Bool -> Bool
(&) external

224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253
-- used for comparison of standard types like Int, Float and Char
eqChar :: Char -> Char -> Bool
#ifdef __PAKCS__
eqChar x y = (prim_eqChar $# y) $# x

prim_eqChar :: Char -> Char -> Bool
prim_eqChar external
#else
eqChar external
#endif

eqInt :: Int -> Int -> Bool
#ifdef __PAKCS__
eqInt x y = (prim_eqInt $# y) $# x

prim_eqInt :: Int -> Int -> Bool
prim_eqInt external
#else
eqInt external
#endif

eqFloat :: Float -> Float -> Bool
#ifdef __PAKCS__
eqFloat x y = (prim_eqFloat $# y) $# x

prim_eqFloat :: Float -> Float -> Bool
prim_eqFloat external
#else
eqFloat external
#endif
254

Björn Peemöller 's avatar
Björn Peemöller committed
255 256
--- Ordering type. Useful as a result of comparison functions.
data Ordering = LT | EQ | GT
257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
 deriving (Eq, Ord, Show, Read)

-- used for comparison of standard types like Int, Float and Char
ltEqChar :: Char -> Char -> Bool
#ifdef __PAKCS__
ltEqChar x y = (prim_ltEqChar $# y) $# x

prim_ltEqChar :: Char -> Char -> Bool
prim_ltEqChar external
#else
ltEqChar external
#endif

ltEqInt :: Int -> Int -> Bool
#ifdef __PAKCS__
ltEqInt x y = (prim_ltEqInt $# y) $# x

prim_ltEqInt :: Int -> Int -> Bool
prim_ltEqInt external
#else
ltEqInt external
#endif

ltEqFloat :: Float -> Float -> Bool
#ifdef __PAKCS__
ltEqFloat x y = (prim_ltEqFloat $# y) $# x

prim_ltEqFloat :: Float -> Float -> Bool
prim_ltEqFloat external
#else
ltEqFloat external
#endif
Björn Peemöller 's avatar
Björn Peemöller committed
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331

-- Pairs

--++ data (a,b) = (a,b)

--- Selects the first component of a pair.
fst             :: (a,_) -> a
fst (x,_)       = x

--- Selects the second component of a pair.
snd             :: (_,b) -> b
snd (_,y)       = y


-- Unit type
--++ data () = ()


-- Lists

--++ data [a] = [] | a : [a]

--- Computes the first element of a list.
head            :: [a] -> a
head (x:_)      = x

--- Computes the remaining elements of a list.
tail            :: [a] -> [a]
tail (_:xs)     = xs

--- Is a list empty?
null            :: [_] -> Bool
null []         = True
null (_:_)      = False

--- Concatenates two lists.
--- Since it is flexible, it could be also used to split a list
--- into two sublists etc.
(++)            :: [a] -> [a] -> [a]
[]     ++ ys    = ys
(x:xs) ++ ys    = x : xs++ys

--- Computes the length of a list.
332 333 334 335 336
--length          :: [_] -> Int
--length []       = 0
--length (_:xs)   = 1 + length xs

length :: [_] -> Int
Björn Peemöller 's avatar
Björn Peemöller committed
337 338 339 340
length xs = len xs 0
  where
    len []     n = n
    len (_:ys) n = let np1 = n + 1 in len ys $!! np1
Björn Peemöller 's avatar
Björn Peemöller committed
341 342 343 344 345 346 347 348 349 350 351 352 353

--- List index (subscript) operator, head has index 0.
(!!)            :: [a] -> Int -> a
(x:xs) !! n | n==0      = x
            | n>0       = xs !! (n-1)

--- Map a function on all elements of a list.
map             :: (a->b) -> [a] -> [b]
map _ []        = []
map f (x:xs)    = f x : map f xs

--- Accumulates all list elements by applying a binary operator from
--- left to right. Thus,
Björn Peemöller 's avatar
Björn Peemöller committed
354 355
---
---     foldl f z [x1,x2,...,xn] = (...((z `f` x1) `f` x2) ...) `f` xn
Björn Peemöller 's avatar
Björn Peemöller committed
356 357 358 359 360 361 362 363 364 365
foldl            :: (a -> b -> a) -> a -> [b] -> a
foldl _ z []     = z
foldl f z (x:xs) = foldl f (f z x) xs

--- Accumulates a non-empty list from left to right.
foldl1           :: (a -> a -> a) -> [a] -> a
foldl1 f (x:xs)  = foldl f x xs

--- Accumulates all list elements by applying a binary operator from
--- right to left. Thus,
Björn Peemöller 's avatar
Björn Peemöller committed
366 367
---
---     foldr f z [x1,x2,...,xn] = (x1 `f` (x2 `f` ... (xn `f` z)...))
Björn Peemöller 's avatar
Björn Peemöller committed
368 369 370 371 372
foldr            :: (a->b->b) -> b -> [a] -> b
foldr _ z []     = z
foldr f z (x:xs) = f x (foldr f z xs)

--- Accumulates a non-empty list from right to left:
373 374 375
foldr1                :: (a -> a -> a) -> [a] -> a
foldr1 _ [x]          = x
foldr1 f (x:xs@(_:_)) = f x (foldr1 f xs)
Björn Peemöller 's avatar
Björn Peemöller committed
376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398

--- Filters all elements satisfying a given predicate in a list.
filter            :: (a -> Bool) -> [a] -> [a]
filter _ []       = []
filter p (x:xs)   = if p x then x : filter p xs
                           else filter p xs

--- Joins two lists into one list of pairs. If one input list is shorter than
--- the other, the additional elements of the longer list are discarded.
zip               :: [a] -> [b] -> [(a,b)]
zip []     _      = []
zip (_:_)  []     = []
zip (x:xs) (y:ys) = (x,y) : zip xs ys

--- Joins three lists into one list of triples. If one input list is shorter
--- than the other, the additional elements of the longer lists are discarded.
zip3                      :: [a] -> [b] -> [c] -> [(a,b,c)]
zip3 []     _      _      = []
zip3 (_:_)  []     _      = []
zip3 (_:_)  (_:_)  []     = []
zip3 (x:xs) (y:ys) (z:zs) = (x,y,z) : zip3 xs ys zs

--- Joins two lists into one list by applying a combination function to
Björn Peemöller 's avatar
Björn Peemöller committed
399
--- corresponding pairs of elements. Thus `zip = zipWith (,)`
Björn Peemöller 's avatar
Björn Peemöller committed
400 401 402 403 404 405
zipWith                 :: (a->b->c) -> [a] -> [b] -> [c]
zipWith _ []     _      = []
zipWith _ (_:_)  []     = []
zipWith f (x:xs) (y:ys) = f x y : zipWith f xs ys

--- Joins three lists into one list by applying a combination function to
Björn Peemöller 's avatar
Björn Peemöller committed
406
--- corresponding triples of elements. Thus `zip3 = zipWith3 (,,)`
Björn Peemöller 's avatar
Björn Peemöller committed
407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431
zipWith3                        :: (a->b->c->d) -> [a] -> [b] -> [c] -> [d]
zipWith3 _ []     _      _      = []
zipWith3 _ (_:_)  []     _      = []
zipWith3 _ (_:_)  (_:_)  []     = []
zipWith3 f (x:xs) (y:ys) (z:zs) = f x y z : zipWith3 f xs ys zs

--- Transforms a list of pairs into a pair of lists.
unzip               :: [(a,b)] -> ([a],[b])
unzip []            = ([],[])
unzip ((x,y):ps)    = (x:xs,y:ys) where (xs,ys) = unzip ps

--- Transforms a list of triples into a triple of lists.
unzip3              :: [(a,b,c)] -> ([a],[b],[c])
unzip3 []           = ([],[],[])
unzip3 ((x,y,z):ts) = (x:xs,y:ys,z:zs) where (xs,ys,zs) = unzip3 ts

--- Concatenates a list of lists into one list.
concat            :: [[a]] -> [a]
concat l          = foldr (++) [] l

--- Maps a function from elements to lists and merges the result into one list.
concatMap         :: (a -> [b]) -> [a] -> [b]
concatMap f       = concat . map f

--- Infinite list of repeated applications of a function f to an element x.
Björn Peemöller 's avatar
Björn Peemöller committed
432
--- Thus, `iterate f x = [x, f x, f (f x),...]`
Björn Peemöller 's avatar
Björn Peemöller committed
433 434 435 436
iterate           :: (a -> a) -> a -> [a]
iterate f x       = x : iterate f (f x)

--- Infinite list where all elements have the same value.
Björn Peemöller 's avatar
Björn Peemöller committed
437
--- Thus, `repeat x = [x, x, x,...]`
Björn Peemöller 's avatar
Björn Peemöller committed
438 439 440 441 442 443 444 445 446 447 448 449 450 451
repeat            :: a -> [a]
repeat x          = x : repeat x

--- List of length n where all elements have the same value.
replicate         :: Int -> a -> [a]
replicate n x     = take n (repeat x)

--- Returns prefix of length n.
take              :: Int -> [a] -> [a]
take n l          = if n<=0 then [] else takep n l
   where takep _ []     = []
         takep m (x:xs) = x : take (m-1) xs

--- Returns suffix without first n elements.
452 453 454 455
drop :: Int -> [a] -> [a]
drop n xs = if n<=0 then xs
                    else case xs of []     -> []
                                    (_:ys) -> drop (n-1) ys
Björn Peemöller 's avatar
Björn Peemöller committed
456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532

--- (splitAt n xs) is equivalent to (take n xs, drop n xs)
splitAt           :: Int -> [a] -> ([a],[a])
splitAt n l       = if n<=0 then ([],l) else splitAtp n l
   where splitAtp _ []     = ([],[])
         splitAtp m (x:xs) = let (ys,zs) = splitAt (m-1) xs in (x:ys,zs)

--- Returns longest prefix with elements satisfying a predicate.
takeWhile          :: (a -> Bool) -> [a] -> [a]
takeWhile _ []     = []
takeWhile p (x:xs) = if p x then x : takeWhile p xs else []

--- Returns suffix without takeWhile prefix.
dropWhile          :: (a -> Bool) -> [a] -> [a]
dropWhile _ []     = []
dropWhile p (x:xs) = if p x then dropWhile p xs else x:xs

--- (span p xs) is equivalent to (takeWhile p xs, dropWhile p xs)
span               :: (a -> Bool) -> [a] -> ([a],[a])
span _ []          = ([],[])
span p (x:xs)
       | p x       = let (ys,zs) = span p xs in (x:ys, zs)
       | otherwise = ([],x:xs)

--- (break p xs) is equivalent to (takeWhile (not.p) xs, dropWhile (not.p) xs).
--- Thus, it breaks a list at the first occurrence of an element satisfying p.
break              :: (a -> Bool) -> [a] -> ([a],[a])
break p            = span (not . p)

--- Breaks a string into a list of lines where a line is terminated at a
--- newline character. The resulting lines do not contain newline characters.
lines        :: String -> [String]
lines []     = []
lines (x:xs) = let (l,xs_l) = splitline (x:xs) in l : lines xs_l
 where splitline []     = ([],[])
       splitline (c:cs) = if c=='\n'
                          then ([],cs)
                          else let (ds,es) = splitline cs in (c:ds,es)

--- Concatenates a list of strings with terminating newlines.
unlines    :: [String] -> String
unlines ls = concatMap (++"\n") ls

--- Breaks a string into a list of words where the words are delimited by
--- white spaces.
words      :: String -> [String]
words s    = let s1 = dropWhile isSpace s
              in if s1=="" then []
                           else let (w,s2) = break isSpace s1
                                 in w : words s2

--- Concatenates a list of strings with a blank between two strings.
unwords    :: [String] -> String
unwords ws = if ws==[] then []
                       else foldr1 (\w s -> w ++ ' ':s) ws

--- Reverses the order of all elements in a list.
reverse    :: [a] -> [a]
reverse    = foldl (flip (:)) []

--- Computes the conjunction of a Boolean list.
and        :: [Bool] -> Bool
and        = foldr (&&) True

--- Computes the disjunction of a Boolean list.
or         :: [Bool] -> Bool
or         = foldr (||) False

--- Is there an element in a list satisfying a given predicate?
any        :: (a -> Bool) -> [a] -> Bool
any p      = or . map p

--- Is a given predicate satisfied by all elements in a list?
all        :: (a -> Bool) -> [a] -> Bool
all p      = and . map p

--- Element of a list?
533 534
elem :: Eq a => a -> [a] -> Bool
elem x = any (x ==)
Björn Peemöller 's avatar
Björn Peemöller committed
535 536

--- Not element of a list?
537 538
notElem :: Eq a => a -> [a] -> Bool
notElem x = all (x /=)
Björn Peemöller 's avatar
Björn Peemöller committed
539 540

--- Looks up a key in an association list.
541
lookup :: Eq a => a -> [(a, b)] -> Maybe b
Björn Peemöller 's avatar
Björn Peemöller committed
542 543 544 545 546 547
lookup _ []       = Nothing
lookup k ((x,y):xys)
      | k==x      = Just y
      | otherwise = lookup k xys

--- Generates an infinite sequence of ascending integers.
548 549
enumFrom_ :: Int -> [Int]                   -- [n..]
enumFrom_ n = n : enumFrom_ (n+1)
Björn Peemöller 's avatar
Björn Peemöller committed
550 551

--- Generates an infinite sequence of integers with a particular in/decrement.
552 553
enumFromThen_ :: Int -> Int -> [Int]            -- [n1,n2..]
enumFromThen_ n1 n2 = iterate ((n2-n1)+) n1
Björn Peemöller 's avatar
Björn Peemöller committed
554 555

--- Generates a sequence of ascending integers.
556 557
enumFromTo_ :: Int -> Int -> [Int]            -- [n..m]
enumFromTo_ n m = if n>m then [] else n : enumFromTo_ (n+1) m
Björn Peemöller 's avatar
Björn Peemöller committed
558 559

--- Generates a sequence of integers with a particular in/decrement.
560 561 562 563 564
enumFromThenTo_ :: Int -> Int -> Int -> [Int]     -- [n1,n2..m]
enumFromThenTo_ n1 n2 m = takeWhile p (enumFromThen_ n1 n2)
 where
  p x | n2 >= n1  = (x <= m)
      | otherwise = (x >= m)
Björn Peemöller 's avatar
Björn Peemöller committed
565 566 567 568 569 570 571 572 573


--- Converts a character into its ASCII value.
ord :: Char -> Int
ord c = prim_ord $# c

prim_ord :: Char -> Int
prim_ord external

Björn Peemöller 's avatar
Björn Peemöller committed
574
--- Converts a Unicode value into a character, fails iff the value is out of bounds
Björn Peemöller 's avatar
Björn Peemöller committed
575
chr :: Int -> Char
Björn Peemöller 's avatar
Björn Peemöller committed
576 577 578
chr n | n >= 0 = prim_chr $# n
-- chr n | n < 0 || n > 1114111 = failed
--       | otherwise = prim_chr $# n
Björn Peemöller 's avatar
Björn Peemöller committed
579 580 581 582 583 584 585 586

prim_chr :: Int -> Char
prim_chr external


-- Types of primitive arithmetic functions and predicates

--- Adds two integers.
587 588 589 590 591 592 593 594 595
(+$)   :: Int -> Int -> Int
#ifdef __PAKCS__
x +$ y = (prim_Int_plus $# y) $# x

prim_Int_plus :: Int -> Int -> Int
prim_Int_plus external
#else
(+$) external
#endif
Björn Peemöller 's avatar
Björn Peemöller committed
596 597

--- Subtracts two integers.
598 599 600 601 602 603 604 605 606
(-$)   :: Int -> Int -> Int
#ifdef __PAKCS__
x -$ y = (prim_Int_minus $# y) $# x

prim_Int_minus :: Int -> Int -> Int
prim_Int_minus external
#else
(-$) external
#endif
Björn Peemöller 's avatar
Björn Peemöller committed
607 608

--- Multiplies two integers.
609 610 611 612 613 614 615 616 617
(*$)   :: Int -> Int -> Int
#ifdef __PAKCS__
x *$ y = (prim_Int_times $# y) $# x

prim_Int_times :: Int -> Int -> Int
prim_Int_times external
#else
(*$) external
#endif
Björn Peemöller 's avatar
Björn Peemöller committed
618 619

--- Integer division. The value is the integer quotient of its arguments
Björn Peemöller 's avatar
Björn Peemöller committed
620
--- and always truncated towards negative infinity.
Björn Peemöller 's avatar
Björn Peemöller committed
621
--- Thus, the value of <code>13 `div` 5</code> is <code>2</code>,
622 623 624 625 626 627 628 629 630 631
--- and the value of <code>-15 `div` 4</code> is <code>-3</code>.
div_   :: Int -> Int -> Int
#ifdef __PAKCS__
x `div_` y = (prim_Int_div $# y) $# x

prim_Int_div :: Int -> Int -> Int
prim_Int_div external
#else
div_ external
#endif
Björn Peemöller 's avatar
Björn Peemöller committed
632 633 634 635 636

--- Integer remainder. The value is the remainder of the integer division and
--- it obeys the rule <code>x `mod` y = x - y * (x `div` y)</code>.
--- Thus, the value of <code>13 `mod` 5</code> is <code>3</code>,
--- and the value of <code>-15 `mod` 4</code> is <code>-3</code>.
637 638 639 640 641 642 643 644 645
mod_   :: Int -> Int -> Int
#ifdef __PAKCS__
x `mod_` y = (prim_Int_mod $# y) $# x

prim_Int_mod :: Int -> Int -> Int
prim_Int_mod external
#else
mod_ external
#endif
Björn Peemöller 's avatar
Björn Peemöller committed
646 647 648 649

--- Returns an integer (quotient,remainder) pair.
--- The value is the integer quotient of its arguments
--- and always truncated towards negative infinity.
650 651 652 653 654 655
divMod_ :: Int -> Int -> (Int, Int)
#ifdef __PAKCS__
divMod_ x y = (x `div` y, x `mod` y)
#else
divMod_ external
#endif
Björn Peemöller 's avatar
Björn Peemöller committed
656

Björn Peemöller 's avatar
Björn Peemöller committed
657 658 659 660
--- Integer division. The value is the integer quotient of its arguments
--- and always truncated towards zero.
--- Thus, the value of <code>13 `quot` 5</code> is <code>2</code>,
--- and the value of <code>-15 `quot` 4</code> is <code>-3</code>.
661 662 663 664 665 666 667 668 669
quot_ :: Int -> Int -> Int
#ifdef __PAKCS__
x `quot_` y = (prim_Int_quot $# y) $# x

prim_Int_quot :: Int -> Int -> Int
prim_Int_quot external
#else
quot_ external
#endif
Björn Peemöller 's avatar
Björn Peemöller committed
670 671 672 673 674

--- Integer remainder. The value is the remainder of the integer division and
--- it obeys the rule <code>x `rem` y = x - y * (x `quot` y)</code>.
--- Thus, the value of <code>13 `rem` 5</code> is <code>3</code>,
--- and the value of <code>-15 `rem` 4</code> is <code>-3</code>.
675 676 677 678 679 680 681 682 683
rem_ :: Int -> Int -> Int
#ifdef __PAKCS__
x `rem_` y = (prim_Int_rem $# y) $# x

prim_Int_rem :: Int -> Int -> Int
prim_Int_rem external
#else
rem_ external
#endif
Björn Peemöller 's avatar
Björn Peemöller committed
684 685 686 687

--- Returns an integer (quotient,remainder) pair.
--- The value is the integer quotient of its arguments
--- and always truncated towards zero.
688 689 690 691 692 693
quotRem_ :: Int -> Int -> (Int, Int)
#ifdef __PAKCS__
quotRem_ x y = (x `quot` y, x `rem` y)
#else
quotRem_ external
#endif
Björn Peemöller 's avatar
Björn Peemöller committed
694 695

--- Unary minus. Usually written as "- e".
696 697
negate_ :: Int -> Int
negate_ x = 0 - x
Björn Peemöller 's avatar
Björn Peemöller committed
698 699 700

--- Unary minus on Floats. Usually written as "-e".
negateFloat :: Float -> Float
701 702
#ifdef __PAKCS__
negateFloat x = prim_negateFloat $# x
Björn Peemöller 's avatar
Björn Peemöller committed
703

704 705 706 707 708
prim_negateFloat :: Float -> Float
prim_negateFloat external
#else
negateFloat external
#endif
Björn Peemöller 's avatar
Björn Peemöller committed
709

710
-- Constraints (included for backward compatibility)
711
type Success = Bool
Björn Peemöller 's avatar
Björn Peemöller committed
712 713 714

--- The always satisfiable constraint.
success :: Success
715
success = True
Björn Peemöller 's avatar
Björn Peemöller committed
716 717 718 719

-- Maybe type

data Maybe a = Nothing | Just a
720
 deriving (Eq, Ord, Show, Read)
Björn Peemöller 's avatar
Björn Peemöller committed
721 722 723 724 725 726 727 728 729

maybe              :: b -> (a -> b) -> Maybe a -> b
maybe n _ Nothing  = n
maybe _ f (Just x) = f x


-- Either type

data Either a b = Left a | Right b
730
 deriving (Eq, Ord, Show, Read)
Björn Peemöller 's avatar
Björn Peemöller committed
731 732 733 734 735 736 737 738

either               :: (a -> c) -> (b -> c) -> Either a b -> c
either f _ (Left x)  = f x
either _ g (Right x) = g x


-- Monadic IO

739
external data IO _  -- conceptually: World -> (a,World)
Björn Peemöller 's avatar
Björn Peemöller committed
740

741
--- Sequential composition of IO actions.
Björn Peemöller 's avatar
Björn Peemöller committed
742 743 744 745
--- @param a - An action
--- @param fa - A function from a value into an action
--- @return An action that first performs a (yielding result r)
---         and then performs (fa r)
746 747
(>>=$)             :: IO a -> (a -> IO b) -> IO b
(>>=$) external
Björn Peemöller 's avatar
Björn Peemöller committed
748

749 750 751
--- The empty IO action that directly returns its argument.
returnIO            :: a -> IO a
returnIO external
Björn Peemöller 's avatar
Björn Peemöller committed
752

753 754 755 756 757 758
--- Sequential composition of IO actions.
--- @param a1 - An IO action
--- @param a2 - An IO action
--- @return An IO action that first performs a1 and then a2
(>>$) :: IO _ -> IO b -> IO b
a >>$ b = a >>=$ (\_ -> b)
Björn Peemöller 's avatar
Björn Peemöller committed
759

760 761 762
--- The empty IO action that returns nothing.
done :: IO ()
done = return ()
Björn Peemöller 's avatar
Björn Peemöller committed
763 764 765

--- An action that puts its character argument on standard output.
putChar           :: Char -> IO ()
766
putChar c = prim_putChar $# c
Björn Peemöller 's avatar
Björn Peemöller committed
767 768 769 770 771 772 773 774 775 776 777 778 779 780

prim_putChar           :: Char -> IO ()
prim_putChar external

--- An action that reads a character from standard output and returns it.
getChar           :: IO Char
getChar external

--- An action that (lazily) reads a file and returns its contents.
readFile          :: String -> IO String
readFile f = prim_readFile $## f

prim_readFile          :: String -> IO String
prim_readFile external
781 782 783 784 785
#ifdef __PAKCS__
-- for internal implementation of readFile:
prim_readFileContents          :: String -> String
prim_readFileContents external
#endif
Björn Peemöller 's avatar
Björn Peemöller committed
786 787 788 789 790

--- An action that writes a file.
--- @param filename - The name of the file to be written.
--- @param contents - The contents to be written to the file.
writeFile         :: String -> String -> IO ()
791
writeFile f s = (prim_writeFile $## f) s
Björn Peemöller 's avatar
Björn Peemöller committed
792 793 794 795 796 797 798 799 800

prim_writeFile         :: String -> String -> IO ()
prim_writeFile external

--- An action that appends a string to a file.
--- It behaves like writeFile if the file does not exist.
--- @param filename - The name of the file to be written.
--- @param contents - The contents to be appended to the file.
appendFile        :: String -> String -> IO ()
801
appendFile f s = (prim_appendFile $## f) s
Björn Peemöller 's avatar
Björn Peemöller committed
802 803 804 805 806 807 808 809

prim_appendFile         :: String -> String -> IO ()
prim_appendFile external

--- Action to print a string on stdout.
putStr            :: String -> IO ()
putStr []         = done
putStr (c:cs)     = putChar c >> putStr cs
Björn Peemöller 's avatar
Björn Peemöller committed
810

Björn Peemöller 's avatar
Björn Peemöller committed
811 812 813 814 815 816 817 818 819 820 821
--- Action to print a string with a newline on stdout.
putStrLn          :: String -> IO ()
putStrLn cs       = putStr cs >> putChar '\n'

--- Action to read a line from stdin.
getLine           :: IO String
getLine           = do c <- getChar
                       if c=='\n' then return []
                                  else do cs <- getLine
                                          return (c:cs)

Björn Peemöller 's avatar
Björn Peemöller committed
822
----------------------------------------------------------------------------
Björn Peemöller 's avatar
Björn Peemöller committed
823 824 825
-- Error handling in the I/O monad:

--- The (abstract) type of error values.
Björn Peemöller 's avatar
Björn Peemöller committed
826 827 828 829 830 831 832 833 834 835 836 837
--- Currently, it distinguishes between general IO errors,
--- user-generated errors (see 'userError'), failures and non-determinism
--- errors during IO computations. These errors can be caught by 'catch'
--- and shown by 'showError'.
--- Each error contains a string shortly explaining the error.
--- This type might be extended in the future to distinguish
--- further error situations.
data IOError
  = IOError     String -- normal IO error
  | UserError   String -- user-specified error
  | FailError   String -- failing computation
  | NondetError String -- non-deterministic computation
838
 deriving (Eq,Show,Read)
Björn Peemöller 's avatar
Björn Peemöller committed
839 840 841 842

--- A user error value is created by providing a description of the
--- error situation as a string.
userError :: String -> IOError
Björn Peemöller 's avatar
Björn Peemöller committed
843
userError s = UserError s
Björn Peemöller 's avatar
Björn Peemöller committed
844 845 846

--- Raises an I/O exception with a given error value.
ioError :: IOError -> IO _
847 848 849
#ifdef __PAKCS__
ioError err = error (showError err)
#else
Björn Peemöller 's avatar
Björn Peemöller committed
850 851 852 853
ioError err = prim_ioError $## err

prim_ioError :: IOError -> IO _
prim_ioError external
854
#endif
Björn Peemöller 's avatar
Björn Peemöller committed
855 856 857

--- Shows an error values as a string.
showError :: IOError -> String
Björn Peemöller 's avatar
Björn Peemöller committed
858 859 860 861
showError (IOError     s) = "i/o error: "    ++ s
showError (UserError   s) = "user error: "   ++ s
showError (FailError   s) = "fail error: "   ++ s
showError (NondetError s) = "nondet error: " ++ s
Björn Peemöller 's avatar
Björn Peemöller committed
862 863

--- Catches a possible error or failure during the execution of an
Björn Peemöller 's avatar
Björn Peemöller committed
864 865 866
--- I/O action. `(catch act errfun)` executes the I/O action
--- `act`. If an exception or failure occurs
--- during this I/O action, the function `errfun` is applied
Björn Peemöller 's avatar
Björn Peemöller committed
867 868 869 870
--- to the error value.
catch :: IO a -> (IOError -> IO a) -> IO a
catch external

Björn Peemöller 's avatar
Björn Peemöller committed
871
----------------------------------------------------------------------------
Björn Peemöller 's avatar
Björn Peemöller committed
872 873

--- Converts an arbitrary term into an external string representation.
874 875
show_    :: _ -> String
show_ x = prim_show $## x
Björn Peemöller 's avatar
Björn Peemöller committed
876 877 878 879 880

prim_show    :: _ -> String
prim_show external

--- Converts a term into a string and prints it.
881
print :: Show a => a -> IO ()
Björn Peemöller 's avatar
Björn Peemöller committed
882 883 884 885
print t = putStrLn (show t)

--- Solves a constraint as an I/O action.
--- Note: the constraint should be always solvable in a deterministic way
886 887
doSolve :: Bool -> IO ()
doSolve b | b = done
Björn Peemöller 's avatar
Björn Peemöller committed
888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912


-- IO monad auxiliary functions:

--- Executes a sequence of I/O actions and collects all results in a list.
sequenceIO       :: [IO a] -> IO [a]
sequenceIO []     = return []
sequenceIO (c:cs) = do x  <- c
                       xs <- sequenceIO cs
                       return (x:xs)

--- Executes a sequence of I/O actions and ignores the results.
sequenceIO_        :: [IO _] -> IO ()
sequenceIO_         = foldr (>>) done

--- Maps an I/O action function on a list of elements.
--- The results of all I/O actions are collected in a list.
mapIO             :: (a -> IO b) -> [a] -> IO [b]
mapIO f            = sequenceIO . map f

--- Maps an I/O action function on a list of elements.
--- The results of all I/O actions are ignored.
mapIO_            :: (a -> IO _) -> [a] -> IO ()
mapIO_ f           = sequenceIO_ . map f

Björn Peemöller 's avatar
Björn Peemöller committed
913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949
--- Folds a list of elements using an binary I/O action and a value
--- for the empty list.
foldIO :: (a -> b -> IO a) -> a -> [b] -> IO a
foldIO _ a []      =  return a
foldIO f a (x:xs)  =  f a x >>= \fax -> foldIO f fax xs

--- Apply a pure function to the result of an I/O action.
liftIO :: (a -> b) -> IO a -> IO b
liftIO f m = m >>= return . f

--- Like `mapIO`, but with flipped arguments.
---
--- This can be useful if the definition of the function is longer
--- than those of the list, like in
---
--- forIO [1..10] $ \n -> do
---   ...
forIO :: [a] -> (a -> IO b) -> IO [b]
forIO xs f = mapIO f xs

--- Like `mapIO_`, but with flipped arguments.
---
--- This can be useful if the definition of the function is longer
--- than those of the list, like in
---
--- forIO_ [1..10] $ \n -> do
---   ...
forIO_ :: [a] -> (a -> IO b) -> IO ()
forIO_ xs f = mapIO_ f xs

--- Performs an `IO` action unless the condition is met.
unless :: Bool -> IO () -> IO ()
unless p act = if p then done else act

--- Performs an `IO` action when the condition is met.
when :: Bool -> IO () -> IO ()
when p act = if p then act else done
Björn Peemöller 's avatar
Björn Peemöller committed
950 951 952 953

----------------------------------------------------------------
-- Non-determinism and free variables:

Björn Peemöller 's avatar
Björn Peemöller committed
954 955
--- Non-deterministic choice _par excellence_.
--- The value of `x ? y` is either `x` or `y`.
Björn Peemöller 's avatar
Björn Peemöller committed
956 957
--- @param x - The right argument.
--- @param y - The left argument.
Björn Peemöller 's avatar
Björn Peemöller committed
958
--- @return either `x` or `y` non-deterministically.
Björn Peemöller 's avatar
Björn Peemöller committed
959 960 961 962
(?)   :: a -> a -> a
x ? _ = x
_ ? y = y

963 964 965
-- Returns non-deterministically any element of a list.
anyOf :: [a] -> a
anyOf = foldr1 (?)
Björn Peemöller 's avatar
Björn Peemöller committed
966 967 968 969 970 971

--- Evaluates to a fresh free variable.
unknown :: _
unknown = let x free in x

----------------------------------------------------------------
972 973 974
--- Identity type synonym used to mark deterministic operations.
type DET a = a

Björn Peemöller 's avatar
Björn Peemöller committed
975 976 977 978 979 980 981
--- Identity function used by the partial evaluator
--- to mark expressions to be partially evaluated.
PEVAL   :: a -> a
PEVAL x = x

--- Evaluates the argument to normal form and returns it.
normalForm :: a -> a
Björn Peemöller 's avatar
Björn Peemöller committed
982
normalForm x = id $!! x
Björn Peemöller 's avatar
Björn Peemöller committed
983 984 985 986

--- Evaluates the argument to ground normal form and returns it.
--- Suspends as long as the normal form of the argument is not ground.
groundNormalForm :: a -> a
Björn Peemöller 's avatar
Björn Peemöller committed
987
groundNormalForm x = id $## x
Björn Peemöller 's avatar
Björn Peemöller committed
988 989

-- Only for internal use:
Björn Peemöller 's avatar
Björn Peemöller committed
990 991
-- Representation of higher-order applications in FlatCurry.
apply :: (a -> b) -> a -> b
Björn Peemöller 's avatar
Björn Peemöller committed
992 993 994 995
apply external

-- Only for internal use:
-- Representation of conditional rules in FlatCurry.
996
cond :: Bool -> a -> a
Björn Peemöller 's avatar
Björn Peemöller committed
997 998
cond external

999 1000 1001 1002 1003 1004 1005
#ifdef __PAKCS__
-- Only for internal use:
-- letrec ones (1:ones) -> bind ones to (1:ones)
letrec :: a -> a -> Bool
letrec external
#endif

Björn Peemöller 's avatar
Björn Peemöller committed
1006
--- Non-strict equational constraint. Used to implement functional patterns.
1007
(=:<=) :: a -> a -> Bool
Björn Peemöller 's avatar
Björn Peemöller committed
1008 1009
(=:<=) external

1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647
#ifdef __PAKCS__
--- Non-strict equational constraint for linear functional patterns.
--- Thus, it must be ensured that the first argument is always (after evalutation
--- by narrowing) a linear pattern. Experimental.
(=:<<=) :: a -> a -> Bool
(=:<<=) external

--- internal function to implement =:<=
ifVar :: _ -> a -> a -> a
ifVar external

--- internal operation to implement failure reporting
failure :: _ -> _ -> _
failure external
#endif

-- -------------------------------------------------------------------------
-- Eq class and related instances and functions
-- -------------------------------------------------------------------------

class Eq a where
  (==), (/=) :: a -> a -> Bool

  x == y = not (x /= y)
  x /= y = not (x == y)

instance Eq Char where
  c == c' = c `eqChar` c'

instance Eq Int where
  i == i' = i `eqInt` i'

instance Eq Float where
  f == f' = f `eqFloat` f'

instance Eq a => Eq [a] where
  []    == []    = True
  []    == (_:_) = False
  (_:_) == []    = False
  (x:xs) == (y:ys) = x == y && xs == ys

instance Eq () where
  () == () = True

instance (Eq a, Eq b) => Eq (a, b) where
  (a, b) == (a', b') = a == a' && b == b'

instance (Eq a, Eq b, Eq c) => Eq (a, b, c) where
  (a, b, c) == (a', b', c') = a == a' && b == b' && c == c'

instance (Eq a, Eq b, Eq c, Eq d) => Eq (a, b, c, d) where
  (a, b, c, d) == (a', b', c', d') = a == a' && b == b' && c == c' && d == d'

instance (Eq a, Eq b, Eq c, Eq d, Eq e) => Eq (a, b, c, d, e) where
  (a, b, c, d, e) == (a', b', c', d', e') = a == a' && b == b' && c == c' && d == d' && e == e'

instance (Eq a, Eq b, Eq c, Eq d, Eq e, Eq f) => Eq (a, b, c, d, e, f) where
  (a, b, c, d, e, f) == (a', b', c', d', e', f') = a == a' && b == b' && c == c' && d == d' && e == e' && f == f'

instance (Eq a, Eq b, Eq c, Eq d, Eq e, Eq f, Eq g) => Eq (a, b, c, d, e, f, g) where
  (a, b, c, d, e, f, g) == (a', b', c', d', e', f', g') = a == a' && b == b' && c == c' && d == d' && e == e' && f == f' && g == g'

-- -------------------------------------------------------------------------
-- Ord class and related instances and functions
-- -------------------------------------------------------------------------

--- minimal complete definition: compare or <=
class Eq a => Ord a where
  compare :: a -> a -> Ordering
  (<=) :: a -> a -> Bool
  (>=) :: a -> a -> Bool
  (<)  :: a -> a -> Bool
  (>)  :: a -> a -> Bool

  min :: a -> a -> a
  max :: a -> a -> a

  x < y = x <= y && x /= y
  x > y = not (x <= y)
  x >= y = y <= x
  x <= y = compare x y == EQ || compare x y == LT

  compare x y | x == y = EQ
              | x <= y = LT
              | otherwise = GT

  min x y | x <= y    = x
          | otherwise = y

  max x y | x >= y    = x
          | otherwise = y

instance Ord Char where
  c1 <= c2 = c1 `ltEqChar` c2

instance Ord Int where
  i1 <= i2 = i1 `ltEqInt` i2

instance Ord Float where
  f1 <= f2 = f1 `ltEqFloat` f2

instance Ord a => Ord [a] where
  []    <= []    = True
  (_:_) <= []    = False
  []    <= (_:_) = True
  (x:xs) <= (y:ys) | x == y    = xs <= ys
                   | otherwise = x < y

instance Ord () where
  () <= () = True

instance (Ord a, Ord b) => Ord (a, b) where
  (a, b) <= (a', b') = a < a' || (a == a' && b <= b')

instance (Ord a, Ord b, Ord c) => Ord (a, b, c) where
  (a, b, c) <= (a', b', c') = a < a'
     || (a == a' && b < b')
     || (a == a' && b == b' && c <= c')

instance (Ord a, Ord b, Ord c, Ord d) => Ord (a, b, c, d) where
  (a, b, c, d) <= (a', b', c', d') = a < a'
     || (a == a' && b < b')
     || (a == a' && b == b' && c < c')
     || (a == a' && b == b' && c == c' && d <= d')

instance (Ord a, Ord b, Ord c, Ord d, Ord e) => Ord (a, b, c, d, e) where
  (a, b, c, d, e) <= (a', b', c', d', e') = a < a'
     || (a == a' && b < b')
     || (a == a' && b == b' && c < c')
     || (a == a' && b == b' && c == c' && d < d')
     || (a == a' && b == b' && c == c' && d == d' && e <= e')

-- -------------------------------------------------------------------------
-- Show class and related instances and functions
-- -------------------------------------------------------------------------

type ShowS = String -> String

class Show a where
  show :: a -> String

  showsPrec :: Int -> a -> ShowS

  showList :: [a] -> ShowS

  showsPrec _ x s = show x ++ s
  show x = shows x ""
  showList ls s = showList' shows ls s

showList' :: (a -> ShowS) ->  [a] -> ShowS
showList' _     []     s = "[]" ++ s
showList' showx (x:xs) s = '[' : showx x (showl xs)
  where
    showl []     = ']' : s
    showl (y:ys) = ',' : showx y (showl ys)

shows :: Show a => a -> ShowS
shows = showsPrec 0

showChar :: Char -> ShowS
showChar c s = c:s

showString :: String -> ShowS
showString str s = foldr showChar s str

showParen :: Bool -> ShowS -> ShowS
showParen b s = if b then showChar '(' . s . showChar ')' else s

-- -------------------------------------------------------------------------

instance Show () where
  showsPrec _ () = showString "()"

instance (Show a, Show b) => Show (a, b) where
  showsPrec _ (a, b) = showTuple [shows a, shows b]

instance (Show a, Show b, Show c) => Show (a, b, c) where
  showsPrec _ (a, b, c) = showTuple [shows a, shows b, shows c]

instance (Show a, Show b, Show c, Show d) => Show (a, b, c, d) where
  showsPrec _ (a, b, c, d) = showTuple [shows a, shows b, shows c, shows d]

instance (Show a, Show b, Show c, Show d, Show e) => Show (a, b, c, d, e) where
  showsPrec _ (a, b, c, d, e) = showTuple [shows a, shows b, shows c, shows d, shows e]

instance Show a => Show [a] where
  showsPrec _ = showList

instance Show Char where
  -- TODO: own implementation instead of passing to original Prelude functions?
  showsPrec _ c = showString (show_ c)

  showList cs | null cs   = showString "\"\""
              | otherwise = showString (show_ cs)

instance Show Int where
  showsPrec = showSigned (showString . show_)

instance Show Float where
  showsPrec = showSigned (showString . show_)

showSigned :: Real a => (a -> ShowS) -> Int -> a -> ShowS
showSigned showPos p x
  | x < 0     = showParen (p > 6) (showChar '-' . showPos (-x))
  | otherwise = showPos x

showTuple :: [ShowS] -> ShowS
showTuple ss = showChar '('
             . foldr1 (\s r -> s . showChar ',' . r) ss
             . showChar ')'

appPrec :: Int
appPrec = 10

appPrec1 :: Int
appPrec1 = 11

-- -------------------------------------------------------------------------
-- Read class and related instances and functions
-- -------------------------------------------------------------------------

type ReadS a = String -> [(a, String)]


class Read a where
  readsPrec :: Int -> ReadS a

  readList :: ReadS [a]
  readList = readListDefault

readListDefault :: Read a => ReadS [a]
readListDefault = readParen False (\r -> [pr | ("[",s)  <- lex r
                                        , pr       <- readl s])
    where readl s = [([], t) | ("]", t) <- lex s] ++
                      [(x : xs, u) | (x, t) <- reads s, (xs, u) <- readl' t]
          readl' s = [([], t) | ("]", t) <- lex s] ++
                       [(x : xs, v) | (",", t)  <- lex s, (x, u) <- reads t
                                    , (xs,v) <- readl' u]

reads :: Read a => ReadS a
reads = readsPrec 0

readParen :: Bool -> ReadS a -> ReadS a
readParen b g = if b then mandatory else optional
  where optional r = g r ++ mandatory r
        mandatory r =
          [(x, u) | ("(", s) <- lex r, (x, t) <- optional s, (")", u) <- lex t]

read :: (Read a) => String -> a
read s =  case [x | (x, t) <- reads s, ("", "") <- lex t] of
  [x] -> x
  [] -> error "Prelude.read: no parse"
  _ -> error "Prelude.read: ambiguous parse"

instance Read () where
  readsPrec _ = readParen False (\r -> [ ((), t) | ("(", s) <- lex r
                                                 , (")", t) <- lex s ])

instance Read Int where
  readsPrec _ = readSigned (\s -> [(i,t) | (x,t) <- lexDigits s
                                         , (i,[]) <- readNatLiteral x])

instance Read Float where
  readsPrec _ = readSigned
                  (\s -> [ (f,t) | (x,t) <- lex s, not (null x)
                                 , isDigit (head x), (f,[]) <- readFloat x ])
   where
    readFloat x = if all isDigit x
                    then [ (i2f i, t) | (i,t) <- readNatLiteral x ]
                    else readFloatLiteral x

readSigned :: Real a => ReadS a -> ReadS a
readSigned p = readParen False read'
  where read' r = read'' r ++ [(-x, t) | ("-", s) <- lex r, (x, t) <- read'' s]
        read'' r = [(n, s) | (str, s) <- lex r, (n, "") <- p str]

instance Read Char where
  readsPrec _ = readParen False
                  (\s -> [ (c, t) | (x, t) <- lex s, not (null x), head x == '\''
                                  , (c, []) <- readCharLiteral x ])

  readList xs = readParen False
                 (\s -> [ (cs, t) | (x, t) <- lex s, not (null x), head x == '"'
                                  , (cs, []) <- readStringLiteral x ]) xs
                ++ readListDefault xs

-- Primitive operations to read specific literals.
readNatLiteral :: ReadS Int
readNatLiteral s = prim_readNatLiteral $## s

prim_readNatLiteral :: String -> [(Int,String)]
prim_readNatLiteral external

readFloatLiteral :: ReadS Float
readFloatLiteral s = prim_readFloatLiteral $## s

prim_readFloatLiteral :: String -> [(Float,String)]
prim_readFloatLiteral external

readCharLiteral :: ReadS Char
readCharLiteral s = prim_readCharLiteral $## s

prim_readCharLiteral :: String -> [(Char,String)]
prim_readCharLiteral external

readStringLiteral :: ReadS String
readStringLiteral s = prim_readStringLiteral $## s

prim_readStringLiteral :: String -> [(String,String)]
prim_readStringLiteral external

instance Read a => Read [a] where
  readsPrec _ = readList

instance (Read a, Read b) => Read (a, b) where
  readsPrec _ = readParen False (\r -> [ ((a, b), w) | ("(", s) <- lex r
                                                     , (a, t) <- reads s
                                                     , (",", u) <- lex t
                                                     , (b, v) <- reads u
                                                     , (")", w) <- lex v ])

instance (Read a, Read b, Read c) => Read (a, b, c) where
  readsPrec _ = readParen False (\r -> [ ((a, b, c), y) | ("(", s) <- lex r
                                                        , (a, t) <- reads s
                                                        , (",", u) <- lex t
                                                        , (b, v) <- reads u
                                                        , (",", w) <- lex v
                                                        , (c, x) <- reads w
                                                        , (")", y) <- lex x ])

instance (Read a, Read b, Read c, Read d) => Read (a, b, c, d) where
  readsPrec _ = readParen False
                  (\q -> [ ((a, b, c, d), z) | ("(", r) <- lex q
                                             , (a, s) <- reads r
                                             , (",", t) <- lex s
                                             , (b, u) <- reads t
                                             , (",", v) <- lex u
                                             , (c, w) <- reads v
                                             , (",", x) <- lex w
                                             , (d, y) <- reads x
                                             , (")", z) <- lex y ])

instance (Read a, Read b, Read c, Read d, Read e) => Read (a, b, c, d, e) where
  readsPrec _ = readParen False
                  (\o -> [ ((a, b, c, d, e), z) | ("(", p) <- lex o
                                                , (a, q) <- reads p
                                                , (",", r) <- lex q
                                                , (b, s) <- reads r
                                                , (",", t) <- lex s
                                                , (c, u) <- reads t
                                                , (",", v) <- lex u
                                                , (d, w) <- reads v
                                                , (",", x) <- lex w
                                                , (e, y) <- reads x
                                                , (")", z) <- lex y ])

-- The following definitions are necessary to implement instances of Read.

lex :: ReadS String
lex xs = case xs of
    "" -> [("","")]
    (c:cs)
      | isSpace c -> lex $ dropWhile isSpace cs
    ('\'':s) ->
      [('\'' : ch ++ "'", t) | (ch, '\'' : t)  <- lexLitChar s, ch /= "'"]
    ('"':s) -> [('"' : str, t) | (str, t) <- lexString s]
    (c:cs)
      | isSingle c -> [([c], cs)]
      | isSym c -> [(c : sym, t) | (sym, t) <- [span isSym cs]]
      | isAlpha c -> [(c : nam, t) | (nam, t) <- [span isIdChar cs]]
      | isDigit c -> [(c : ds ++ fe, t) | (ds, s) <- [span isDigit cs]
                                        , (fe, t)  <- lexFracExp s]
      | otherwise -> []
  where
  isSingle c = c `elem` ",;()[]{}_`"
  isSym c = c `elem` "!@#$%&⋆+./<=>?\\^|:-~"
  isIdChar c = isAlphaNum c || c `elem` "_'"
  lexFracExp s = case s of
    ('.':c:cs)
      | isDigit c ->
        [('.' : ds ++ e, u) | (ds, t) <- lexDigits (c : cs), (e, u)  <- lexExp t]
    _ -> lexExp s
  lexExp s = case s of
    (e:cs) | e `elem` "eE" ->
      [(e : c : ds, u) | (c:t)  <- [cs], c `elem` "+-"
                       , (ds, u) <- lexDigits t] ++
        [(e : ds, t) | (ds, t) <- lexDigits cs]
    _ -> [("", s)]
  lexString s = case s of
    ('"':cs) -> [("\"", cs)]
    _ -> [(ch ++ str, u) | (ch, t) <- lexStrItem s, (str, u) <- lexString t]
  lexStrItem s = case s of
    ('\\':'&':cs) -> [("\\&", cs)]
    ('\\':c:cs)
      | isSpace c -> [("\\&", t) | '\\':t <- [dropWhile isSpace cs]]
    _ -> lexLitChar s

lexLitChar :: ReadS String
lexLitChar xs = case xs of
    "" -> []
    ('\\':cs) -> map (prefix '\\') (lexEsc cs)
    (c:cs) -> [([c], cs)]
 where
  lexEsc s = case s of
    (c:cs)
      | c `elem` "abfnrtv\\\"'" -> [([c], cs)]
    ('^':c:cs)
      | c >= '@' && c <= '_'    -> [(['^',c], cs)]
    ('b':cs) -> [prefix 'b' (span isBinDigit cs)]
    ('o':cs) -> [prefix 'o' (span isOctDigit cs)]
    ('x':cs) -> [prefix 'x' (span isHexDigit cs)]
    cs@(d:_)
      | isDigit d -> [span isDigit cs]
    cs@(c:_)
      | isUpper c -> [span isCharName cs]
    _ -> []
  isCharName c = isUpper c || isDigit c
  prefix c (t, cs) = (c : t, cs)

lexDigits :: ReadS String
lexDigits = nonNull isDigit

nonNull :: (Char -> Bool) -> ReadS String
nonNull p s = [(cs, t) | (cs@(_:_), t) <- [span p s]]

--- Returns true if the argument is an uppercase letter.
isUpper         :: Char -> Bool
isUpper c       =  c >= 'A' && c <= 'Z'

--- Returns true if the argument is an lowercase letter.
isLower         :: Char -> Bool
isLower c       =  c >= 'a' && c <= 'z'

--- Returns true if the argument is a letter.
isAlpha         :: Char -> Bool
isAlpha c       =  isUpper c || isLower c

--- Returns true if the argument is a decimal digit.
isDigit         :: Char -> Bool
isDigit c       =  c >= '0' && c <= '9'

--- Returns true if the argument is a letter or digit.
isAlphaNum      :: Char -> Bool
isAlphaNum c    =  isAlpha c || isDigit c

--- Returns true if the argument is a binary digit.
isBinDigit     :: Char -> Bool
isBinDigit c   =  c >= '0' || c <= '1'

--- Returns true if the argument is an octal digit.
isOctDigit     :: Char -> Bool
isOctDigit c    =  c >= '0' && c <= '7'

--- Returns true if the argument is a hexadecimal digit.
isHexDigit      :: Char -> Bool
isHexDigit c     = isDigit c || c >= 'A' && c <= 'F'
                             || c >= 'a' && c <= 'f'

--- Returns true if the argument is a white space.
isSpace         :: Char -> Bool
isSpace c       =  c == ' '    || c == '\t' || c == '\n' ||
                   c == '\r'   || c == '\f' || c == '\v' ||
                   c == '\xa0' || ord c `elem` [5760,6158,8192,8239,8287,12288]

-- -------------------------------------------------------------------------
-- Bounded and Enum classes and instances
-- -------------------------------------------------------------------------

class Bounded a where
  minBound, maxBound :: a

class Enum a where
  succ :: a -> a
  pred :: a -> a

  toEnum   :: Int -> a
  fromEnum :: a -> Int

  enumFrom       :: a -> [a]
  enumFromThen   :: a -> a -> [a]
  enumFromTo     :: a -> a -> [a]
  enumFromThenTo :: a -> a -> a -> [a]

  succ = toEnum . (+ 1) . fromEnum
  pred = toEnum . (\x -> x -1) . fromEnum
  enumFrom x = map toEnum [fromEnum x ..]
  enumFromThen x y = map toEnum [fromEnum x, fromEnum y ..]
  enumFromTo x y = map toEnum [fromEnum x .. fromEnum y]
  enumFromThenTo x1 x2 y = map toEnum [fromEnum x1, fromEnum x2 .. fromEnum y]

instance Bounded () where
  minBound = ()
  maxBound = ()

instance Enum () where
  succ _      = error "Prelude.Enum.().succ: bad argument"
  pred _      = error "Prelude.Enum.().pred: bad argument"

  toEnum x | x == 0    = ()
           | otherwise = error "Prelude.Enum.().toEnum: bad argument"

  fromEnum () = 0
  enumFrom ()         = [()]
  enumFromThen () ()  = let many = ():many in many
  enumFromTo () ()    = [()]
  enumFromThenTo () () () = let many = ():many in many

instance Bounded Bool where
  minBound = False
  maxBound = True

instance Enum Bool where
  succ False = True
  succ True  = error "Prelude.Enum.Bool.succ: bad argument"

  pred False = error "Prelude.Enum.Bool.pred: bad argument"
  pred True  = False

  toEnum n | n == 0 = False
           | n == 1 = True
           | otherwise = error "Prelude.Enum.Bool.toEnum: bad argument"

  fromEnum False = 0
  fromEnum True  = 1

  enumFrom = boundedEnumFrom
  enumFromThen = boundedEnumFromThen


instance (Bounded a, Bounded b) => Bounded (a, b) where
  minBound = (minBound, minBound)
  maxBound = (maxBound, maxBound)

instance (Bounded a, Bounded b, Bounded c) => Bounded (a, b, c) where
  minBound = (minBound, minBound, minBound)
  maxBound = (maxBound, maxBound, maxBound)

instance (Bounded a, Bounded b, Bounded c, Bounded d) => Bounded (a, b, c, d) where
  minBound = (minBound, minBound, minBound, minBound)
  maxBound = (maxBound, maxBound, maxBound, maxBound)

instance (Bounded a, Bounded b, Bounded c, Bounded d, Bounded e) => Bounded (a, b, c, d, e) where
  minBound = (minBound, minBound, minBound, minBound, minBound)
  maxBound = (maxBound, maxBound, maxBound, maxBound, maxBound)



instance Bounded Ordering where
  minBound = LT
  maxBound = GT

instance Enum Ordering where
  succ LT = EQ
  succ EQ = GT
  succ GT = error "Prelude.Enum.Ordering.succ: bad argument"

  pred LT = error "Prelude.Enum.Ordering.pred: bad argument"
  pred EQ = LT
  pred GT = EQ

  toEnum n | n == 0 = LT
           | n == 1 = EQ
           | n == 2 = GT
           | otherwise = error "Prelude.Enum.Ordering.toEnum: bad argument"

  fromEnum LT = 0
  fromEnum EQ = 1
  fromEnum GT = 2

  enumFrom = boundedEnumFrom
  enumFromThen = boundedEnumFromThen

uppermostCharacter :: Int
uppermostCharacter = 0x10FFFF

instance Bounded Char where
   minBound = chr 0
   maxBound = chr uppermostCharacter


instance Enum Char where

  succ c | ord c < uppermostCharacter = chr $ ord c + 1
         | otherwise = error "Prelude.Enum.Char.succ: no successor"

  pred c | ord c > 0 = chr $ ord c - 1
         | otherwise = error "Prelude.Enum.Char.succ: no predecessor"

  toEnum = chr
  fromEnum = ord

  enumFrom = boundedEnumFrom
  enumFromThen = boundedEnumFromThen

-- TODO:
-- instance Enum Float where

-- TODO (?):
-- instance Bounded Int where

instance Enum Int where
  -- TODO: is Int unbounded?
  succ x = x + 1
  pred x = x - 1

  -- TODO: correct semantic?
  toEnum n = n
  fromEnum n = n

  -- TODO: provide own implementations?
  enumFrom = enumFrom_
  enumFromTo = enumFromTo_
  enumFromThen = enumFromThen_
  enumFromThenTo = enumFromThenTo_


boundedEnumFrom :: (Enum a, Bounded a) => a -> [a]
boundedEnumFrom n = map toEnum [fromEnum n .. fromEnum (maxBound `asTypeOf` n)]

boundedEnumFromThen :: (Enum a, Bounded a) => a -> a -> [a]
boundedEnumFromThen n1 n2
  | i_n2 >= i_n1  = map toEnum [i_n1, i_n2 .. fromEnum (maxBound `asTypeOf` n1)]
  | otherwise     = map toEnum [i_n1, i_n2 .. fromEnum (minBound `asTypeOf` n1)]
  where
    i_n1 = fromEnum n1
    i_n2 = fromEnum n2

-- -------------------------------------------------------------------------
-- Numeric classes and instances
-- -------------------------------------------------------------------------

-- minimal definition: all (except negate or (-))
class Num a where
  (+), (-), (*) :: a -> a -> a
  negate :: a -> a
  abs :: a -> a
  signum :: a -> a

Finn Teegen's avatar
Finn Teegen committed
1648
  fromInt :: Int -> a
1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666

  x - y = x + negate y
  negate x = 0 - x

instance Num Int where
  x + y = x +$ y
  x - y = x -$ y
  x * y = x *$ y

  negate x = 0 - x

  abs x | x >= 0 = x
        | otherwise = negate x

  signum x | x > 0     = 1
           | x == 0    = 0
           | otherwise = -1

Finn Teegen's avatar
Finn Teegen committed
1667
  fromInt x = x
1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683

instance Num Float where
  x + y = x +. y
  x - y = x -. y
  x * y = x *. y

  negate x = negateFloat x

  abs x | x >= 0 = x
        | otherwise = negate x


  signum x | x > 0     = 1
           | x == 0    = 0
           | otherwise = -1

Finn Teegen's avatar
Finn Teegen committed
1684
  fromInt x = i2f x
1685

Finn Teegen's avatar
Finn Teegen committed
1686
-- minimal definition: fromFloat and (recip or (/))
1687 1688 1689 1690 1691 1692 1693 1694
class Num a => Fractional a where

  (/) :: a -> a -> a
  recip :: a -> a

  recip x = 1/x
  x / y = x * recip y

Finn Teegen's avatar
Finn Teegen committed
1695
  fromFloat :: Float -> a -- since we have no type Rational
1696 1697 1698 1699 1700

instance Fractional Float where
  x / y = x /. y
  recip x = 1.0/x

Finn Teegen's avatar
Finn Teegen committed
1701
  fromFloat x = x
1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775

class (Num a, Ord a) => Real a where
  -- toRational :: a -> Rational

class Real a => Integral a where
  div  :: a -> a -> a
  mod  :: a -> a -> a
  quot :: a -> a -> a
  rem  :: a -> a -> a

  divMod  :: a -> a -> (a, a)
  quotRem :: a -> a -> (a, a)

  n `div`  d = q where (q, _) = divMod n d
  n `mod`  d = r where (_, r) = divMod n d
  n `quot` d = q where (q, _) = n `quotRem` d
  n `rem`  d = r where (_, r) = n `quotRem` d

instance Real Int where
  -- no class methods to implement

instance Real Float where
  -- no class methods to implement

instance Integral Int where
  divMod n d = (n `div_` d, n `mod_` d)
  quotRem n d = (n `quot_` d, n `rem_` d)

-- -------------------------------------------------------------------------
-- Helper functions
-- -------------------------------------------------------------------------

asTypeOf :: a -> a -> a
asTypeOf = const

-- -------------------------------------------------------------------------
-- Floating point operations
-- -------------------------------------------------------------------------

--- Addition on floats.
(+.)   :: Float -> Float -> Float
x +. y = (prim_Float_plus $# y) $# x

prim_Float_plus :: Float -> Float -> Float
prim_Float_plus external

--- Subtraction on floats.
(-.)   :: Float -> Float -> Float
x -. y = (prim_Float_minus $# y) $# x

prim_Float_minus :: Float -> Float -> Float
prim_Float_minus external

--- Multiplication on floats.
(*.)   :: Float -> Float -> Float
x *. y = (prim_Float_times $# y) $# x

prim_Float_times :: Float -> Float -> Float
prim_Float_times external

--- Division on floats.
(/.)   :: Float -> Float -> Float
x /. y = (prim_Float_div $# y) $# x

prim_Float_div :: Float -> Float -> Float
prim_Float_div external

--- Conversion function from integers to floats.
i2f    :: Int -> Float
i2f x = prim_i2f $# x

prim_i2f :: Int -> Float
prim_i2f external

Björn Peemöller 's avatar
Björn Peemöller committed
1776
-- the end of the standard prelude
1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806

class Functor f where
  fmap :: (a -> b) -> f a -> f b

instance Functor [] where
  fmap = map

class Monad m where
  (>>=) :: m a -> (a -> m b) -> m b
  (>>) :: m a -> m b -> m b
  m >> k = m >>= \_ -> k
  return :: a -> m a
  fail :: String -> m a
  fail s = error s

instance Monad IO where
  a1 >>= a2 = a1 >>=$ a2
  a1 >>  a2 = a1 >>$  a2
  return x = returnIO x

instance Monad Maybe where
  Nothing >>= _ = Nothing
  (Just x) >>= f = f x
  return = Just
  fail _ = Nothing

instance Monad [] where
  xs >>= f = [y | x <- xs, y <- f x]
  return x = [x]
  fail _ = []