将函数依赖类转换为类型族实例 [英] Converting Functional Dependency class to Type Family instances
问题描述
是否可以从fundep类创建类型族实例?例如,假设我有一个课程
Is it possible to create type family instances from a fundep class? For example, let's say that I have the class
class A a b | a -> b
具有某些实例(导入了外部库),并且想要为类型族创建所有对应的实例
with some instances (imported an external library) and want to create all corresponding instances for the type family
type family A' a :: *
表示A' a ~ b
iff A a b
,而无需从外部源手动复制和修改实例.
such that A' a ~ b
iff A a b
, without having to manually copy and modify the instances from the external source.
如果可能的话,我该怎么办?
How would I do that (if it is possible)?
迄今为止我最有前途的尝试,
My most promising attempt so far,
class A' a where
type A'_b a :: *
instance forall a b. A a b => A' a where
type A'_b a = b
给出错误消息
The RHS of an associated type declaration mentions ‘b’
All such variables must be bound on the LHS
所以,我的猜测是答案是否定的? :/
So, my guess is that the answer is no? :/
推荐答案
不要考虑太多.
class C a b | a -> b
instance C T U
大致翻译为
class C' a where
type B a
instance C' T where
type B T = U
即使它们的行为类似,它们在语义上也有所不同. C
是一个两参数类,但是其第二个参数由其第一个唯一地确定. C'
是具有关联类型的单参数类.关联类型被解释为FC强制系统的顶级公理,而眼底基本上只影响统一.
They're semantically somewhat different, even though they behave in a similar way. C
is a two-parameter class, but its second parameter is uniquely determined by its first. C'
is a one-parameter class with an associated type. Associated types are interpreted as top-level axioms for FC's coercion system whereas fundeps basically just affect unification.
可以在两种样式之间进行转换,但是必须使用newtype
来绑定type
公式中的变量.
It is possible to convert between the two styles, but you have to use a newtype
to bind the variables in the type
equation.
newtype WrappedB a = WrappedB { unwrapB :: B a }
instance C' a => C a (WrappedB a) -- you can't use a type synonym family in an instance
newtype Wrap a b = Wrap { unWrap :: a }
instance C a b => C' (Wrap a b) where
type B (Wrap a b) = b -- b needs to be bound on the LHS of this equation
通常我不建议编写您在问题中尝试过的通用实例,因为这样实例有重叠的趋势.
In general I don't advise writing the sort of generic instance you've attempted in your question, because such instances have a tendency to be overlapping.
功能依赖项少,嗯,很奇怪而不是类型家庭.在其他所有条件都相同的情况下,我倾向于选择资助人.
Functional dependencies are less, um, weird than type families, though. All other things being equal I tend to prefer a fundep.
这篇关于将函数依赖类转换为类型族实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!