Eq and Ord have moved into GHC.Classes
[ghc-base.git] / GHC / Base.lhs
1 \section[GHC.Base]{Module @GHC.Base@}
2
3 The overall structure of the GHC Prelude is a bit tricky.
4
5   a) We want to avoid "orphan modules", i.e. ones with instance
6         decls that don't belong either to a tycon or a class
7         defined in the same module
8
9   b) We want to avoid giant modules
10
11 So the rough structure is as follows, in (linearised) dependency order
12
13
14 GHC.Prim                Has no implementation.  It defines built-in things, and
15                 by importing it you bring them into scope.
16                 The source file is GHC.Prim.hi-boot, which is just
17                 copied to make GHC.Prim.hi
18
19 GHC.Base        Classes: Eq, Ord, Functor, Monad
20                 Types:   list, (), Int, Bool, Ordering, Char, String
21
22 Data.Tuple      Types: tuples, plus instances for GHC.Base classes
23
24 GHC.Show        Class: Show, plus instances for GHC.Base/GHC.Tup types
25
26 GHC.Enum        Class: Enum,  plus instances for GHC.Base/GHC.Tup types
27
28 Data.Maybe      Type: Maybe, plus instances for GHC.Base classes
29
30 GHC.List        List functions
31
32 GHC.Num         Class: Num, plus instances for Int
33                 Type:  Integer, plus instances for all classes so far (Eq, Ord, Num, Show)
34
35                 Integer is needed here because it is mentioned in the signature
36                 of 'fromInteger' in class Num
37
38 GHC.Real        Classes: Real, Integral, Fractional, RealFrac
39                          plus instances for Int, Integer
40                 Types:  Ratio, Rational
41                         plus intances for classes so far
42
43                 Rational is needed here because it is mentioned in the signature
44                 of 'toRational' in class Real
45
46 GHC.ST  The ST monad, instances and a few helper functions
47
48 Ix              Classes: Ix, plus instances for Int, Bool, Char, Integer, Ordering, tuples
49
50 GHC.Arr         Types: Array, MutableArray, MutableVar
51
52                 Arrays are used by a function in GHC.Float
53
54 GHC.Float       Classes: Floating, RealFloat
55                 Types:   Float, Double, plus instances of all classes so far
56
57                 This module contains everything to do with floating point.
58                 It is a big module (900 lines)
59                 With a bit of luck, many modules can be compiled without ever reading GHC.Float.hi
60
61
62 Other Prelude modules are much easier with fewer complex dependencies.
63
64 \begin{code}
65 {-# OPTIONS_GHC -XNoImplicitPrelude #-}
66 {-# OPTIONS_HADDOCK hide #-}
67 -----------------------------------------------------------------------------
68 -- |
69 -- Module      :  GHC.Base
70 -- Copyright   :  (c) The University of Glasgow, 1992-2002
71 -- License     :  see libraries/base/LICENSE
72 -- 
73 -- Maintainer  :  cvs-ghc@haskell.org
74 -- Stability   :  internal
75 -- Portability :  non-portable (GHC extensions)
76 --
77 -- Basic data types and classes.
78 -- 
79 -----------------------------------------------------------------------------
80
81 #include "MachDeps.h"
82
83 -- #hide
84 module GHC.Base
85         (
86         module GHC.Base,
87         module GHC.Bool,
88         module GHC.Classes,
89         module GHC.Generics,
90         module GHC.Ordering,
91         module GHC.Types,
92         module GHC.Prim,        -- Re-export GHC.Prim and GHC.Err, to avoid lots
93         module GHC.Err          -- of people having to import it explicitly
94   ) 
95         where
96
97 import GHC.Types
98 import GHC.Bool
99 import GHC.Classes
100 import GHC.Generics
101 import GHC.Ordering
102 import GHC.Prim
103 import {-# SOURCE #-} GHC.Err
104
105 infixr 9  .
106 infixr 5  ++
107 infixl 1  >>, >>=
108 infixr 0  $
109
110 default ()              -- Double isn't available yet
111 \end{code}
112
113
114 %*********************************************************
115 %*                                                      *
116 \subsection{DEBUGGING STUFF}
117 %*  (for use when compiling GHC.Base itself doesn't work)
118 %*                                                      *
119 %*********************************************************
120
121 \begin{code}
122 {-
123 data  Bool  =  False | True
124 data Ordering = LT | EQ | GT 
125 data Char = C# Char#
126 type  String = [Char]
127 data Int = I# Int#
128 data  ()  =  ()
129 data [] a = MkNil
130
131 not True = False
132 (&&) True True = True
133 otherwise = True
134
135 build = error "urk"
136 foldr = error "urk"
137
138 unpackCString# :: Addr# -> [Char]
139 unpackFoldrCString# :: Addr# -> (Char  -> a -> a) -> a -> a 
140 unpackAppendCString# :: Addr# -> [Char] -> [Char]
141 unpackCStringUtf8# :: Addr# -> [Char]
142 unpackCString# a = error "urk"
143 unpackFoldrCString# a = error "urk"
144 unpackAppendCString# a = error "urk"
145 unpackCStringUtf8# a = error "urk"
146 -}
147 \end{code}
148
149
150 %*********************************************************
151 %*                                                      *
152 \subsection{Monadic classes @Functor@, @Monad@ }
153 %*                                                      *
154 %*********************************************************
155
156 \begin{code}
157 {- | The 'Functor' class is used for types that can be mapped over.
158 Instances of 'Functor' should satisfy the following laws:
159
160 > fmap id  ==  id
161 > fmap (f . g)  ==  fmap f . fmap g
162
163 The instances of 'Functor' for lists, 'Data.Maybe.Maybe' and 'System.IO.IO'
164 defined in the "Prelude" satisfy these laws.
165 -}
166
167 class  Functor f  where
168     fmap        :: (a -> b) -> f a -> f b
169
170 {- | The 'Monad' class defines the basic operations over a /monad/,
171 a concept from a branch of mathematics known as /category theory/.
172 From the perspective of a Haskell programmer, however, it is best to
173 think of a monad as an /abstract datatype/ of actions.
174 Haskell's @do@ expressions provide a convenient syntax for writing
175 monadic expressions.
176
177 Minimal complete definition: '>>=' and 'return'.
178
179 Instances of 'Monad' should satisfy the following laws:
180
181 > return a >>= k  ==  k a
182 > m >>= return  ==  m
183 > m >>= (\x -> k x >>= h)  ==  (m >>= k) >>= h
184
185 Instances of both 'Monad' and 'Functor' should additionally satisfy the law:
186
187 > fmap f xs  ==  xs >>= return . f
188
189 The instances of 'Monad' for lists, 'Data.Maybe.Maybe' and 'System.IO.IO'
190 defined in the "Prelude" satisfy these laws.
191 -}
192
193 class  Monad m  where
194     -- | Sequentially compose two actions, passing any value produced
195     -- by the first as an argument to the second.
196     (>>=)       :: forall a b. m a -> (a -> m b) -> m b
197     -- | Sequentially compose two actions, discarding any value produced
198     -- by the first, like sequencing operators (such as the semicolon)
199     -- in imperative languages.
200     (>>)        :: forall a b. m a -> m b -> m b
201         -- Explicit for-alls so that we know what order to
202         -- give type arguments when desugaring
203
204     -- | Inject a value into the monadic type.
205     return      :: a -> m a
206     -- | Fail with a message.  This operation is not part of the
207     -- mathematical definition of a monad, but is invoked on pattern-match
208     -- failure in a @do@ expression.
209     fail        :: String -> m a
210
211     m >> k      = m >>= \_ -> k
212     fail s      = error s
213 \end{code}
214
215
216 %*********************************************************
217 %*                                                      *
218 \subsection{The list type}
219 %*                                                      *
220 %*********************************************************
221
222 \begin{code}
223 -- do explicitly: deriving (Eq, Ord)
224 -- to avoid weird names like con2tag_[]#
225
226 instance (Eq a) => Eq [a] where
227     {-# SPECIALISE instance Eq [Char] #-}
228     []     == []     = True
229     (x:xs) == (y:ys) = x == y && xs == ys
230     _xs    == _ys    = False
231
232 instance (Ord a) => Ord [a] where
233     {-# SPECIALISE instance Ord [Char] #-}
234     compare []     []     = EQ
235     compare []     (_:_)  = LT
236     compare (_:_)  []     = GT
237     compare (x:xs) (y:ys) = case compare x y of
238                                 EQ    -> compare xs ys
239                                 other -> other
240
241 instance Functor [] where
242     fmap = map
243
244 instance  Monad []  where
245     m >>= k             = foldr ((++) . k) [] m
246     m >> k              = foldr ((++) . (\ _ -> k)) [] m
247     return x            = [x]
248     fail _              = []
249 \end{code}
250
251 A few list functions that appear here because they are used here.
252 The rest of the prelude list functions are in GHC.List.
253
254 ----------------------------------------------
255 --      foldr/build/augment
256 ----------------------------------------------
257   
258 \begin{code}
259 -- | 'foldr', applied to a binary operator, a starting value (typically
260 -- the right-identity of the operator), and a list, reduces the list
261 -- using the binary operator, from right to left:
262 --
263 -- > foldr f z [x1, x2, ..., xn] == x1 `f` (x2 `f` ... (xn `f` z)...)
264
265 foldr            :: (a -> b -> b) -> b -> [a] -> b
266 -- foldr _ z []     =  z
267 -- foldr f z (x:xs) =  f x (foldr f z xs)
268 {-# INLINE [0] foldr #-}
269 -- Inline only in the final stage, after the foldr/cons rule has had a chance
270 foldr k z xs = go xs
271              where
272                go []     = z
273                go (y:ys) = y `k` go ys
274
275 -- | A list producer that can be fused with 'foldr'.
276 -- This function is merely
277 --
278 -- >    build g = g (:) []
279 --
280 -- but GHC's simplifier will transform an expression of the form
281 -- @'foldr' k z ('build' g)@, which may arise after inlining, to @g k z@,
282 -- which avoids producing an intermediate list.
283
284 build   :: forall a. (forall b. (a -> b -> b) -> b -> b) -> [a]
285 {-# INLINE [1] build #-}
286         -- The INLINE is important, even though build is tiny,
287         -- because it prevents [] getting inlined in the version that
288         -- appears in the interface file.  If [] *is* inlined, it
289         -- won't match with [] appearing in rules in an importing module.
290         --
291         -- The "1" says to inline in phase 1
292
293 build g = g (:) []
294
295 -- | A list producer that can be fused with 'foldr'.
296 -- This function is merely
297 --
298 -- >    augment g xs = g (:) xs
299 --
300 -- but GHC's simplifier will transform an expression of the form
301 -- @'foldr' k z ('augment' g xs)@, which may arise after inlining, to
302 -- @g k ('foldr' k z xs)@, which avoids producing an intermediate list.
303
304 augment :: forall a. (forall b. (a->b->b) -> b -> b) -> [a] -> [a]
305 {-# INLINE [1] augment #-}
306 augment g xs = g (:) xs
307
308 {-# RULES
309 "fold/build"    forall k z (g::forall b. (a->b->b) -> b -> b) . 
310                 foldr k z (build g) = g k z
311
312 "foldr/augment" forall k z xs (g::forall b. (a->b->b) -> b -> b) . 
313                 foldr k z (augment g xs) = g k (foldr k z xs)
314
315 "foldr/id"                        foldr (:) [] = \x  -> x
316 "foldr/app"     [1] forall ys. foldr (:) ys = \xs -> xs ++ ys
317         -- Only activate this from phase 1, because that's
318         -- when we disable the rule that expands (++) into foldr
319
320 -- The foldr/cons rule looks nice, but it can give disastrously
321 -- bloated code when commpiling
322 --      array (a,b) [(1,2), (2,2), (3,2), ...very long list... ]
323 -- i.e. when there are very very long literal lists
324 -- So I've disabled it for now. We could have special cases
325 -- for short lists, I suppose.
326 -- "foldr/cons" forall k z x xs. foldr k z (x:xs) = k x (foldr k z xs)
327
328 "foldr/single"  forall k z x. foldr k z [x] = k x z
329 "foldr/nil"     forall k z.   foldr k z []  = z 
330
331 "augment/build" forall (g::forall b. (a->b->b) -> b -> b)
332                        (h::forall b. (a->b->b) -> b -> b) .
333                        augment g (build h) = build (\c n -> g c (h c n))
334 "augment/nil"   forall (g::forall b. (a->b->b) -> b -> b) .
335                         augment g [] = build g
336  #-}
337
338 -- This rule is true, but not (I think) useful:
339 --      augment g (augment h t) = augment (\cn -> g c (h c n)) t
340 \end{code}
341
342
343 ----------------------------------------------
344 --              map     
345 ----------------------------------------------
346
347 \begin{code}
348 -- | 'map' @f xs@ is the list obtained by applying @f@ to each element
349 -- of @xs@, i.e.,
350 --
351 -- > map f [x1, x2, ..., xn] == [f x1, f x2, ..., f xn]
352 -- > map f [x1, x2, ...] == [f x1, f x2, ...]
353
354 map :: (a -> b) -> [a] -> [b]
355 map _ []     = []
356 map f (x:xs) = f x : map f xs
357
358 -- Note eta expanded
359 mapFB ::  (elt -> lst -> lst) -> (a -> elt) -> a -> lst -> lst
360 {-# INLINE [0] mapFB #-}
361 mapFB c f x ys = c (f x) ys
362
363 -- The rules for map work like this.
364 -- 
365 -- Up to (but not including) phase 1, we use the "map" rule to
366 -- rewrite all saturated applications of map with its build/fold 
367 -- form, hoping for fusion to happen.
368 -- In phase 1 and 0, we switch off that rule, inline build, and
369 -- switch on the "mapList" rule, which rewrites the foldr/mapFB
370 -- thing back into plain map.  
371 --
372 -- It's important that these two rules aren't both active at once 
373 -- (along with build's unfolding) else we'd get an infinite loop 
374 -- in the rules.  Hence the activation control below.
375 --
376 -- The "mapFB" rule optimises compositions of map.
377 --
378 -- This same pattern is followed by many other functions: 
379 -- e.g. append, filter, iterate, repeat, etc.
380
381 {-# RULES
382 "map"       [~1] forall f xs.   map f xs                = build (\c n -> foldr (mapFB c f) n xs)
383 "mapList"   [1]  forall f.      foldr (mapFB (:) f) []  = map f
384 "mapFB"     forall c f g.       mapFB (mapFB c f) g     = mapFB c (f.g) 
385   #-}
386 \end{code}
387
388
389 ----------------------------------------------
390 --              append  
391 ----------------------------------------------
392 \begin{code}
393 -- | Append two lists, i.e.,
394 --
395 -- > [x1, ..., xm] ++ [y1, ..., yn] == [x1, ..., xm, y1, ..., yn]
396 -- > [x1, ..., xm] ++ [y1, ...] == [x1, ..., xm, y1, ...]
397 --
398 -- If the first list is not finite, the result is the first list.
399
400 (++) :: [a] -> [a] -> [a]
401 (++) []     ys = ys
402 (++) (x:xs) ys = x : xs ++ ys
403
404 {-# RULES
405 "++"    [~1] forall xs ys. xs ++ ys = augment (\c n -> foldr c n xs) ys
406   #-}
407
408 \end{code}
409
410
411 %*********************************************************
412 %*                                                      *
413 \subsection{Type @Bool@}
414 %*                                                      *
415 %*********************************************************
416
417 \begin{code}
418 -- |The 'Bool' type is an enumeration.  It is defined with 'False'
419 -- first so that the corresponding 'Prelude.Enum' instance will give
420 -- 'Prelude.fromEnum' 'False' the value zero, and
421 -- 'Prelude.fromEnum' 'True' the value 1.
422 -- The actual definition is in the ghc-prim package.
423
424 -- XXX These don't work:
425 -- deriving instance Eq Bool
426 -- deriving instance Ord Bool
427 -- <wired into compiler>:
428 --     Illegal binding of built-in syntax: con2tag_Bool#
429
430 instance Eq Bool where
431     True  == True  = True
432     False == False = True
433     _     == _     = False
434
435 instance Ord Bool where
436     compare False True  = LT
437     compare True  False = GT
438     compare _     _     = EQ
439
440 -- Read is in GHC.Read, Show in GHC.Show
441
442 -- |'otherwise' is defined as the value 'True'.  It helps to make
443 -- guards more readable.  eg.
444 --
445 -- >  f x | x < 0     = ...
446 -- >      | otherwise = ...
447 otherwise               :: Bool
448 otherwise               =  True
449 \end{code}
450
451 %*********************************************************
452 %*                                                      *
453 \subsection{Type @Ordering@}
454 %*                                                      *
455 %*********************************************************
456
457 \begin{code}
458 -- | Represents an ordering relationship between two values: less
459 -- than, equal to, or greater than.  An 'Ordering' is returned by
460 -- 'compare'.
461 -- XXX These don't work:
462 -- deriving instance Eq Ordering
463 -- deriving instance Ord Ordering
464 -- Illegal binding of built-in syntax: con2tag_Ordering#
465 instance Eq Ordering where
466     EQ == EQ = True
467     LT == LT = True
468     GT == GT = True
469     _  == _  = False
470         -- Read in GHC.Read, Show in GHC.Show
471
472 instance Ord Ordering where
473     LT <= _  = True
474     _  <= LT = False
475     EQ <= _  = True
476     _  <= EQ = False
477     GT <= GT = True
478 \end{code}
479
480
481 %*********************************************************
482 %*                                                      *
483 \subsection{Type @Char@ and @String@}
484 %*                                                      *
485 %*********************************************************
486
487 \begin{code}
488 -- | A 'String' is a list of characters.  String constants in Haskell are values
489 -- of type 'String'.
490 --
491 type String = [Char]
492
493 {-| The character type 'Char' is an enumeration whose values represent
494 Unicode (or equivalently ISO\/IEC 10646) characters
495 (see <http://www.unicode.org/> for details).
496 This set extends the ISO 8859-1 (Latin-1) character set
497 (the first 256 charachers), which is itself an extension of the ASCII
498 character set (the first 128 characters).
499 A character literal in Haskell has type 'Char'.
500
501 To convert a 'Char' to or from the corresponding 'Int' value defined
502 by Unicode, use 'Prelude.toEnum' and 'Prelude.fromEnum' from the
503 'Prelude.Enum' class respectively (or equivalently 'ord' and 'chr').
504 -}
505
506 -- We don't use deriving for Eq and Ord, because for Ord the derived
507 -- instance defines only compare, which takes two primops.  Then
508 -- '>' uses compare, and therefore takes two primops instead of one.
509
510 instance Eq Char where
511     (C# c1) == (C# c2) = c1 `eqChar#` c2
512     (C# c1) /= (C# c2) = c1 `neChar#` c2
513
514 instance Ord Char where
515     (C# c1) >  (C# c2) = c1 `gtChar#` c2
516     (C# c1) >= (C# c2) = c1 `geChar#` c2
517     (C# c1) <= (C# c2) = c1 `leChar#` c2
518     (C# c1) <  (C# c2) = c1 `ltChar#` c2
519
520 {-# RULES
521 "x# `eqChar#` x#" forall x#. x# `eqChar#` x# = True
522 "x# `neChar#` x#" forall x#. x# `neChar#` x# = False
523 "x# `gtChar#` x#" forall x#. x# `gtChar#` x# = False
524 "x# `geChar#` x#" forall x#. x# `geChar#` x# = True
525 "x# `leChar#` x#" forall x#. x# `leChar#` x# = True
526 "x# `ltChar#` x#" forall x#. x# `ltChar#` x# = False
527   #-}
528
529 -- | The 'Prelude.toEnum' method restricted to the type 'Data.Char.Char'.
530 chr :: Int -> Char
531 chr (I# i#) | int2Word# i# `leWord#` int2Word# 0x10FFFF# = C# (chr# i#)
532             | otherwise                                  = error "Prelude.chr: bad argument"
533
534 unsafeChr :: Int -> Char
535 unsafeChr (I# i#) = C# (chr# i#)
536
537 -- | The 'Prelude.fromEnum' method restricted to the type 'Data.Char.Char'.
538 ord :: Char -> Int
539 ord (C# c#) = I# (ord# c#)
540 \end{code}
541
542 String equality is used when desugaring pattern-matches against strings.
543
544 \begin{code}
545 eqString :: String -> String -> Bool
546 eqString []       []       = True
547 eqString (c1:cs1) (c2:cs2) = c1 == c2 && cs1 `eqString` cs2
548 eqString _        _        = False
549
550 {-# RULES "eqString" (==) = eqString #-}
551 -- eqString also has a BuiltInRule in PrelRules.lhs:
552 --      eqString (unpackCString# (Lit s1)) (unpackCString# (Lit s2) = s1==s2
553 \end{code}
554
555
556 %*********************************************************
557 %*                                                      *
558 \subsection{Type @Int@}
559 %*                                                      *
560 %*********************************************************
561
562 \begin{code}
563 zeroInt, oneInt, twoInt, maxInt, minInt :: Int
564 zeroInt = I# 0#
565 oneInt  = I# 1#
566 twoInt  = I# 2#
567
568 {- Seems clumsy. Should perhaps put minInt and MaxInt directly into MachDeps.h -}
569 #if WORD_SIZE_IN_BITS == 31
570 minInt  = I# (-0x40000000#)
571 maxInt  = I# 0x3FFFFFFF#
572 #elif WORD_SIZE_IN_BITS == 32
573 minInt  = I# (-0x80000000#)
574 maxInt  = I# 0x7FFFFFFF#
575 #else 
576 minInt  = I# (-0x8000000000000000#)
577 maxInt  = I# 0x7FFFFFFFFFFFFFFF#
578 #endif
579
580 instance Eq Int where
581     (==) = eqInt
582     (/=) = neInt
583
584 instance Ord Int where
585     compare = compareInt
586     (<)     = ltInt
587     (<=)    = leInt
588     (>=)    = geInt
589     (>)     = gtInt
590
591 compareInt :: Int -> Int -> Ordering
592 (I# x#) `compareInt` (I# y#) = compareInt# x# y#
593
594 compareInt# :: Int# -> Int# -> Ordering
595 compareInt# x# y#
596     | x# <#  y# = LT
597     | x# ==# y# = EQ
598     | otherwise = GT
599 \end{code}
600
601
602 %*********************************************************
603 %*                                                      *
604 \subsection{The function type}
605 %*                                                      *
606 %*********************************************************
607
608 \begin{code}
609 -- | Identity function.
610 id                      :: a -> a
611 id x                    =  x
612
613 -- | The call '(lazy e)' means the same as 'e', but 'lazy' has a 
614 -- magical strictness property: it is lazy in its first argument, 
615 -- even though its semantics is strict.
616 lazy :: a -> a
617 lazy x = x
618 -- Implementation note: its strictness and unfolding are over-ridden
619 -- by the definition in MkId.lhs; in both cases to nothing at all.
620 -- That way, 'lazy' does not get inlined, and the strictness analyser
621 -- sees it as lazy.  Then the worker/wrapper phase inlines it.
622 -- Result: happiness
623
624
625 -- | The call '(inline f)' reduces to 'f', but 'inline' has a BuiltInRule
626 -- that tries to inline 'f' (if it has an unfolding) unconditionally
627 -- The 'NOINLINE' pragma arranges that inline only gets inlined (and
628 -- hence eliminated) late in compilation, after the rule has had
629 -- a god chance to fire.
630 inline :: a -> a
631 {-# NOINLINE[0] inline #-}
632 inline x = x
633
634 -- Assertion function.  This simply ignores its boolean argument.
635 -- The compiler may rewrite it to @('assertError' line)@.
636
637 -- | If the first argument evaluates to 'True', then the result is the
638 -- second argument.  Otherwise an 'AssertionFailed' exception is raised,
639 -- containing a 'String' with the source file and line number of the
640 -- call to 'assert'.
641 --
642 -- Assertions can normally be turned on or off with a compiler flag
643 -- (for GHC, assertions are normally on unless optimisation is turned on 
644 -- with @-O@ or the @-fignore-asserts@
645 -- option is given).  When assertions are turned off, the first
646 -- argument to 'assert' is ignored, and the second argument is
647 -- returned as the result.
648
649 --      SLPJ: in 5.04 etc 'assert' is in GHC.Prim,
650 --      but from Template Haskell onwards it's simply
651 --      defined here in Base.lhs
652 assert :: Bool -> a -> a
653 assert _pred r = r
654
655 breakpoint :: a -> a
656 breakpoint r = r
657
658 breakpointCond :: Bool -> a -> a
659 breakpointCond _ r = r
660
661 data Opaque = forall a. O a
662
663 -- | Constant function.
664 const                   :: a -> b -> a
665 const x _               =  x
666
667 -- | Function composition.
668 {-# INLINE (.) #-}
669 (.)       :: (b -> c) -> (a -> b) -> a -> c
670 (.) f g x = f (g x)
671
672 -- | @'flip' f@ takes its (first) two arguments in the reverse order of @f@.
673 flip                    :: (a -> b -> c) -> b -> a -> c
674 flip f x y              =  f y x
675
676 -- | Application operator.  This operator is redundant, since ordinary
677 -- application @(f x)@ means the same as @(f '$' x)@. However, '$' has
678 -- low, right-associative binding precedence, so it sometimes allows
679 -- parentheses to be omitted; for example:
680 --
681 -- >     f $ g $ h x  =  f (g (h x))
682 --
683 -- It is also useful in higher-order situations, such as @'map' ('$' 0) xs@,
684 -- or @'Data.List.zipWith' ('$') fs xs@.
685 {-# INLINE ($) #-}
686 ($)                     :: (a -> b) -> a -> b
687 f $ x                   =  f x
688
689 -- | @'until' p f@ yields the result of applying @f@ until @p@ holds.
690 until                   :: (a -> Bool) -> (a -> a) -> a -> a
691 until p f x | p x       =  x
692             | otherwise =  until p f (f x)
693
694 -- | 'asTypeOf' is a type-restricted version of 'const'.  It is usually
695 -- used as an infix operator, and its typing forces its first argument
696 -- (which is usually overloaded) to have the same type as the second.
697 asTypeOf                :: a -> a -> a
698 asTypeOf                =  const
699 \end{code}
700
701 %*********************************************************
702 %*                                                      *
703 \subsection{@getTag@}
704 %*                                                      *
705 %*********************************************************
706
707 Returns the 'tag' of a constructor application; this function is used
708 by the deriving code for Eq, Ord and Enum.
709
710 The primitive dataToTag# requires an evaluated constructor application
711 as its argument, so we provide getTag as a wrapper that performs the
712 evaluation before calling dataToTag#.  We could have dataToTag#
713 evaluate its argument, but we prefer to do it this way because (a)
714 dataToTag# can be an inline primop if it doesn't need to do any
715 evaluation, and (b) we want to expose the evaluation to the
716 simplifier, because it might be possible to eliminate the evaluation
717 in the case when the argument is already known to be evaluated.
718
719 \begin{code}
720 {-# INLINE getTag #-}
721 getTag :: a -> Int#
722 getTag x = x `seq` dataToTag# x
723 \end{code}
724
725 %*********************************************************
726 %*                                                      *
727 \subsection{Numeric primops}
728 %*                                                      *
729 %*********************************************************
730
731 \begin{code}
732 divInt# :: Int# -> Int# -> Int#
733 x# `divInt#` y#
734         -- Be careful NOT to overflow if we do any additional arithmetic
735         -- on the arguments...  the following  previous version of this
736         -- code has problems with overflow:
737 --    | (x# ># 0#) && (y# <# 0#) = ((x# -# y#) -# 1#) `quotInt#` y#
738 --    | (x# <# 0#) && (y# ># 0#) = ((x# -# y#) +# 1#) `quotInt#` y#
739     | (x# ># 0#) && (y# <# 0#) = ((x# -# 1#) `quotInt#` y#) -# 1#
740     | (x# <# 0#) && (y# ># 0#) = ((x# +# 1#) `quotInt#` y#) -# 1#
741     | otherwise                = x# `quotInt#` y#
742
743 modInt# :: Int# -> Int# -> Int#
744 x# `modInt#` y#
745     | (x# ># 0#) && (y# <# 0#) ||
746       (x# <# 0#) && (y# ># 0#)    = if r# /=# 0# then r# +# y# else 0#
747     | otherwise                   = r#
748     where
749     r# = x# `remInt#` y#
750 \end{code}
751
752 Definitions of the boxed PrimOps; these will be
753 used in the case of partial applications, etc.
754
755 \begin{code}
756 {-# INLINE eqInt #-}
757 {-# INLINE neInt #-}
758 {-# INLINE gtInt #-}
759 {-# INLINE geInt #-}
760 {-# INLINE ltInt #-}
761 {-# INLINE leInt #-}
762 {-# INLINE plusInt #-}
763 {-# INLINE minusInt #-}
764 {-# INLINE timesInt #-}
765 {-# INLINE quotInt #-}
766 {-# INLINE remInt #-}
767 {-# INLINE negateInt #-}
768
769 plusInt, minusInt, timesInt, quotInt, remInt, divInt, modInt, gcdInt :: Int -> Int -> Int
770 (I# x) `plusInt`  (I# y) = I# (x +# y)
771 (I# x) `minusInt` (I# y) = I# (x -# y)
772 (I# x) `timesInt` (I# y) = I# (x *# y)
773 (I# x) `quotInt`  (I# y) = I# (x `quotInt#` y)
774 (I# x) `remInt`   (I# y) = I# (x `remInt#`  y)
775 (I# x) `divInt`   (I# y) = I# (x `divInt#`  y)
776 (I# x) `modInt`   (I# y) = I# (x `modInt#`  y)
777
778 {-# RULES
779 "x# +# 0#" forall x#. x# +# 0# = x#
780 "0# +# x#" forall x#. 0# +# x# = x#
781 "x# -# 0#" forall x#. x# -# 0# = x#
782 "x# -# x#" forall x#. x# -# x# = 0#
783 "x# *# 0#" forall x#. x# *# 0# = 0#
784 "0# *# x#" forall x#. 0# *# x# = 0#
785 "x# *# 1#" forall x#. x# *# 1# = x#
786 "1# *# x#" forall x#. 1# *# x# = x#
787   #-}
788
789 gcdInt (I# a) (I# b) = g a b
790    where g 0# 0# = error "GHC.Base.gcdInt: gcd 0 0 is undefined"
791          g 0# _  = I# absB
792          g _  0# = I# absA
793          g _  _  = I# (gcdInt# absA absB)
794
795          absInt x = if x <# 0# then negateInt# x else x
796
797          absA     = absInt a
798          absB     = absInt b
799
800 negateInt :: Int -> Int
801 negateInt (I# x) = I# (negateInt# x)
802
803 gtInt, geInt, eqInt, neInt, ltInt, leInt :: Int -> Int -> Bool
804 (I# x) `gtInt` (I# y) = x >#  y
805 (I# x) `geInt` (I# y) = x >=# y
806 (I# x) `eqInt` (I# y) = x ==# y
807 (I# x) `neInt` (I# y) = x /=# y
808 (I# x) `ltInt` (I# y) = x <#  y
809 (I# x) `leInt` (I# y) = x <=# y
810
811 {-# RULES
812 "x# ># x#"  forall x#. x# >#  x# = False
813 "x# >=# x#" forall x#. x# >=# x# = True
814 "x# ==# x#" forall x#. x# ==# x# = True
815 "x# /=# x#" forall x#. x# /=# x# = False
816 "x# <# x#"  forall x#. x# <#  x# = False
817 "x# <=# x#" forall x#. x# <=# x# = True
818   #-}
819
820 {-# RULES
821 "plusFloat x 0.0"   forall x#. plusFloat#  x#   0.0# = x#
822 "plusFloat 0.0 x"   forall x#. plusFloat#  0.0# x#   = x#
823 "minusFloat x 0.0"  forall x#. minusFloat# x#   0.0# = x#
824 "minusFloat x x"    forall x#. minusFloat# x#   x#   = 0.0#
825 "timesFloat x 0.0"  forall x#. timesFloat# x#   0.0# = 0.0#
826 "timesFloat0.0 x"   forall x#. timesFloat# 0.0# x#   = 0.0#
827 "timesFloat x 1.0"  forall x#. timesFloat# x#   1.0# = x#
828 "timesFloat 1.0 x"  forall x#. timesFloat# 1.0# x#   = x#
829 "divideFloat x 1.0" forall x#. divideFloat# x#  1.0# = x#
830   #-}
831
832 {-# RULES
833 "plusDouble x 0.0"   forall x#. (+##) x#    0.0## = x#
834 "plusDouble 0.0 x"   forall x#. (+##) 0.0## x#    = x#
835 "minusDouble x 0.0"  forall x#. (-##) x#    0.0## = x#
836 "timesDouble x 1.0"  forall x#. (*##) x#    1.0## = x#
837 "timesDouble 1.0 x"  forall x#. (*##) 1.0## x#    = x#
838 "divideDouble x 1.0" forall x#. (/##) x#    1.0## = x#
839   #-}
840
841 {-
842 We'd like to have more rules, but for example:
843
844 This gives wrong answer (0) for NaN - NaN (should be NaN):
845     "minusDouble x x"    forall x#. (-##) x#    x#    = 0.0##
846
847 This gives wrong answer (0) for 0 * NaN (should be NaN):
848     "timesDouble 0.0 x"  forall x#. (*##) 0.0## x#    = 0.0##
849
850 This gives wrong answer (0) for NaN * 0 (should be NaN):
851     "timesDouble x 0.0"  forall x#. (*##) x#    0.0## = 0.0##
852
853 These are tested by num014.
854 -}
855
856 -- Wrappers for the shift operations.  The uncheckedShift# family are
857 -- undefined when the amount being shifted by is greater than the size
858 -- in bits of Int#, so these wrappers perform a check and return
859 -- either zero or -1 appropriately.
860 --
861 -- Note that these wrappers still produce undefined results when the
862 -- second argument (the shift amount) is negative.
863
864 -- | Shift the argument left by the specified number of bits
865 -- (which must be non-negative).
866 shiftL# :: Word# -> Int# -> Word#
867 a `shiftL#` b   | b >=# WORD_SIZE_IN_BITS# = int2Word# 0#
868                 | otherwise                = a `uncheckedShiftL#` b
869
870 -- | Shift the argument right by the specified number of bits
871 -- (which must be non-negative).
872 shiftRL# :: Word# -> Int# -> Word#
873 a `shiftRL#` b  | b >=# WORD_SIZE_IN_BITS# = int2Word# 0#
874                 | otherwise                = a `uncheckedShiftRL#` b
875
876 -- | Shift the argument left by the specified number of bits
877 -- (which must be non-negative).
878 iShiftL# :: Int# -> Int# -> Int#
879 a `iShiftL#` b  | b >=# WORD_SIZE_IN_BITS# = 0#
880                 | otherwise                = a `uncheckedIShiftL#` b
881
882 -- | Shift the argument right (signed) by the specified number of bits
883 -- (which must be non-negative).
884 iShiftRA# :: Int# -> Int# -> Int#
885 a `iShiftRA#` b | b >=# WORD_SIZE_IN_BITS# = if a <# 0# then (-1#) else 0#
886                 | otherwise                = a `uncheckedIShiftRA#` b
887
888 -- | Shift the argument right (unsigned) by the specified number of bits
889 -- (which must be non-negative).
890 iShiftRL# :: Int# -> Int# -> Int#
891 a `iShiftRL#` b | b >=# WORD_SIZE_IN_BITS# = 0#
892                 | otherwise                = a `uncheckedIShiftRL#` b
893
894 #if WORD_SIZE_IN_BITS == 32
895 {-# RULES
896 "narrow32Int#"  forall x#. narrow32Int#   x# = x#
897 "narrow32Word#" forall x#. narrow32Word#   x# = x#
898    #-}
899 #endif
900
901 {-# RULES
902 "int2Word2Int"  forall x#. int2Word# (word2Int# x#) = x#
903 "word2Int2Word" forall x#. word2Int# (int2Word# x#) = x#
904   #-}
905 \end{code}
906
907
908 %********************************************************
909 %*                                                      *
910 \subsection{Unpacking C strings}
911 %*                                                      *
912 %********************************************************
913
914 This code is needed for virtually all programs, since it's used for
915 unpacking the strings of error messages.
916
917 \begin{code}
918 unpackCString# :: Addr# -> [Char]
919 {-# NOINLINE [1] unpackCString# #-}
920 unpackCString# addr 
921   = unpack 0#
922   where
923     unpack nh
924       | ch `eqChar#` '\0'# = []
925       | otherwise          = C# ch : unpack (nh +# 1#)
926       where
927         ch = indexCharOffAddr# addr nh
928
929 unpackAppendCString# :: Addr# -> [Char] -> [Char]
930 unpackAppendCString# addr rest
931   = unpack 0#
932   where
933     unpack nh
934       | ch `eqChar#` '\0'# = rest
935       | otherwise          = C# ch : unpack (nh +# 1#)
936       where
937         ch = indexCharOffAddr# addr nh
938
939 unpackFoldrCString# :: Addr# -> (Char  -> a -> a) -> a -> a 
940 {-# NOINLINE [0] unpackFoldrCString# #-}
941 -- Don't inline till right at the end;
942 -- usually the unpack-list rule turns it into unpackCStringList
943 -- It also has a BuiltInRule in PrelRules.lhs:
944 --      unpackFoldrCString# "foo" c (unpackFoldrCString# "baz" c n)
945 --        =  unpackFoldrCString# "foobaz" c n
946 unpackFoldrCString# addr f z 
947   = unpack 0#
948   where
949     unpack nh
950       | ch `eqChar#` '\0'# = z
951       | otherwise          = C# ch `f` unpack (nh +# 1#)
952       where
953         ch = indexCharOffAddr# addr nh
954
955 unpackCStringUtf8# :: Addr# -> [Char]
956 unpackCStringUtf8# addr 
957   = unpack 0#
958   where
959     unpack nh
960       | ch `eqChar#` '\0'#   = []
961       | ch `leChar#` '\x7F'# = C# ch : unpack (nh +# 1#)
962       | ch `leChar#` '\xDF'# =
963           C# (chr# (((ord# ch                                  -# 0xC0#) `uncheckedIShiftL#`  6#) +#
964                      (ord# (indexCharOffAddr# addr (nh +# 1#)) -# 0x80#))) :
965           unpack (nh +# 2#)
966       | ch `leChar#` '\xEF'# =
967           C# (chr# (((ord# ch                                  -# 0xE0#) `uncheckedIShiftL#` 12#) +#
968                     ((ord# (indexCharOffAddr# addr (nh +# 1#)) -# 0x80#) `uncheckedIShiftL#`  6#) +#
969                      (ord# (indexCharOffAddr# addr (nh +# 2#)) -# 0x80#))) :
970           unpack (nh +# 3#)
971       | otherwise            =
972           C# (chr# (((ord# ch                                  -# 0xF0#) `uncheckedIShiftL#` 18#) +#
973                     ((ord# (indexCharOffAddr# addr (nh +# 1#)) -# 0x80#) `uncheckedIShiftL#` 12#) +#
974                     ((ord# (indexCharOffAddr# addr (nh +# 2#)) -# 0x80#) `uncheckedIShiftL#`  6#) +#
975                      (ord# (indexCharOffAddr# addr (nh +# 3#)) -# 0x80#))) :
976           unpack (nh +# 4#)
977       where
978         ch = indexCharOffAddr# addr nh
979
980 unpackNBytes# :: Addr# -> Int# -> [Char]
981 unpackNBytes# _addr 0#   = []
982 unpackNBytes#  addr len# = unpack [] (len# -# 1#)
983     where
984      unpack acc i#
985       | i# <# 0#  = acc
986       | otherwise = 
987          case indexCharOffAddr# addr i# of
988             ch -> unpack (C# ch : acc) (i# -# 1#)
989
990 {-# RULES
991 "unpack"       [~1] forall a   . unpackCString# a                  = build (unpackFoldrCString# a)
992 "unpack-list"  [1]  forall a   . unpackFoldrCString# a (:) [] = unpackCString# a
993 "unpack-append"     forall a n . unpackFoldrCString# a (:) n  = unpackAppendCString# a n
994
995 -- There's a built-in rule (in PrelRules.lhs) for
996 --      unpackFoldr "foo" c (unpackFoldr "baz" c n)  =  unpackFoldr "foobaz" c n
997
998   #-}
999 \end{code}
1000
1001 #ifdef __HADDOCK__
1002 \begin{code}
1003 -- | A special argument for the 'Control.Monad.ST.ST' type constructor,
1004 -- indexing a state embedded in the 'Prelude.IO' monad by
1005 -- 'Control.Monad.ST.stToIO'.
1006 data RealWorld
1007 \end{code}
1008 #endif