1{-# LANGUAGE BangPatterns #-}
2{-# LANGUAGE CPP #-}
3{-# LANGUAGE MagicHash #-}
4{-# LANGUAGE NoImplicitPrelude #-}
5{-# LANGUAGE StandaloneDeriving #-}
6{-# LANGUAGE Trustworthy #-}
7{-# OPTIONS_HADDOCK not-home #-}
8
9-----------------------------------------------------------------------------
10-- |
11-- Module      :  GHC.Enum
12-- Copyright   :  (c) The University of Glasgow, 1992-2002
13-- License     :  see libraries/base/LICENSE
14--
15-- Maintainer  :  cvs-ghc@haskell.org
16-- Stability   :  internal
17-- Portability :  non-portable (GHC extensions)
18--
19-- The 'Enum' and 'Bounded' classes.
20--
21-----------------------------------------------------------------------------
22
23#include "MachDeps.h"
24
25module GHC.Enum(
26        Bounded(..), Enum(..),
27        boundedEnumFrom, boundedEnumFromThen,
28        toEnumError, fromEnumError, succError, predError,
29
30        -- Instances for Bounded and Enum: (), Char, Int
31
32   ) where
33
34import GHC.Base hiding ( many )
35import GHC.Char
36import GHC.Integer
37import GHC.Num
38import GHC.Show
39default ()              -- Double isn't available yet
40
41-- | The 'Bounded' class is used to name the upper and lower limits of a
42-- type.  'Ord' is not a superclass of 'Bounded' since types that are not
43-- totally ordered may also have upper and lower bounds.
44--
45-- The 'Bounded' class may be derived for any enumeration type;
46-- 'minBound' is the first constructor listed in the @data@ declaration
47-- and 'maxBound' is the last.
48-- 'Bounded' may also be derived for single-constructor datatypes whose
49-- constituent types are in 'Bounded'.
50
51class  Bounded a  where
52    minBound, maxBound :: a
53
54-- | Class 'Enum' defines operations on sequentially ordered types.
55--
56-- The @enumFrom@... methods are used in Haskell's translation of
57-- arithmetic sequences.
58--
59-- Instances of 'Enum' may be derived for any enumeration type (types
60-- whose constructors have no fields).  The nullary constructors are
61-- assumed to be numbered left-to-right by 'fromEnum' from @0@ through @n-1@.
62-- See Chapter 10 of the /Haskell Report/ for more details.
63--
64-- For any type that is an instance of class 'Bounded' as well as 'Enum',
65-- the following should hold:
66--
67-- * The calls @'succ' 'maxBound'@ and @'pred' 'minBound'@ should result in
68--   a runtime error.
69--
70-- * 'fromEnum' and 'toEnum' should give a runtime error if the
71--   result value is not representable in the result type.
72--   For example, @'toEnum' 7 :: 'Bool'@ is an error.
73--
74-- * 'enumFrom' and 'enumFromThen' should be defined with an implicit bound,
75--   thus:
76--
77-- >    enumFrom     x   = enumFromTo     x maxBound
78-- >    enumFromThen x y = enumFromThenTo x y bound
79-- >      where
80-- >        bound | fromEnum y >= fromEnum x = maxBound
81-- >              | otherwise                = minBound
82--
83class  Enum a   where
84    -- | the successor of a value.  For numeric types, 'succ' adds 1.
85    succ                :: a -> a
86    -- | the predecessor of a value.  For numeric types, 'pred' subtracts 1.
87    pred                :: a -> a
88    -- | Convert from an 'Int'.
89    toEnum              :: Int -> a
90    -- | Convert to an 'Int'.
91    -- It is implementation-dependent what 'fromEnum' returns when
92    -- applied to a value that is too large to fit in an 'Int'.
93    fromEnum            :: a -> Int
94
95    -- | Used in Haskell's translation of @[n..]@ with @[n..] = enumFrom n@,
96    --   a possible implementation being @enumFrom n = n : enumFrom (succ n)@.
97    --   For example:
98    --
99    --     * @enumFrom 4 :: [Integer] = [4,5,6,7,...]@
100    --     * @enumFrom 6 :: [Int] = [6,7,8,9,...,maxBound :: Int]@
101    enumFrom            :: a -> [a]
102    -- | Used in Haskell's translation of @[n,n'..]@
103    --   with @[n,n'..] = enumFromThen n n'@, a possible implementation being
104    --   @enumFromThen n n' = n : n' : worker (f x) (f x n')@,
105    --   @worker s v = v : worker s (s v)@, @x = fromEnum n' - fromEnum n@ and
106    --   @f n y
107    --     | n > 0 = f (n - 1) (succ y)
108    --     | n < 0 = f (n + 1) (pred y)
109    --     | otherwise = y@
110    --   For example:
111    --
112    --     * @enumFromThen 4 6 :: [Integer] = [4,6,8,10...]@
113    --     * @enumFromThen 6 2 :: [Int] = [6,2,-2,-6,...,minBound :: Int]@
114    enumFromThen        :: a -> a -> [a]
115    -- | Used in Haskell's translation of @[n..m]@ with
116    --   @[n..m] = enumFromTo n m@, a possible implementation being
117    --   @enumFromTo n m
118    --      | n <= m = n : enumFromTo (succ n) m
119    --      | otherwise = []@.
120    --   For example:
121    --
122    --     * @enumFromTo 6 10 :: [Int] = [6,7,8,9,10]@
123    --     * @enumFromTo 42 1 :: [Integer] = []@
124    enumFromTo          :: a -> a -> [a]
125    -- | Used in Haskell's translation of @[n,n'..m]@ with
126    --   @[n,n'..m] = enumFromThenTo n n' m@, a possible implementation
127    --   being @enumFromThenTo n n' m = worker (f x) (c x) n m@,
128    --   @x = fromEnum n' - fromEnum n@, @c x = bool (>=) (<=) (x > 0)@
129    --   @f n y
130    --      | n > 0 = f (n - 1) (succ y)
131    --      | n < 0 = f (n + 1) (pred y)
132    --      | otherwise = y@ and
133    --   @worker s c v m
134    --      | c v m = v : worker s c (s v) m
135    --      | otherwise = []@
136    --   For example:
137    --
138    --     * @enumFromThenTo 4 2 -6 :: [Integer] = [4,2,0,-2,-4,-6]@
139    --     * @enumFromThenTo 6 8 2 :: [Int] = []@
140    enumFromThenTo      :: a -> a -> a -> [a]
141
142    succ                   = toEnum . (+ 1)  . fromEnum
143    pred                   = toEnum . (subtract 1) . fromEnum
144    enumFrom x             = map toEnum [fromEnum x ..]
145    enumFromThen x y       = map toEnum [fromEnum x, fromEnum y ..]
146    enumFromTo x y         = map toEnum [fromEnum x .. fromEnum y]
147    enumFromThenTo x1 x2 y = map toEnum [fromEnum x1, fromEnum x2 .. fromEnum y]
148
149-- Default methods for bounded enumerations
150boundedEnumFrom :: (Enum a, Bounded a) => a -> [a]
151boundedEnumFrom n = map toEnum [fromEnum n .. fromEnum (maxBound `asTypeOf` n)]
152
153boundedEnumFromThen :: (Enum a, Bounded a) => a -> a -> [a]
154boundedEnumFromThen n1 n2
155  | i_n2 >= i_n1  = map toEnum [i_n1, i_n2 .. fromEnum (maxBound `asTypeOf` n1)]
156  | otherwise     = map toEnum [i_n1, i_n2 .. fromEnum (minBound `asTypeOf` n1)]
157  where
158    i_n1 = fromEnum n1
159    i_n2 = fromEnum n2
160
161------------------------------------------------------------------------
162-- Helper functions
163------------------------------------------------------------------------
164
165{-# NOINLINE toEnumError #-}
166toEnumError :: (Show a) => String -> Int -> (a,a) -> b
167toEnumError inst_ty i bnds =
168    errorWithoutStackTrace $ "Enum.toEnum{" ++ inst_ty ++ "}: tag (" ++
169            show i ++
170            ") is outside of bounds " ++
171            show bnds
172
173{-# NOINLINE fromEnumError #-}
174fromEnumError :: (Show a) => String -> a -> b
175fromEnumError inst_ty x =
176    errorWithoutStackTrace $ "Enum.fromEnum{" ++ inst_ty ++ "}: value (" ++
177            show x ++
178            ") is outside of Int's bounds " ++
179            show (minBound::Int, maxBound::Int)
180
181{-# NOINLINE succError #-}
182succError :: String -> a
183succError inst_ty =
184    errorWithoutStackTrace $ "Enum.succ{" ++ inst_ty ++ "}: tried to take `succ' of maxBound"
185
186{-# NOINLINE predError #-}
187predError :: String -> a
188predError inst_ty =
189    errorWithoutStackTrace $ "Enum.pred{" ++ inst_ty ++ "}: tried to take `pred' of minBound"
190
191------------------------------------------------------------------------
192-- Tuples
193------------------------------------------------------------------------
194
195-- | @since 2.01
196deriving instance Bounded ()
197
198-- | @since 2.01
199instance Enum () where
200    succ _      = errorWithoutStackTrace "Prelude.Enum.().succ: bad argument"
201    pred _      = errorWithoutStackTrace "Prelude.Enum.().pred: bad argument"
202
203    toEnum x | x == 0    = ()
204             | otherwise = errorWithoutStackTrace "Prelude.Enum.().toEnum: bad argument"
205
206    fromEnum () = 0
207    enumFrom ()         = [()]
208    enumFromThen () ()  = let many = ():many in many
209    enumFromTo () ()    = [()]
210    enumFromThenTo () () () = let many = ():many in many
211
212-- Report requires instances up to 15
213-- | @since 2.01
214deriving instance (Bounded a, Bounded b)
215        => Bounded (a,b)
216-- | @since 2.01
217deriving instance (Bounded a, Bounded b, Bounded c)
218        => Bounded (a,b,c)
219-- | @since 2.01
220deriving instance (Bounded a, Bounded b, Bounded c, Bounded d)
221        => Bounded (a,b,c,d)
222-- | @since 2.01
223deriving instance (Bounded a, Bounded b, Bounded c, Bounded d, Bounded e)
224        => Bounded (a,b,c,d,e)
225-- | @since 2.01
226deriving instance (Bounded a, Bounded b, Bounded c, Bounded d, Bounded e,
227          Bounded f)
228        => Bounded (a,b,c,d,e,f)
229-- | @since 2.01
230deriving instance (Bounded a, Bounded b, Bounded c, Bounded d, Bounded e,
231          Bounded f, Bounded g)
232        => Bounded (a,b,c,d,e,f,g)
233-- | @since 2.01
234deriving instance (Bounded a, Bounded b, Bounded c, Bounded d, Bounded e,
235          Bounded f, Bounded g, Bounded h)
236        => Bounded (a,b,c,d,e,f,g,h)
237-- | @since 2.01
238deriving instance (Bounded a, Bounded b, Bounded c, Bounded d, Bounded e,
239          Bounded f, Bounded g, Bounded h, Bounded i)
240        => Bounded (a,b,c,d,e,f,g,h,i)
241-- | @since 2.01
242deriving instance (Bounded a, Bounded b, Bounded c, Bounded d, Bounded e,
243          Bounded f, Bounded g, Bounded h, Bounded i, Bounded j)
244        => Bounded (a,b,c,d,e,f,g,h,i,j)
245-- | @since 2.01
246deriving instance (Bounded a, Bounded b, Bounded c, Bounded d, Bounded e,
247          Bounded f, Bounded g, Bounded h, Bounded i, Bounded j, Bounded k)
248        => Bounded (a,b,c,d,e,f,g,h,i,j,k)
249-- | @since 2.01
250deriving instance (Bounded a, Bounded b, Bounded c, Bounded d, Bounded e,
251          Bounded f, Bounded g, Bounded h, Bounded i, Bounded j, Bounded k,
252          Bounded l)
253        => Bounded (a,b,c,d,e,f,g,h,i,j,k,l)
254-- | @since 2.01
255deriving instance (Bounded a, Bounded b, Bounded c, Bounded d, Bounded e,
256          Bounded f, Bounded g, Bounded h, Bounded i, Bounded j, Bounded k,
257          Bounded l, Bounded m)
258        => Bounded (a,b,c,d,e,f,g,h,i,j,k,l,m)
259-- | @since 2.01
260deriving instance (Bounded a, Bounded b, Bounded c, Bounded d, Bounded e,
261          Bounded f, Bounded g, Bounded h, Bounded i, Bounded j, Bounded k,
262          Bounded l, Bounded m, Bounded n)
263        => Bounded (a,b,c,d,e,f,g,h,i,j,k,l,m,n)
264-- | @since 2.01
265deriving instance (Bounded a, Bounded b, Bounded c, Bounded d, Bounded e,
266          Bounded f, Bounded g, Bounded h, Bounded i, Bounded j, Bounded k,
267          Bounded l, Bounded m, Bounded n, Bounded o)
268        => Bounded (a,b,c,d,e,f,g,h,i,j,k,l,m,n,o)
269
270------------------------------------------------------------------------
271-- Bool
272------------------------------------------------------------------------
273
274-- | @since 2.01
275deriving instance Bounded Bool
276
277-- | @since 2.01
278instance Enum Bool where
279  succ False = True
280  succ True  = errorWithoutStackTrace "Prelude.Enum.Bool.succ: bad argument"
281
282  pred True  = False
283  pred False  = errorWithoutStackTrace "Prelude.Enum.Bool.pred: bad argument"
284
285  toEnum n | n == 0    = False
286           | n == 1    = True
287           | otherwise = errorWithoutStackTrace "Prelude.Enum.Bool.toEnum: bad argument"
288
289  fromEnum False = 0
290  fromEnum True  = 1
291
292  -- Use defaults for the rest
293  enumFrom     = boundedEnumFrom
294  enumFromThen = boundedEnumFromThen
295
296------------------------------------------------------------------------
297-- Ordering
298------------------------------------------------------------------------
299
300-- | @since 2.01
301deriving instance Bounded Ordering
302-- | @since 2.01
303instance Enum Ordering where
304  succ LT = EQ
305  succ EQ = GT
306  succ GT = errorWithoutStackTrace "Prelude.Enum.Ordering.succ: bad argument"
307
308  pred GT = EQ
309  pred EQ = LT
310  pred LT = errorWithoutStackTrace "Prelude.Enum.Ordering.pred: bad argument"
311
312  toEnum n | n == 0 = LT
313           | n == 1 = EQ
314           | n == 2 = GT
315  toEnum _ = errorWithoutStackTrace "Prelude.Enum.Ordering.toEnum: bad argument"
316
317  fromEnum LT = 0
318  fromEnum EQ = 1
319  fromEnum GT = 2
320
321  -- Use defaults for the rest
322  enumFrom     = boundedEnumFrom
323  enumFromThen = boundedEnumFromThen
324
325------------------------------------------------------------------------
326-- Char
327------------------------------------------------------------------------
328
329-- | @since 2.01
330instance  Bounded Char  where
331    minBound =  '\0'
332    maxBound =  '\x10FFFF'
333
334-- | @since 2.01
335instance  Enum Char  where
336    succ (C# c#)
337       | isTrue# (ord# c# /=# 0x10FFFF#) = C# (chr# (ord# c# +# 1#))
338       | otherwise             = errorWithoutStackTrace ("Prelude.Enum.Char.succ: bad argument")
339    pred (C# c#)
340       | isTrue# (ord# c# /=# 0#) = C# (chr# (ord# c# -# 1#))
341       | otherwise                = errorWithoutStackTrace ("Prelude.Enum.Char.pred: bad argument")
342
343    toEnum   = chr
344    fromEnum = ord
345
346    {-# INLINE enumFrom #-}
347    enumFrom (C# x) = eftChar (ord# x) 0x10FFFF#
348        -- Blarg: technically I guess enumFrom isn't strict!
349
350    {-# INLINE enumFromTo #-}
351    enumFromTo (C# x) (C# y) = eftChar (ord# x) (ord# y)
352
353    {-# INLINE enumFromThen #-}
354    enumFromThen (C# x1) (C# x2) = efdChar (ord# x1) (ord# x2)
355
356    {-# INLINE enumFromThenTo #-}
357    enumFromThenTo (C# x1) (C# x2) (C# y) = efdtChar (ord# x1) (ord# x2) (ord# y)
358
359-- See Note [How the Enum rules work]
360{-# RULES
361"eftChar"       [~1] forall x y.        eftChar x y       = build (\c n -> eftCharFB c n x y)
362"efdChar"       [~1] forall x1 x2.      efdChar x1 x2     = build (\ c n -> efdCharFB c n x1 x2)
363"efdtChar"      [~1] forall x1 x2 l.    efdtChar x1 x2 l  = build (\ c n -> efdtCharFB c n x1 x2 l)
364"eftCharList"   [1]  eftCharFB  (:) [] = eftChar
365"efdCharList"   [1]  efdCharFB  (:) [] = efdChar
366"efdtCharList"  [1]  efdtCharFB (:) [] = efdtChar
367 #-}
368
369
370-- We can do better than for Ints because we don't
371-- have hassles about arithmetic overflow at maxBound
372{-# INLINE [0] eftCharFB #-} -- See Note [Inline FB functions] in GHC.List
373eftCharFB :: (Char -> a -> a) -> a -> Int# -> Int# -> a
374eftCharFB c n x0 y = go x0
375                 where
376                    go x | isTrue# (x ># y) = n
377                         | otherwise        = C# (chr# x) `c` go (x +# 1#)
378
379{-# NOINLINE [1] eftChar #-}
380eftChar :: Int# -> Int# -> String
381eftChar x y | isTrue# (x ># y ) = []
382            | otherwise         = C# (chr# x) : eftChar (x +# 1#) y
383
384
385-- For enumFromThenTo we give up on inlining
386{-# INLINE [0] efdCharFB #-} -- See Note [Inline FB functions] in GHC.List
387efdCharFB :: (Char -> a -> a) -> a -> Int# -> Int# -> a
388efdCharFB c n x1 x2
389  | isTrue# (delta >=# 0#) = go_up_char_fb c n x1 delta 0x10FFFF#
390  | otherwise              = go_dn_char_fb c n x1 delta 0#
391  where
392    !delta = x2 -# x1
393
394{-# NOINLINE [1] efdChar #-}
395efdChar :: Int# -> Int# -> String
396efdChar x1 x2
397  | isTrue# (delta >=# 0#) = go_up_char_list x1 delta 0x10FFFF#
398  | otherwise              = go_dn_char_list x1 delta 0#
399  where
400    !delta = x2 -# x1
401
402{-# INLINE [0] efdtCharFB #-} -- See Note [Inline FB functions] in GHC.List
403efdtCharFB :: (Char -> a -> a) -> a -> Int# -> Int# -> Int# -> a
404efdtCharFB c n x1 x2 lim
405  | isTrue# (delta >=# 0#) = go_up_char_fb c n x1 delta lim
406  | otherwise              = go_dn_char_fb c n x1 delta lim
407  where
408    !delta = x2 -# x1
409
410{-# NOINLINE [1] efdtChar #-}
411efdtChar :: Int# -> Int# -> Int# -> String
412efdtChar x1 x2 lim
413  | isTrue# (delta >=# 0#) = go_up_char_list x1 delta lim
414  | otherwise              = go_dn_char_list x1 delta lim
415  where
416    !delta = x2 -# x1
417
418go_up_char_fb :: (Char -> a -> a) -> a -> Int# -> Int# -> Int# -> a
419go_up_char_fb c n x0 delta lim
420  = go_up x0
421  where
422    go_up x | isTrue# (x ># lim) = n
423            | otherwise          = C# (chr# x) `c` go_up (x +# delta)
424
425go_dn_char_fb :: (Char -> a -> a) -> a -> Int# -> Int# -> Int# -> a
426go_dn_char_fb c n x0 delta lim
427  = go_dn x0
428  where
429    go_dn x | isTrue# (x <# lim) = n
430            | otherwise          = C# (chr# x) `c` go_dn (x +# delta)
431
432go_up_char_list :: Int# -> Int# -> Int# -> String
433go_up_char_list x0 delta lim
434  = go_up x0
435  where
436    go_up x | isTrue# (x ># lim) = []
437            | otherwise          = C# (chr# x) : go_up (x +# delta)
438
439go_dn_char_list :: Int# -> Int# -> Int# -> String
440go_dn_char_list x0 delta lim
441  = go_dn x0
442  where
443    go_dn x | isTrue# (x <# lim) = []
444            | otherwise          = C# (chr# x) : go_dn (x +# delta)
445
446
447------------------------------------------------------------------------
448-- Int
449------------------------------------------------------------------------
450
451{-
452Be careful about these instances.
453        (a) remember that you have to count down as well as up e.g. [13,12..0]
454        (b) be careful of Int overflow
455        (c) remember that Int is bounded, so [1..] terminates at maxInt
456-}
457
458-- | @since 2.01
459instance  Bounded Int where
460    minBound =  minInt
461    maxBound =  maxInt
462
463-- | @since 2.01
464instance  Enum Int  where
465    succ x
466       | x == maxBound  = errorWithoutStackTrace "Prelude.Enum.succ{Int}: tried to take `succ' of maxBound"
467       | otherwise      = x + 1
468    pred x
469       | x == minBound  = errorWithoutStackTrace "Prelude.Enum.pred{Int}: tried to take `pred' of minBound"
470       | otherwise      = x - 1
471
472    toEnum   x = x
473    fromEnum x = x
474
475    {-# INLINE enumFrom #-}
476    enumFrom (I# x) = eftInt x maxInt#
477        where !(I# maxInt#) = maxInt
478        -- Blarg: technically I guess enumFrom isn't strict!
479
480    {-# INLINE enumFromTo #-}
481    enumFromTo (I# x) (I# y) = eftInt x y
482
483    {-# INLINE enumFromThen #-}
484    enumFromThen (I# x1) (I# x2) = efdInt x1 x2
485
486    {-# INLINE enumFromThenTo #-}
487    enumFromThenTo (I# x1) (I# x2) (I# y) = efdtInt x1 x2 y
488
489
490-----------------------------------------------------
491-- eftInt and eftIntFB deal with [a..b], which is the
492-- most common form, so we take a lot of care
493-- In particular, we have rules for deforestation
494
495{-# RULES
496"eftInt"        [~1] forall x y. eftInt x y = build (\ c n -> eftIntFB c n x y)
497"eftIntList"    [1] eftIntFB  (:) [] = eftInt
498 #-}
499
500{- Note [How the Enum rules work]
501~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
502* Phase 2: eftInt ---> build . eftIntFB
503* Phase 1: inline build; eftIntFB (:) --> eftInt
504* Phase 0: optionally inline eftInt
505-}
506
507{-# NOINLINE [1] eftInt #-}
508eftInt :: Int# -> Int# -> [Int]
509-- [x1..x2]
510eftInt x0 y | isTrue# (x0 ># y) = []
511            | otherwise         = go x0
512               where
513                 go x = I# x : if isTrue# (x ==# y)
514                               then []
515                               else go (x +# 1#)
516
517{-# INLINE [0] eftIntFB #-} -- See Note [Inline FB functions] in GHC.List
518eftIntFB :: (Int -> r -> r) -> r -> Int# -> Int# -> r
519eftIntFB c n x0 y | isTrue# (x0 ># y) = n
520                  | otherwise         = go x0
521                 where
522                   go x = I# x `c` if isTrue# (x ==# y)
523                                   then n
524                                   else go (x +# 1#)
525                        -- Watch out for y=maxBound; hence ==, not >
526        -- Be very careful not to have more than one "c"
527        -- so that when eftInfFB is inlined we can inline
528        -- whatever is bound to "c"
529
530
531-----------------------------------------------------
532-- efdInt and efdtInt deal with [a,b..] and [a,b..c].
533-- The code is more complicated because of worries about Int overflow.
534
535-- See Note [How the Enum rules work]
536{-# RULES
537"efdtInt"       [~1] forall x1 x2 y.
538                     efdtInt x1 x2 y = build (\ c n -> efdtIntFB c n x1 x2 y)
539"efdtIntUpList" [1]  efdtIntFB (:) [] = efdtInt
540 #-}
541
542efdInt :: Int# -> Int# -> [Int]
543-- [x1,x2..maxInt]
544efdInt x1 x2
545 | isTrue# (x2 >=# x1) = case maxInt of I# y -> efdtIntUp x1 x2 y
546 | otherwise           = case minInt of I# y -> efdtIntDn x1 x2 y
547
548{-# NOINLINE [1] efdtInt #-}
549efdtInt :: Int# -> Int# -> Int# -> [Int]
550-- [x1,x2..y]
551efdtInt x1 x2 y
552 | isTrue# (x2 >=# x1) = efdtIntUp x1 x2 y
553 | otherwise           = efdtIntDn x1 x2 y
554
555{-# INLINE [0] efdtIntFB #-} -- See Note [Inline FB functions] in GHC.List
556efdtIntFB :: (Int -> r -> r) -> r -> Int# -> Int# -> Int# -> r
557efdtIntFB c n x1 x2 y
558 | isTrue# (x2 >=# x1) = efdtIntUpFB c n x1 x2 y
559 | otherwise           = efdtIntDnFB c n x1 x2 y
560
561-- Requires x2 >= x1
562efdtIntUp :: Int# -> Int# -> Int# -> [Int]
563efdtIntUp x1 x2 y    -- Be careful about overflow!
564 | isTrue# (y <# x2) = if isTrue# (y <# x1) then [] else [I# x1]
565 | otherwise = -- Common case: x1 <= x2 <= y
566               let !delta = x2 -# x1 -- >= 0
567                   !y' = y -# delta  -- x1 <= y' <= y; hence y' is representable
568
569                   -- Invariant: x <= y
570                   -- Note that: z <= y' => z + delta won't overflow
571                   -- so we are guaranteed not to overflow if/when we recurse
572                   go_up x | isTrue# (x ># y') = [I# x]
573                           | otherwise         = I# x : go_up (x +# delta)
574               in I# x1 : go_up x2
575
576-- Requires x2 >= x1
577{-# INLINE [0] efdtIntUpFB #-} -- See Note [Inline FB functions] in GHC.List
578efdtIntUpFB :: (Int -> r -> r) -> r -> Int# -> Int# -> Int# -> r
579efdtIntUpFB c n x1 x2 y    -- Be careful about overflow!
580 | isTrue# (y <# x2) = if isTrue# (y <# x1) then n else I# x1 `c` n
581 | otherwise = -- Common case: x1 <= x2 <= y
582               let !delta = x2 -# x1 -- >= 0
583                   !y' = y -# delta  -- x1 <= y' <= y; hence y' is representable
584
585                   -- Invariant: x <= y
586                   -- Note that: z <= y' => z + delta won't overflow
587                   -- so we are guaranteed not to overflow if/when we recurse
588                   go_up x | isTrue# (x ># y') = I# x `c` n
589                           | otherwise         = I# x `c` go_up (x +# delta)
590               in I# x1 `c` go_up x2
591
592-- Requires x2 <= x1
593efdtIntDn :: Int# -> Int# -> Int# -> [Int]
594efdtIntDn x1 x2 y    -- Be careful about underflow!
595 | isTrue# (y ># x2) = if isTrue# (y ># x1) then [] else [I# x1]
596 | otherwise = -- Common case: x1 >= x2 >= y
597               let !delta = x2 -# x1 -- <= 0
598                   !y' = y -# delta  -- y <= y' <= x1; hence y' is representable
599
600                   -- Invariant: x >= y
601                   -- Note that: z >= y' => z + delta won't underflow
602                   -- so we are guaranteed not to underflow if/when we recurse
603                   go_dn x | isTrue# (x <# y') = [I# x]
604                           | otherwise         = I# x : go_dn (x +# delta)
605   in I# x1 : go_dn x2
606
607-- Requires x2 <= x1
608{-# INLINE [0] efdtIntDnFB #-} -- See Note [Inline FB functions] in GHC.List
609efdtIntDnFB :: (Int -> r -> r) -> r -> Int# -> Int# -> Int# -> r
610efdtIntDnFB c n x1 x2 y    -- Be careful about underflow!
611 | isTrue# (y ># x2) = if isTrue# (y ># x1) then n else I# x1 `c` n
612 | otherwise = -- Common case: x1 >= x2 >= y
613               let !delta = x2 -# x1 -- <= 0
614                   !y' = y -# delta  -- y <= y' <= x1; hence y' is representable
615
616                   -- Invariant: x >= y
617                   -- Note that: z >= y' => z + delta won't underflow
618                   -- so we are guaranteed not to underflow if/when we recurse
619                   go_dn x | isTrue# (x <# y') = I# x `c` n
620                           | otherwise         = I# x `c` go_dn (x +# delta)
621               in I# x1 `c` go_dn x2
622
623
624------------------------------------------------------------------------
625-- Word
626------------------------------------------------------------------------
627
628-- | @since 2.01
629instance Bounded Word where
630    minBound = 0
631
632    -- use unboxed literals for maxBound, because GHC doesn't optimise
633    -- (fromInteger 0xffffffff :: Word).
634#if WORD_SIZE_IN_BITS == 32
635    maxBound = W# 0xFFFFFFFF##
636#elif WORD_SIZE_IN_BITS == 64
637    maxBound = W# 0xFFFFFFFFFFFFFFFF##
638#else
639#error Unhandled value for WORD_SIZE_IN_BITS
640#endif
641
642-- | @since 2.01
643instance Enum Word where
644    succ x
645        | x /= maxBound = x + 1
646        | otherwise     = succError "Word"
647    pred x
648        | x /= minBound = x - 1
649        | otherwise     = predError "Word"
650    toEnum i@(I# i#)
651        | i >= 0        = W# (int2Word# i#)
652        | otherwise     = toEnumError "Word" i (minBound::Word, maxBound::Word)
653    fromEnum x@(W# x#)
654        | x <= maxIntWord = I# (word2Int# x#)
655        | otherwise       = fromEnumError "Word" x
656
657    {-# INLINE enumFrom #-}
658    enumFrom (W# x#)      = eftWord x# maxWord#
659        where !(W# maxWord#) = maxBound
660        -- Blarg: technically I guess enumFrom isn't strict!
661
662    {-# INLINE enumFromTo #-}
663    enumFromTo (W# x) (W# y) = eftWord x y
664
665    {-# INLINE enumFromThen #-}
666    enumFromThen (W# x1) (W# x2) = efdWord x1 x2
667
668    {-# INLINE enumFromThenTo #-}
669    enumFromThenTo (W# x1) (W# x2) (W# y) = efdtWord x1 x2 y
670
671maxIntWord :: Word
672-- The biggest word representable as an Int
673maxIntWord = W# (case maxInt of I# i -> int2Word# i)
674
675-----------------------------------------------------
676-- eftWord and eftWordFB deal with [a..b], which is the
677-- most common form, so we take a lot of care
678-- In particular, we have rules for deforestation
679
680{-# RULES
681"eftWord"        [~1] forall x y. eftWord x y = build (\ c n -> eftWordFB c n x y)
682"eftWordList"    [1] eftWordFB  (:) [] = eftWord
683 #-}
684
685-- The Enum rules for Word work much the same way that they do for Int.
686-- See Note [How the Enum rules work].
687
688{-# NOINLINE [1] eftWord #-}
689eftWord :: Word# -> Word# -> [Word]
690-- [x1..x2]
691eftWord x0 y | isTrue# (x0 `gtWord#` y) = []
692             | otherwise                = go x0
693                where
694                  go x = W# x : if isTrue# (x `eqWord#` y)
695                                then []
696                                else go (x `plusWord#` 1##)
697
698{-# INLINE [0] eftWordFB #-} -- See Note [Inline FB functions] in GHC.List
699eftWordFB :: (Word -> r -> r) -> r -> Word# -> Word# -> r
700eftWordFB c n x0 y | isTrue# (x0 `gtWord#` y) = n
701                   | otherwise                = go x0
702                  where
703                    go x = W# x `c` if isTrue# (x `eqWord#` y)
704                                    then n
705                                    else go (x `plusWord#` 1##)
706                        -- Watch out for y=maxBound; hence ==, not >
707        -- Be very careful not to have more than one "c"
708        -- so that when eftInfFB is inlined we can inline
709        -- whatever is bound to "c"
710
711
712-----------------------------------------------------
713-- efdWord and efdtWord deal with [a,b..] and [a,b..c].
714-- The code is more complicated because of worries about Word overflow.
715
716-- See Note [How the Enum rules work]
717{-# RULES
718"efdtWord"       [~1] forall x1 x2 y.
719                     efdtWord x1 x2 y = build (\ c n -> efdtWordFB c n x1 x2 y)
720"efdtWordUpList" [1]  efdtWordFB (:) [] = efdtWord
721 #-}
722
723efdWord :: Word# -> Word# -> [Word]
724-- [x1,x2..maxWord]
725efdWord x1 x2
726 | isTrue# (x2 `geWord#` x1) = case maxBound of W# y -> efdtWordUp x1 x2 y
727 | otherwise                 = case minBound of W# y -> efdtWordDn x1 x2 y
728
729{-# NOINLINE [1] efdtWord #-}
730efdtWord :: Word# -> Word# -> Word# -> [Word]
731-- [x1,x2..y]
732efdtWord x1 x2 y
733 | isTrue# (x2 `geWord#` x1) = efdtWordUp x1 x2 y
734 | otherwise                 = efdtWordDn x1 x2 y
735
736{-# INLINE [0] efdtWordFB #-} -- See Note [Inline FB functions] in GHC.List
737efdtWordFB :: (Word -> r -> r) -> r -> Word# -> Word# -> Word# -> r
738efdtWordFB c n x1 x2 y
739 | isTrue# (x2 `geWord#` x1) = efdtWordUpFB c n x1 x2 y
740 | otherwise                 = efdtWordDnFB c n x1 x2 y
741
742-- Requires x2 >= x1
743efdtWordUp :: Word# -> Word# -> Word# -> [Word]
744efdtWordUp x1 x2 y    -- Be careful about overflow!
745 | isTrue# (y `ltWord#` x2) = if isTrue# (y `ltWord#` x1) then [] else [W# x1]
746 | otherwise = -- Common case: x1 <= x2 <= y
747               let !delta = x2 `minusWord#` x1 -- >= 0
748                   !y' = y `minusWord#` delta  -- x1 <= y' <= y; hence y' is representable
749
750                   -- Invariant: x <= y
751                   -- Note that: z <= y' => z + delta won't overflow
752                   -- so we are guaranteed not to overflow if/when we recurse
753                   go_up x | isTrue# (x `gtWord#` y') = [W# x]
754                           | otherwise                = W# x : go_up (x `plusWord#` delta)
755               in W# x1 : go_up x2
756
757-- Requires x2 >= x1
758{-# INLINE [0] efdtWordUpFB #-} -- See Note [Inline FB functions] in GHC.List
759efdtWordUpFB :: (Word -> r -> r) -> r -> Word# -> Word# -> Word# -> r
760efdtWordUpFB c n x1 x2 y    -- Be careful about overflow!
761 | isTrue# (y `ltWord#` x2) = if isTrue# (y `ltWord#` x1) then n else W# x1 `c` n
762 | otherwise = -- Common case: x1 <= x2 <= y
763               let !delta = x2 `minusWord#` x1 -- >= 0
764                   !y' = y `minusWord#` delta  -- x1 <= y' <= y; hence y' is representable
765
766                   -- Invariant: x <= y
767                   -- Note that: z <= y' => z + delta won't overflow
768                   -- so we are guaranteed not to overflow if/when we recurse
769                   go_up x | isTrue# (x `gtWord#` y') = W# x `c` n
770                           | otherwise                = W# x `c` go_up (x `plusWord#` delta)
771               in W# x1 `c` go_up x2
772
773-- Requires x2 <= x1
774efdtWordDn :: Word# -> Word# -> Word# -> [Word]
775efdtWordDn x1 x2 y    -- Be careful about underflow!
776 | isTrue# (y `gtWord#` x2) = if isTrue# (y `gtWord#` x1) then [] else [W# x1]
777 | otherwise = -- Common case: x1 >= x2 >= y
778               let !delta = x2 `minusWord#` x1 -- <= 0
779                   !y' = y `minusWord#` delta  -- y <= y' <= x1; hence y' is representable
780
781                   -- Invariant: x >= y
782                   -- Note that: z >= y' => z + delta won't underflow
783                   -- so we are guaranteed not to underflow if/when we recurse
784                   go_dn x | isTrue# (x `ltWord#` y') = [W# x]
785                           | otherwise                = W# x : go_dn (x `plusWord#` delta)
786   in W# x1 : go_dn x2
787
788-- Requires x2 <= x1
789{-# INLINE [0] efdtWordDnFB #-} -- See Note [Inline FB functions] in GHC.List
790efdtWordDnFB :: (Word -> r -> r) -> r -> Word# -> Word# -> Word# -> r
791efdtWordDnFB c n x1 x2 y    -- Be careful about underflow!
792 | isTrue# (y `gtWord#` x2) = if isTrue# (y `gtWord#` x1) then n else W# x1 `c` n
793 | otherwise = -- Common case: x1 >= x2 >= y
794               let !delta = x2 `minusWord#` x1 -- <= 0
795                   !y' = y `minusWord#` delta  -- y <= y' <= x1; hence y' is representable
796
797                   -- Invariant: x >= y
798                   -- Note that: z >= y' => z + delta won't underflow
799                   -- so we are guaranteed not to underflow if/when we recurse
800                   go_dn x | isTrue# (x `ltWord#` y') = W# x `c` n
801                           | otherwise                = W# x `c` go_dn (x `plusWord#` delta)
802               in W# x1 `c` go_dn x2
803
804------------------------------------------------------------------------
805-- Integer
806------------------------------------------------------------------------
807
808-- | @since 2.01
809instance  Enum Integer  where
810    succ x               = x + 1
811    pred x               = x - 1
812    toEnum (I# n)        = smallInteger n
813    fromEnum n           = I# (integerToInt n)
814
815    {-# INLINE enumFrom #-}
816    {-# INLINE enumFromThen #-}
817    {-# INLINE enumFromTo #-}
818    {-# INLINE enumFromThenTo #-}
819    enumFrom x             = enumDeltaInteger   x 1
820    enumFromThen x y       = enumDeltaInteger   x (y-x)
821    enumFromTo x lim       = enumDeltaToInteger x 1     lim
822    enumFromThenTo x y lim = enumDeltaToInteger x (y-x) lim
823
824-- See Note [How the Enum rules work]
825{-# RULES
826"enumDeltaInteger"      [~1] forall x y.   enumDeltaInteger x y         = build (\c _ -> enumDeltaIntegerFB c x y)
827"efdtInteger"           [~1] forall x d l. enumDeltaToInteger x d l     = build (\c n -> enumDeltaToIntegerFB  c n x d l)
828"efdtInteger1"          [~1] forall x l.   enumDeltaToInteger x 1 l     = build (\c n -> enumDeltaToInteger1FB c n x l)
829
830"enumDeltaToInteger1FB" [1] forall c n x.  enumDeltaToIntegerFB c n x 1 = enumDeltaToInteger1FB c n x
831
832"enumDeltaInteger"      [1] enumDeltaIntegerFB    (:)     = enumDeltaInteger
833"enumDeltaToInteger"    [1] enumDeltaToIntegerFB  (:) []  = enumDeltaToInteger
834"enumDeltaToInteger1"   [1] enumDeltaToInteger1FB (:) []  = enumDeltaToInteger1
835 #-}
836
837{- Note [Enum Integer rules for literal 1]
838The "1" rules above specialise for the common case where delta = 1,
839so that we can avoid the delta>=0 test in enumDeltaToIntegerFB.
840Then enumDeltaToInteger1FB is nice and small and can be inlined,
841which would allow the constructor to be inlined and good things to happen.
842
843We match on the literal "1" both in phase 2 (rule "efdtInteger1") and
844phase 1 (rule "enumDeltaToInteger1FB"), just for belt and braces
845
846We do not do it for Int this way because hand-tuned code already exists, and
847the special case varies more from the general case, due to the issue of overflows.
848-}
849
850{-# INLINE [0] enumDeltaIntegerFB #-}
851-- See Note [Inline FB functions] in GHC.List
852enumDeltaIntegerFB :: (Integer -> b -> b) -> Integer -> Integer -> b
853enumDeltaIntegerFB c x0 d = go x0
854  where go x = x `seq` (x `c` go (x+d))
855
856{-# NOINLINE [1] enumDeltaInteger #-}
857enumDeltaInteger :: Integer -> Integer -> [Integer]
858enumDeltaInteger x d = x `seq` (x : enumDeltaInteger (x+d) d)
859-- strict accumulator, so
860--     head (drop 1000000 [1 .. ]
861-- works
862
863{-# INLINE [0] enumDeltaToIntegerFB #-}
864-- See Note [Inline FB functions] in GHC.List
865-- Don't inline this until RULE "enumDeltaToInteger" has had a chance to fire
866enumDeltaToIntegerFB :: (Integer -> a -> a) -> a
867                     -> Integer -> Integer -> Integer -> a
868enumDeltaToIntegerFB c n x delta lim
869  | delta >= 0 = up_fb c n x delta lim
870  | otherwise  = dn_fb c n x delta lim
871
872{-# INLINE [0] enumDeltaToInteger1FB #-}
873-- See Note [Inline FB functions] in GHC.List
874-- Don't inline this until RULE "enumDeltaToInteger" has had a chance to fire
875enumDeltaToInteger1FB :: (Integer -> a -> a) -> a
876                      -> Integer -> Integer -> a
877enumDeltaToInteger1FB c n x0 lim = go (x0 :: Integer)
878                      where
879                        go x | x > lim   = n
880                             | otherwise = x `c` go (x+1)
881
882{-# NOINLINE [1] enumDeltaToInteger #-}
883enumDeltaToInteger :: Integer -> Integer -> Integer -> [Integer]
884enumDeltaToInteger x delta lim
885  | delta >= 0 = up_list x delta lim
886  | otherwise  = dn_list x delta lim
887
888{-# NOINLINE [1] enumDeltaToInteger1 #-}
889enumDeltaToInteger1 :: Integer -> Integer -> [Integer]
890-- Special case for Delta = 1
891enumDeltaToInteger1 x0 lim = go (x0 :: Integer)
892                      where
893                        go x | x > lim   = []
894                             | otherwise = x : go (x+1)
895
896up_fb :: (Integer -> a -> a) -> a -> Integer -> Integer -> Integer -> a
897up_fb c n x0 delta lim = go (x0 :: Integer)
898                      where
899                        go x | x > lim   = n
900                             | otherwise = x `c` go (x+delta)
901dn_fb :: (Integer -> a -> a) -> a -> Integer -> Integer -> Integer -> a
902dn_fb c n x0 delta lim = go (x0 :: Integer)
903                      where
904                        go x | x < lim   = n
905                             | otherwise = x `c` go (x+delta)
906
907up_list :: Integer -> Integer -> Integer -> [Integer]
908up_list x0 delta lim = go (x0 :: Integer)
909                    where
910                        go x | x > lim   = []
911                             | otherwise = x : go (x+delta)
912dn_list :: Integer -> Integer -> Integer -> [Integer]
913dn_list x0 delta lim = go (x0 :: Integer)
914                    where
915                        go x | x < lim   = []
916                             | otherwise = x : go (x+delta)
917
918------------------------------------------------------------------------
919-- Natural
920------------------------------------------------------------------------
921
922-- | @since 4.8.0.0
923instance Enum Natural where
924    succ n = n `plusNatural`  wordToNaturalBase 1##
925    pred n = n `minusNatural` wordToNaturalBase 1##
926
927    toEnum = intToNatural
928
929#if defined(MIN_VERSION_integer_gmp)
930    fromEnum (NatS# w)
931      | i >= 0    = i
932      | otherwise = errorWithoutStackTrace "fromEnum: out of Int range"
933      where
934        i = I# (word2Int# w)
935#endif
936    fromEnum n = fromEnum (naturalToInteger n)
937
938    enumFrom x        = enumDeltaNatural      x (wordToNaturalBase 1##)
939    enumFromThen x y
940      | x <= y        = enumDeltaNatural      x (y-x)
941      | otherwise     = enumNegDeltaToNatural x (x-y) (wordToNaturalBase 0##)
942
943    enumFromTo x lim  = enumDeltaToNatural    x (wordToNaturalBase 1##) lim
944    enumFromThenTo x y lim
945      | x <= y        = enumDeltaToNatural    x (y-x) lim
946      | otherwise     = enumNegDeltaToNatural x (x-y) lim
947
948-- Helpers for 'Enum Natural'; TODO: optimise & make fusion work
949
950enumDeltaNatural :: Natural -> Natural -> [Natural]
951enumDeltaNatural !x d = x : enumDeltaNatural (x+d) d
952
953enumDeltaToNatural :: Natural -> Natural -> Natural -> [Natural]
954enumDeltaToNatural x0 delta lim = go x0
955  where
956    go x | x > lim   = []
957         | otherwise = x : go (x+delta)
958
959enumNegDeltaToNatural :: Natural -> Natural -> Natural -> [Natural]
960enumNegDeltaToNatural x0 ndelta lim = go x0
961  where
962    go x | x < lim     = []
963         | x >= ndelta = x : go (x-ndelta)
964         | otherwise   = [x]
965
966
967-- Instances from GHC.Types
968
969-- | @since 4.10.0.0
970deriving instance Bounded VecCount
971-- | @since 4.10.0.0
972deriving instance Enum VecCount
973
974-- | @since 4.10.0.0
975deriving instance Bounded VecElem
976-- | @since 4.10.0.0
977deriving instance Enum VecElem
978