00:19
class Monoid a where mempty :: a -- ^ Identity of 'mappend' mappend :: a -> a -> a -- ^ An associative operation mconcat :: [a] -> a -- ^ Fold a list using the monoid. -- For most types, the default definition for 'mconcat' will be -- used, but the function is included in the class definition so -- that an optimized version can be provided for specific types. mconcat = foldr mappend mempty
instance Monoid [a] where {-# INLINE mempty #-} mempty = [] {-# INLINE mappend #-} mappend = (++) {-# INLINE mconcat #-} mconcat xss = [x | xs <- xss, x <- xs]
Note: [List comprehensions and inlining]
The list monad operations are traditionally described in terms of concatMap:
The list monad operations are traditionally described in terms of concatMap:
Similarly, mconcat for lists is just concat. Here in Base, however, we don't have concatMap, and we'll refrain from adding it here so it won't have to be hidden in imports. Instead, we use GHC's list comprehension desugaring mechanism to define mconcat and the Applicative and Monad instances for lists. We mark them INLINE because the inliner is not generally too keen to inline build forms such as the ones these desugar to without our insistence.
Defining these using list comprehensions instead of foldr has an additional potential benefit, as described in compiler/deSugar/DsListComp.lhs: if optimizations needed to make foldr/build forms efficient are turned off, we'll get reasonably efficient translations anyway.
instance Monoid b => Monoid (a -> b) where mempty _ = mempty mappend f g x = f x `mappend` g x instance Monoid () where -- Should it be strict? mempty = () _ `mappend` _ = () mconcat _ = () instance (Monoid a, Monoid b) => Monoid (a,b) where mempty = (mempty, mempty) (a1,b1) `mappend` (a2,b2) = (a1 `mappend` a2, b1 `mappend` b2)
1 hour later…
02:24
10 hours later…
12:48
« first day (463 days earlier) ← previous day next day → last day (1403 days later) »