折叠一个可折叠的可能(Monoid)忽略Haskell中的缺失值

时间:2016-10-06 09:37:58

标签: haskell fold maybe monoids

我正在处理一些缺少值的数据,这些数据只是表示为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的内容,这在我的情况下不是一个选项。我有一个解决方案,涉及为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

我喜欢这个:它给了我两个函数,一个宽松的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.

2 个答案:

答案 0 :(得分:5)

有一个Monoid的实例做了正确的事情:

instance Monoid a => Monoid (Maybe a) where
  mempty = Nothing
  Nothing `mappend` m = m
  m `mappend` Nothing = m
  Just m1 `mappend` Just m2 = Just (m1 `mappend` m2)

它在Data.Monoid

因此,

foldMap (liftA Sum) [Just 1, Nothing, Just 2, Nothing, Just 3] = 
   fold [Just (Sum 1), Nothing, Just (Sum 2), Nothing, Just (Sum 3)] = 
      Just (Sum 6)

对于严格的左折叠版本,可以使用fold代替foldl' mappend mempty,而不是foldMap f使用foldl' (mappend . f) mempty。在Maybe幺半群中,memptyNothing

答案 1 :(得分:1)

如何使用Data.Maybe中的catMaybes来放弃所有Nothing值?然后,您可以在纯值的列表上运行任何聚合和计算。