简体   繁体   English

是否有错误折叠的类型类?

[英]Is there a type class for fallible fold?

Let's say T is a type that is an instance of Foldable .假设T是一个类型,它是Foldable一个实例。 If I need to perform a fold that can fail, I can use foldM with a function that returns a Maybe .如果我需要执行可能失败的折叠,我可以将foldM与返回Maybe的函数一起使用。

But, what if the fallibility of the fold is inherent to T itself?但是,如果折叠的易错性是T本身固有的呢? Is there a type class for this?是否有一个类型类? In other words, is there a type class for types that can be folded, but where fold cannot be defined for all values?换句话说,是否有可以折叠的类型的类型类,但不能为所有值定义 fold ?

Can this be generalized to other Monads (or other type constructors) other than Maybe ?这可以推广到除Maybe之外的其他 Monads(或其他类型构造函数)吗?

Update更新

I'm looking for something like this:我正在寻找这样的东西:

{-# LANGUAGE TypeFamilies #-}
class FoldableT t where
    type F t :: * -> *
    foldMap  :: Monoid m => (a -> m) -> t a -> F t m 

Then Foldable would just be a special case of FoldableT where F is Identity.然后Foldable也只是一个特例FoldableT其中F是身份。

One possibility you may not have considered is to wrap the non-foldable type with something that is trivially foldable:您可能没有考虑过的一种可能性是用可简单折叠的东西包裹不可折叠类型:

newtype Trivial a = Trivial a
    deriving (Functor)
instance Foldable Trivial where
    foldMap _ _ = mempty

Then you can derive Foldable on the whole type and it will make the non-foldable branch appear empty.然后你可以在整个类型上派生Foldable ,它会使不可折叠的分支显示为空。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM