Overlapping instances in Haskell

前端 未结 2 1219
鱼传尺愫
鱼传尺愫 2020-12-11 16:47

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

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


        
相关标签:
2条回答
  • 2020-12-11 16:50

    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).

    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
    

    also the context of

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

    is ignored for instance selection.

    Thus GHC sees the two instances

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

    and they both match the required

    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.

    0 讨论(0)
  • 2020-12-11 16:55

    These exist

    ghci> :i ToJSON
    ...
    instance ToJSON [Char]
    ...
    instance (ToJSON a, ToJSON b) => ToJSON (a, b)
    

    So there'd be an overlap even if GHC took context into account (see Daniel Fischer's answer).

    0 讨论(0)
提交回复
热议问题