【发布时间】:2022-02-21 19:48:16
【问题描述】:
给定以下数据类型
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 转换为 (,)”。我如何告诉编译器使用显而易见的方式来做到这一点?
我已经看过 this question 和答案,但我希望找到一个需要更少样板的解决方案。
【问题讨论】:
标签: haskell deriving derivingvia