Haskell中的重叠实例 [英] Overlapping instances in Haskell

查看:74
本文介绍了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

用于实例选择的方式与

instance JSON [a] where

也是

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

对于实例选择将被忽略.

is ignored for instance selection.

因此,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天全站免登陆