首页 > 解决方案 > 如何使用实例链解决重叠

问题描述

我一直在尝试下一个 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

标签: purescript

解决方案


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

您的实例在头部完全重叠,因此您的第一个实例始终在第二个实例之前匹配,并且由于没有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没有;-)


推荐阅读