我一直在尝试下一个purescript ver 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
答案 0 :(得分:2)
即使实例链匹配仍在实例的头部完成。当任何约束对所选实例失败时,没有“回溯”。
您的实例在头部完全重叠,因此您的第一个实例始终在第二个实例之前匹配,但由于A
没有X
实例,因此它失败。
实例链允许您定义实例解析的显式排序,而不依赖于例如名称的字母顺序等(因为它已经完成,直到0.12.0版本 - please check the third paragraph here)。例如,您可以定义此重叠方案:
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
; - )