-{-# OPTIONS_GHC -fno-implicit-prelude #-}
+{-# OPTIONS_GHC -XNoImplicitPrelude #-}
-----------------------------------------------------------------------------
-- |
-- Module : Data.Bits
question. -}
shift :: a -> Int -> a
- x `shift` i | i<0 = x `shiftR` (-i)
- | i==0 = x
- | i>0 = x `shiftL` i
+ x `shift` i | i<0 = x `shiftR` (-i)
+ | i>0 = x `shiftL` i
+ | otherwise = x
{-| @'rotate' x i@ rotates @x@ left by @i@ bits if @i@ is positive,
or right by @-i@ bits otherwise.
question. -}
rotate :: a -> Int -> a
- x `rotate` i | i<0 = x `rotateR` (-i)
- | i==0 = x
- | i>0 = x `rotateL` i
+ x `rotate` i | i<0 = x `rotateR` (-i)
+ | i>0 = x `rotateL` i
+ | otherwise = x
{-
-- Rotation can be implemented in terms of two shifts, but care is
| i# >=# 0# = I# (x# `iShiftL#` i#)
| otherwise = I# (x# `iShiftRA#` negateInt# i#)
- -- Important for constant folding (May 2008):
- {-# INLINE rotate #-}
+ {-# INLINE rotate #-} -- See Note [Constant folding for rotate]
(I# x#) `rotate` (I# i#) =
I# (word2Int# ((x'# `uncheckedShiftL#` i'#) `or#`
(x'# `uncheckedShiftRL#` (wsib -# i'#))))
i'# = word2Int# (int2Word# i# `and#` int2Word# (wsib -# 1#))
wsib = WORD_SIZE_IN_BITS# {- work around preprocessor problem (??) -}
bitSize _ = WORD_SIZE_IN_BITS
+
+ {-# INLINE shiftR #-}
+ -- same as the default definition, but we want it inlined (#2376)
+ x `shiftR` i = x `shift` (-i)
#else /* !__GLASGOW_HASKELL__ */
#ifdef __HUGS__
numInts = toInteger (maxBound::Int) - toInteger (minBound::Int) + 1
#endif /* !__GLASGOW_HASKELL__ */
+
+{- Note [Constant folding for rotate]
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+The INLINE on the Int instance of rotate enables it to be constant
+folded. For example:
+ sumU . mapU (`rotate` 3) . replicateU 10000000 $ (7 :: Int)
+goes to:
+ Main.$wfold =
+ \ (ww_sO7 :: Int#) (ww1_sOb :: Int#) ->
+ case ww1_sOb of wild_XM {
+ __DEFAULT -> Main.$wfold (+# ww_sO7 56) (+# wild_XM 1);
+ 10000000 -> ww_sO7
+whereas before it was left as a call to $wrotate.
+
+All other Bits instances seem to inline well enough on their
+own to enable constant folding; for example 'shift':
+ sumU . mapU (`shift` 3) . replicateU 10000000 $ (7 :: Int)
+ goes to:
+ Main.$wfold =
+ \ (ww_sOb :: Int#) (ww1_sOf :: Int#) ->
+ case ww1_sOf of wild_XM {
+ __DEFAULT -> Main.$wfold (+# ww_sOb 56) (+# wild_XM 1);
+ 10000000 -> ww_sOb
+ }
+-}
+
+