【发布时间】:2016-10-06 09:37:57
【问题描述】:
我正在处理一些缺少值的数据,这些数据只是简单地表示为 Maybe 值的列表。我想执行各种聚合/统计操作,这些操作只是忽略缺失值。
这与以下问题有关:
Idiomatic way to sum a list of Maybe Int in haskell
How to use the maybe monoid and combine values with a custom operation, easily?
但是,如果缺少任何值,前一个问题满足于返回 Nothing,这在我的情况下不是一个选项。我有一个解决方案,它涉及为Maybe 创建一个Num 实例。然而,这意味着它是特定于加法和乘法的,它也有一些其他的问题。
instance Num a => Num (Maybe a) where
negate = fmap negate
(+) = liftA2 (+)
(*) = liftA2 (*)
fromInteger = pure . fromInteger
abs = fmap abs
signum = fmap signum
基于此,我们可以这样做:
maybeCombineW :: (a -> a -> a) -> Maybe a -> Maybe a -> Maybe a
maybeCombineW f (Just x) (Just y) = Just (f x y)
maybeCombineW _ (Just x) Nothing = Just x
maybeCombineW _ Nothing (Just y) = Just y
maybeCombineW _ Nothing Nothing = Nothing
maybeCombineS :: (a -> a -> a) -> Maybe a -> Maybe a -> Maybe a
maybeCombineS f (Just x) (Just y) = Just (f x y)
maybeCombineS _ _ _ = Nothing
class (Num a) => Num' a where
(+?) :: a -> a -> a
(*?) :: a -> a -> a
(+!) :: a -> a -> a
(*!) :: a -> a -> a
(+?) = (+)
(*?) = (*)
(+!) = (+)
(*!) = (*)
instance {-# OVERLAPPABLE #-} (Num a) => Num' a
instance {-# OVERLAPPING #-} (Num' a) => Num' (Maybe a) where
(+?) = maybeCombineW (+?)
(*?) = maybeCombineW (*?)
(+!) = maybeCombineS (+!)
(*!) = maybeCombineS (*!)
sum' :: (Num' b, Foldable t) => t b -> b
sum' = foldr (+?) 0
sum'' :: (Num' b, Foldable t) => t b -> b
sum'' = foldr (+!) 0
我喜欢这个:它给了我两个功能,一个宽松的sum' 和一个严格的sum'',我可以根据需要从中选择。我可以使用相同的函数对任何 Num 实例求和,因此我可以为没有 Maybe 的列表重用相同的代码,而无需先转换它们。
我不喜欢这个:实例重叠。另外,对于除加法和乘法之外的任何操作,我都必须指定一个新的类型类并创建新的实例。
因此,我想知道是否有可能获得一个不错的通用解决方案,也许与第二个问题中建议的思路一致,它将Nothing 视为mempty 用于任何有问题的操作。
有没有很好的惯用方法?
编辑:这是迄今为止最好的解决方案:
inout i o = ((fmap o) . getOption) . foldMap (Option . (fmap i))
sum' = Sum `inout` getSum
min' = Min `inout` getMin
-- etc.
【问题讨论】:
标签: haskell fold maybe monoids