首先一些imports
,
import Control.Applicative
import Data.Traversable as T
import Data.Foldable as F
import Data.Monoid
假设我有一个持有一对值的函子,
data Fret a = Fret a a deriving (Show)
instance Functor Fret where fmap f (Fret a b) = Fret (f a) (f b)
instance Applicative Fret where
pure a = Fret a a
Fret aa ab <*> Fret ba bb = Fret (aa ba) (ab bb)
instance Monoid a => Monoid (Fret a) where
mempty = Fret mempty mempty
a `mappend` b = mappend <$> a <*> b
我有一个很大的清单,
frets = replicate 10000000 (Fret 1 2)
我想计算一个,例如,一个平均值,
data Average a = Average !Int !a deriving (Read, Show)
instance Num a => Monoid (Average a) where
mempty = Average 0 0
Average n a `mappend` Average m b = Average (n+m) (a+b)
runAverage :: Fractional a => Average a -> a
runAverage (Average n a) = a / fromIntegral n
average = Average 1
以下是一些可能的实现,
average1 = runAverage <$> foldMap (fmap average) frets
average2 = pure (runAverage . mconcat) <*> T.sequenceA (map (pure (Average 1) <*>) frets)
不幸的是,所有这些都会导致堆栈溢出。
认为问题可能是过度懒惰Foldable.foldMap
,我尝试实施更严格的变体,
foldMap' :: (F.Foldable f, Monoid m) => (a -> m) -> f a -> m
foldMap' f = F.foldl' (\m a->mappend m $! f a) mempty
average3 = runAverage <$> foldMap' (fmap average) frets
不幸的是,这也溢出了。
如何在不损害该方法的简洁结构的情况下实现这一目标?
更新
如果我将字段Fret
设为严格,事情似乎会按预期工作。检查这是否适用于更大的应用程序。