为什么Eq(GADT)案例给我一个类型错误?

时间:2017-01-17 14:43:04

标签: haskell gadt

{-# LANGUAGE GADTs #-}

module Main where

data CudaExpr x where
  C :: x -> CudaExpr x

  Add :: Num x => CudaExpr x -> CudaExpr x -> CudaExpr x
  Sub :: Num x => CudaExpr x -> CudaExpr x -> CudaExpr x
  Mul :: Num x => CudaExpr x -> CudaExpr x -> CudaExpr x
  Div :: (Num x, Fractional x) => CudaExpr x -> CudaExpr x -> CudaExpr x

  Eq :: (Eq x) => CudaExpr x -> CudaExpr x -> CudaExpr Bool
  -- LessThan :: CudaExpr x -> CudaExpr x -> CudaExpr Bool
  -- If :: CudaExpr Bool -> CudaExpr x -> CudaExpr x -> CudaExpr x

eval (C x) = x
eval (Add a b) = eval a + eval b
eval (Sub a b) = eval a - eval b
eval (Mul a b) = eval a * eval b
eval (Div a b) = eval a / eval b

eval (Eq a b) = eval a == eval b
-- eval (LessThan a b) = eval a < eval b
-- eval (If cond true false) = if eval cond then eval true else eval false


main :: IO ()
main = print "Hello"

它似乎不是单形态限制。这是我得到的错误:

* Could not deduce: x ~ Bool
  from the context: (t ~ Bool, Eq x)
    bound by a pattern with constructor:
               Eq :: forall x. Eq x => CudaExpr x -> CudaExpr x -> CudaExpr Bool,
             in an equation for `eval'
    at app\Main.hs:23:7-12
  `x' is a rigid type variable bound by
    a pattern with constructor:
      Eq :: forall x. Eq x => CudaExpr x -> CudaExpr x -> CudaExpr Bool,
    in an equation for `eval'
    at app\Main.hs:23:7
  Expected type: CudaExpr x -> Bool
    Actual type: CudaExpr t -> t
* In the first argument of `(==)', namely `eval a'
  In the expression: eval a == eval b
  In an equation for `eval': eval (Eq a b) = eval a == eval b
* Relevant bindings include
    b :: CudaExpr x (bound at app\Main.hs:23:12)
    a :: CudaExpr x (bound at app\Main.hs:23:10)

1 个答案:

答案 0 :(得分:7)

来自GHC docs

  

一般原则是:类型细化仅基于用户提供的类型注释执行。因此,如果没有为eval提供类型签名,则不会进行任何类型细化,并且会发生许多模糊的错误消息。

换句话说,当我们在GADT类型上进行模式匹配时(通过多个方程或使用case),提供显式类型注释是必要的。

作为思想实验考虑

data T a where C :: Char -> T Char

f (C c) = c

什么是正确的打字?

f :: T a    -> a
f :: T a    -> Char
f :: T Char -> Char

最后一个更具体,前两个更严格一般。然而,前两个中没有一个比另一个更通用 - GHC不能选择“最佳”。

GADT在这方面并不特别。大多数高级功能需要类型注释:GADT,更高级别的类型,至少类型系列。