给定以下数据类型
data Both a b = Both { left :: a, right :: b }
我可以像这样为 Applicative 等编写实例(在这里省略 Functor,因为我们可以使用DeriveFunctor
):
instance Monoid a => Applicative (Both a) where
pure x = Both mempty x
Both u f <*> Both v x = Both (u <> v) (f x)
由于Both
与 同构(a,b)
,我想知道是否可以使用DerivingVia
来派生实例:
data Both a b = ... deriving Applicative via ((,) a)
这会导致错误消息,例如:
• Couldn't match representation of type ‘(a, a1)’
with that of ‘Both a a1’
arising from the coercion of the method ‘pure’
from type ‘forall a1. a1 -> (a, a1)’
to type ‘forall a1. a1 -> Both a a1’
• When deriving the instance for (Applicative (Both a))
我将其解释为“编译器不知道如何Both
变成(,)
”。我如何告诉编译器使用明显的方式来做到这一点?
我已经看到了这个问题和答案,但我希望有一个需要更少样板的解决方案。