繁体   English   中英

GADT:是否有理由不选择最弱或最强的类型

[英]GADT's: Is there a reason why the weakest or strongest type is not chosen

我正在阅读有趣的幽灵类型 第一个练习询问为什么有必要为在幻影类型上运行的函数提供签名。 虽然我无法提出一般原因,但我确实在以下示例中看到了一个问题:

data Expr a where
  I :: Int -> Expr Int
  B :: Bool -> Expr Bool
  Add :: Expr Int -> Expr Int -> Expr Int
  Eq :: (Eq a) => Expr a -> Expr a -> Expr Bool


whatIs (I _) = "an integer expression"
whatIs (Add _ _) = "an adition operation"

现在我明白了,有两种可能的类型whatIs以上,分别是:

Expr a -> String

Expr Int -> String

但是,编译器会给出错误:

• Couldn't match expected type ‘t’ with actual type ‘[Char]’
    ‘t’ is untouchable
      inside the constraints: t1 ~ Int
      bound by a pattern with constructor: I :: Int -> Expr Int,
               in an equation for ‘whatIs’
      at ti.hs:9:9-11
  ‘t’ is a rigid type variable bound by
    the inferred type of whatIs :: Expr t1 -> t at ti.hs:9:1
  Possible fix: add a type signature for ‘whatIs’
• In the expression: "someString"
  In an equation for ‘whatIs’: whatIs (I _) = "someString"
• Relevant bindings include
    whatIs :: Expr t1 -> t (bound at ti.hs:9:1)

我想知道为什么编译器不会选择这两者中的任何一个。

对于您的示例, Expr a -> String是比Expr Int -> String更严格的类型Expr Int -> String :在任何可以使用Expr Int -> String地方, Expr a -> String肯定会这样做。 但有时候没有 “最弱”或“最强”的类型。

让我们进一步简化您的示例:

data SoSimple a where
    SoSimple :: SoSimple Int

eval SoSimple = 3 :: Int

现在这里有两个非常好的类型给eval

eval :: SoSimple a -> a
eval :: SoSimple a -> Int

这些类型不可互换! 每种都适用于不同的情况。 相比:

{-# LANGUAGE EmptyCase #-}
{-# LANGUAGE GADTs #-}
import Data.Void

data SomeSimple where
    SomeSimple :: SoSimple a -> SomeSimple

-- typechecks if eval :: SoSimple a -> Int,
--    but not if eval :: SoSimple a -> a
evalSome :: SomeSimple -> Int
evalSome (SomeSimple x) = eval x

-- typechecks if eval :: SoSimple a -> a,
--    but not if eval :: SoSimple a -> Int
evalNone :: SoSimple Void -> Void
evalNone = eval

因此,这些都不比另一个更通用(并且事实证明,没有类型比两者更通用,同时仍然让eval自己进行类型检查)。 由于eval没有最通用的类​​型,因此拒绝选择类型并迫使用户决定他们想要的许多可能类型中的哪一种是有意义的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM