3

I have a data type:

data Box a b = Box a b

I want to create a Foldable instance of Box and since the Foldable instance has to be given something of kind * -> *, I'll declare the instance as:

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

Now I can only do something like:

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

in the definition of foldr but what if instead of operating on s, I want to to something like:

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

The compiler doesn't let me do this so what is the proper way to go about it?

4

2 回答 2

0

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

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

于 2016-03-12T00:48:46.850 回答
0

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

于 2016-10-24T00:44:28.777 回答