Simple type family example errors about non injective type function

前端 未结 2 845
面向向阳花
面向向阳花 2020-12-09 18:00

I\'m trying to understand type families without much success. Here\'s a minimal example:

{-# LANGUAGE TypeFamilies #-}

class Object obj where
  type Unit ob         


        
2条回答
  •  情歌与酒
    2020-12-09 18:51

    Since associated types are not injective (defined below) you need an argument in order to type check. For instance, consider the following (incorrect) code.

    class Valuable o where
      type Value o :: *
      value :: Value o
    
    data Pearl
    data Diamond
    
    instance Valuable Pearl where
      type Value Pearl = Int
      value = 1000
    
    instance Valuable Diamond where
      type Value Diamond = Int
      value = 10000
    

    Note that Value a ~ Value b does not imply a ~ b as injectivity would have it. Thus it's now ambiguous as to what the value of value is. It doesn't even help if we constrict the type of value :: Int since Value Pearl ~ Value Diamond ~ Int.


    That said, there's some very nice parallelism in the code.

    import Control.Arrow
    
    class Object obj where
      type Unit obj :: *
      unit :: obj -> Unit obj
    
    instance (Object obj, Object obj') => Object (obj, obj') where
      type Unit (obj, obj') = (Unit obj, Unit obj')
      unit = unit *** unit
    

提交回复
热议问题