我正在处理一些缺少值的数据,这些数据仅表示为 Maybe 值列表。我想执行各种聚合/统计操作,这些操作只是忽略缺失值。
这与以下问题有关:
Nothing
但是,如果缺少任何值,前一个问题就满足于返回,这在我的情况下不是一个选项。我有一个解决方案,其中涉及Num
为Maybe
. 但是,这意味着它特定于加法和乘法,并且它也有一些其他问题。
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
我喜欢这个:它给了我两个函数,一个 lenientsum'
和一个 strict sum''
,我可以根据需要从中选择。我可以使用相同的函数来汇总任何Num
实例,因此我可以为列表重用相同的代码,而Maybe
无需先转换它们。
我不喜欢这个:实例重叠。此外,对于除加法和乘法之外的任何操作,我必须指定一个新类型类并创建新实例。
因此,我想知道是否有可能以某种方式获得一个很好的通用解决方案,也许按照第二个问题中建议的思路,将其Nothing
视为mempty
有问题的操作。
有没有一种很好的惯用方式来做到这一点?
编辑:这是迄今为止最好的解决方案:
inout i o = ((fmap o) . getOption) . foldMap (Option . (fmap i))
sum' = Sum `inout` getSum
min' = Min `inout` getMin
-- etc.