在 Haskell 中重叠实例,因为我希望它不会由于约束而重叠 [英] Overlapping instances in Haskell when I'd expect it not to overlap due to constraints

查看:18
本文介绍了在 Haskell 中重叠实例,因为我希望它不会由于约束而重叠的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

阅读本书Real world Haskell 得到下面重叠实例的例子

Reading the book Real world Haskell geting below example of Overlapping instances

instance (JSON a) => JSON [a] where
    toJValue = undefined
    fromJValue = undefined

instance (JSON a) => JSON [(String, a)] where
    toJValue = undefined
    fromJValue = undefined

ghci> toJValue [("foo","bar")]

<interactive>:1:0:
    Overlapping instances for JSON [([Char], [Char])]
      arising from a use of `toJValue' at <interactive>:1:0-23
Matching instances:
  instance (JSON a) => JSON [a]
    -- Defined at BrokenClass.hs:(44,0)-(46,25)
  instance (JSON a) => JSON [(String, a)]
    -- Defined at BrokenClass.hs:(50,0)-(52,25)
   In the expression: toJValue [("foo", "bar")]
   In the definition of `it': it = toJValue [("foo", "bar")]

据我所知,这不会是重叠的,因为 [a] 不应该是一个选择,因为对 JSON [a] 的限制是 'a' 必须是 JSON 的一个实例本身.(String, a) 没有 JSON 实例.

By my understanding this won't be a overlapping, as [a] shouldn't be a choice, since The restriction on JSON [a] was that 'a' must be an instance itself of JSON. There is no instance of JSON for (String, a).

推荐答案

据我所知,这不会是重叠的,因为 [a] 不应该是一个选择,因为对 JSON [a] 的限制是 a 必须是 JSON 的实例本身.(String, a) 没有 JSON 的实例.

By my understanding this won't be a overlapping, as [a] shouldn't be a choice, since The restriction on JSON [a] was that a must be an instance itself of JSON. There is no instance of JSON for (String, a).

这是个误会.GHC 选择实例时只考虑实例头,对实例没有任何限制.

That's a misunderstanding. GHC does the instance selection taking only the instance head into account, and not any constraints on the instances.

instance (JSON a) => JSON [a] where

表示与选择实例的目的相同

means for the purpose of instance selection the same as

instance JSON [a] where

也是上下文

instance (JSON a) => JSON [(String, a)] where

忽略实例选择.

因此 GHC 看到了两个实例

Thus GHC sees the two instances

instance JSON [a]
instance JSON [(String, a)]

并且它们都匹配所需的

instance JSON [(String, String)]

这意味着您有重叠(无论实际存在哪些实例以及两个实例中的每一个都有哪些约束).

that means you have overlap (regardless of what instances actually exist and what constraints each of the two instances has).

如果选择了实例,则考虑约束,如果不满足,则为类型错误.

If an instance is selected, then the constraints are taken into account, and if they are not met, that is a type error.

这篇关于在 Haskell 中重叠实例,因为我希望它不会由于约束而重叠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆