如何在 Haskell 中创建具有多个参数的类型的 Foldable 实例?

How to create a Foldable instance of a type with multiple parameters in Haskell?

我有一个数据类型:

data Box a b = Box a b

我想创建一个 BoxFoldable 实例,由于必须为 Foldable 实例提供一些类似的东西 * -> *,我将声明该实例如:

instance Foldable (Box a) where
  foldr f x (Box r s) = undefined

现在我只能做类似的事情:

foldr f x (Box r s) = f s x

foldr 的定义中,但如果不是对 s 进行操作,我想做的事情如下:

foldr f x (Box r s) = f r x

编译器不允许我这样做,那么正确的方法是什么?

您已经找到了答案——只是您不喜欢它。无法按照您的要求进行操作,因为唯一可能的行为由 foldr.

的签名确定

建议使用定义了适当实例的新类型 newtype Flip t a b = Flip {unFlip :: (t b a)} 是解决此问题的最标准方法,现在您可以将折叠写在 Flip Box 而不是 Box.

您必须将实例声明为:instance Foldable Box where ... (方框 a)::*