3

在 haskell 中,s k v ~ s1 k1 v1, where是否s :: * -> * -> *暗示k ~ k1, v ~ v1, 或s ~ s1? 如果不是,为什么不呢?

我在写一些实验代码的时候遇到了这个问题,其中一小部分是:

newtype Article = Article String
newtype ArticleId = ArticleId Int
newtype Comment = Comment String
newtype CommentId = CommentId Int

data TableName k v where
    Articles :: TableName ArticleId Article
    Comments :: TableName CommentId Comment    

data CRUD k v r where
    Create :: v -> CRUD k v k
    Read :: k -> CRUD k v (Maybe v)

data Operation t r where
    Operation :: s k v -> CRUD k v r -> Operation (s k v) r        

operatesOn :: (Eq (s k v)) => s k v -> Operation (s k v) r -> Bool
operatesOn tableName1 (Operation tableName2 _) = tableName1 == tableName2 

由于以下错误而无法编译:

Could not deduce (v1 ~ v)
from the context (Eq (s k v))
  bound by the type signature for
             operatesOn :: Eq (s k v) => s k v -> Operation (s k v) r -> Bool
or from (s k v ~ s1 k1 v1)
  bound by a pattern with constructor
             Operation :: forall r (s :: * -> * -> *) k v.
                          s k v -> CRUD k v r -> Operation (s k v) r,
           in an equation for `operatesOn'
  `v1' is a rigid type variable bound by
       a pattern with constructor
         Operation :: forall r (s :: * -> * -> *) k v.
                      s k v -> CRUD k v r -> Operation (s k v) r,
       in an equation for `operatesOn'
       at src\Example\Error.hs:44:24
  `v' is a rigid type variable bound by
      the type signature for
        operatesOn :: Eq (s k v) => s k v -> Operation (s k v) r -> Bool
      at src\Example\Error.hs:43:15
Expected type: s k v
  Actual type: s1 k1 v1
In the second argument of `(==)', namely `tableName2'
In the expression: tableName1 == tableName2
In an equation for `operatesOn':
    operatesOn tableName1 (Operation tableName2 _)
      = tableName1 == tableName2
4

1 回答 1

1

如果我将操作的定义更改为

data Operation t r where
    Operation :: (t ~ s k v) => t -> CRUD k v r -> Operation t r

operationsOn 函数将编译,类似于它为 Maybe 所做的那样

(t ~ s k v) =>约束(?)仍然会拒绝不正确的程序,例如:

doesntCompile = Operation Article $ Create $ Comment "Yo"

于 2013-08-22T05:01:52.010 回答