purescript - 如何使用实例链解决重叠
问题描述
我一直在尝试下一个 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
解决方案
即使使用实例链匹配仍然在实例的头部完成。当所选实例的任何约束失败时,没有“回溯”。
您的实例在头部完全重叠,因此您的第一个实例始终在第二个实例之前匹配,并且由于没有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
没有;-)
推荐阅读
- firebase - Cloud Firestore 的不安全安全规则
- reactjs - 当我使用 react-test-library 测试一个具有不同 prop 值的组件时,它给了我错误
- sql-server - SQL数据库中的数据库下可以创建表吗?
- google-apps-script - 使用谷歌脚本将谷歌驱动器视频插入谷歌幻灯片
- javascript - axios拦截器拦截所有axios请求
- asp.net - 如何在 Identity Server 4 保护的 webapi 中访问自定义声明?
- java - 没有虚拟方法 verifyPhoneNumber,致命异常:main
- mql4 - 为什么这个字符串函数不更新?MQL4
- java - Java 中的刽子手游戏并没有脱离循环
- python - 如何修复在赋值前引用的第 6 行封闭范围中定义的“局部变量”prev_time”错误