Non-Injective Closed Type Family

折月煮酒 提交于 2021-01-28 04:31:39

问题


I have this admittedly contrived chunk of code

{-# LANGUAGE DataKinds, TypeFamilies #-}

data Foo = Foo

type family Id (n :: Foo) a where
    Id 'Foo a = a

data Bar (n :: Foo) = Bar

class Dispatch (n :: Foo) where
    consume :: Id n a -> Bar n -> a

consume' :: Dispatch n => Id n [Bool] -> Bar n -> [Bool]
consume' = consume

consume'' :: Dispatch n => Id n [Bool] -> Bar n -> Bool
consume'' g x = and (consume' g x)

This compiles and works fine. However, if I replace the final consume'' definition with

consume'' :: Dispatch n => Id n [Bool] -> Bar n -> Bool
consume'' g x = and (consume g x)

(Note the consume rather than consume'), then I get an error

noinject.hs:17:30: error:
    • Couldn't match expected type ‘Id n (t0 Bool)’
                  with actual type ‘Id n [Bool]’
      NB: ‘Id’ is a non-injective type family
      The type variable ‘t0’ is ambiguous
    • In the first argument of ‘consume’, namely ‘g’
      In the first argument of ‘and’, namely ‘(consume g x)’
      In the expression: and (consume g x)
    • Relevant bindings include
        x :: Bar n (bound at noinject.hs:17:13)
        g :: Id n [Bool] (bound at noinject.hs:17:11)
        consume'' :: Id n [Bool] -> Bar n -> Bool
          (bound at noinject.hs:17:1)
   |
17 | consume'' g x = and (consume g x)
   |                              ^
Failed, no modules loaded.

If we assume Id is non-injective, then the error occurs because consume could feasibly specialize to consume :: Id n (t0 Bool) -> Bar n -> t0 Bool, for some foldable t0 that isn't []. I understand that much. My question is: why is Id not actually injective. It takes two arguments: there's only one valid value for the first argument, and Id is pretty clearly injective in its second argument, so why does GHC think this is a non-injective family?


回答1:


Injective type families are a separate extension on top of type families, and you need special syntax to declare a type family as one. Injectivity does not get inferred.



来源:https://stackoverflow.com/questions/52547887/non-injective-closed-type-family

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!