gpt4 book ai didi

haskell - 将功能依赖类转换为类型族实例

转载 作者:行者123 更新时间:2023-12-02 21:30:18 24 4
gpt4 key购买 nike

是否可以从fundep类创建类型族实例?例如,假设我有这个类(class)

class A a b | a -> b

有一些实例(导入外部库)并希望为该类型系列创建所有相应的实例

type family A' a :: *

这样A' a ~ b iff A a b,而无需从外部源手动复制和修改实例。

我该怎么做(如果可能的话)?

<小时/>

迄今为止我最有希望的尝试,

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

所以,我猜答案是否定的? :/

最佳答案

别想太多

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 强制系统的顶级公理,而fundeps 基本上只影响统一。

可以在两种样式之间进行转换,但您必须使用 newtype 来绑定(bind) type 方程中的变量。

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

总的来说我don't advise编写您在问题中尝试过的通用实例,因为此类实例有重叠的趋势。

功能依赖是 less, um, weird不过,比类型家庭。在所有其他条件相同的情况下,我倾向于选择fundep。

关于haskell - 将功能依赖类转换为类型族实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43821747/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com