1 {-# LANGUAGE Trustworthy #-}

2 {-# LANGUAGE NoImplicitPrelude #-}

4 -----------------------------------------------------------------------------

5 -- This is a non-exposed internal module.

6 --

7 -- This code contains utility function and data structures that are used

8 -- to improve the efficiency of several instances in the Data.* namespace.

9 -----------------------------------------------------------------------------

16 -- We don't expose Max and Min because, as Edward Kmett pointed out to me,

17 -- there are two reasonable ways to define them. One way is to use Maybe, as we

18 -- do here; the other way is to impose a Bounded constraint on the Monoid

19 -- instance. We may eventually want to add both versions, but we don't want to

20 -- trample on anyone's toes by imposing Max = MaxMaybe.

25 -- | @since 4.11.0.0

27 {-# INLINE (<>) #-}

34 -- | @since 4.8.0.0

36 mempty = Max Nothing

38 -- | @since 4.11.0.0

40 {-# INLINE (<>) #-}

47 -- | @since 4.8.0.0

49 mempty = Min Nothing

51 -- left-to-right state-transforming monad

54 -- | @since 4.0

58 -- | @since 4.0

70 -- right-to-left state-transforming monad

73 -- | @since 4.0

77 -- | @since 4.0

89 -- See Note [Function coercion]

92 {-# INLINE (#.) #-}

94 {-

95 Note [Function coercion]

96 ~~~~~~~~~~~~~~~~~~~~~~~

98 Several functions here use (#.) instead of (.) to avoid potential efficiency

99 problems relating to #7542. The problem, in a nutshell:

101 If N is a newtype constructor, then N x will always have the same

102 representation as x (something similar applies for a newtype deconstructor).

103 However, if f is a function,

105 N . f = \x -> N (f x)

107 This looks almost the same as f, but the eta expansion lifts it--the lhs could

108 be _|_, but the rhs never is. This can lead to very inefficient code. Thus we

109 steal a technique from Shachaf and Edward Kmett and adapt it to the current

110 (rather clean) setting. Instead of using N . f, we use N #. f, which is

111 just

113 coerce f `asTypeOf` (N . f)

115 That is, we just *pretend* that f has the right type, and thanks to the safety

116 of coerce, the type checker guarantees that nothing really goes wrong. We still

117 have to be a bit careful, though: remember that #. completely ignores the

118 *value* of its left operand.

119 -}