如何使用实例链解决重叠问题



我一直在尝试下一个纯脚本版本 0.12.0-rc1。
我有一个问题如何使用新功能"实例链"。
据我了解,实例链提供了一种能够明确指定实例解析顺序的功能。 这样可以避免实例定义重叠。

所以我想它可能会起作用:

class A a
class B b
class C c where
c :: c -> String
instance ca :: A a => C a where
c = const "ca"
else
instance cb :: B b => C b where
c = const "cb"
data X = X
instance bx :: B X
main :: forall eff. Eff (console :: CONSOLE | eff) Unit
main = logShow $ c X

但无法编译。

什么是不正确的? 或者实例链的使用情况是什么?

结果:

Error found:
in module Main
at src/Main.purs line 23, column 8 - line 23, column 20
No type class instance was found for
Main.A X

while applying a function c
of type C t0 => t0 -> String
to argument X
while inferring the type of c X
in value declaration main
where t0 is an unknown type

即使使用实例链,匹配仍然在实例的头部完成。当所选实例的任何约束失败时,没有"回溯"。

您的实例在头部上完全重叠,因此您的第一个实例始终在第二个实例之前匹配,并且它失败,因为没有A实例用于X

实例链允许您定义实例解析的显式顺序,而无需依赖例如名称的字母顺序等(就像在 0.12.0 版本之前所做的那样 - 请在此处查看第三段(。例如,您可以定义此重叠方案:

class IsRecord a where
isRecord :: a -> Boolean
instance a_isRecordRecord :: IsRecord (Record a) where
isRecord _ = true
instance b_isRecordOther :: IsRecord a where
isRecord _ = false

instance isRecordRecord :: IsRecord (Record a) where
isRecord _ = true
else instance isRecordOther :: IsRecord a where
isRecord _ = false

我希望它能编译 - 我还没有purs-0.12.0-rc;-(

最新更新