假设我有一张带有可测量对象的地图,我想要它们的最大宽度,默认为 0。Foldable( foldMap) 和Semigroup( Max) 的机制似乎很完美,只是我似乎无法引入任意下限。
data Thing
width :: Thing -> Double
maxWidth :: Map k Thing -> Double
maxWidth things = getMax . foldMap (Max . width) $ things
这正确地抱怨了缺少的Bounded实例Double,因为使用的Monoid实例。Max amempty = minBound
我看到源Data.Foldable使用不同的定义newtype Max来实现maximum。该变体会很好,但它似乎没有被导出:
maxWidth things = fromMaybe 0 . getMax . foldMap (Max . Just . width) $ things