为什么在Haskell中不进行这种类型检查? [英] Why doesn't this type-check in Haskell?

查看:54
本文介绍了为什么在Haskell中不进行这种类型检查?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这不会键入检查:

module DoesntTypeCheck where {
import Prelude(Either(..));
defaultEither :: a -> Either b c -> Either a c;
defaultEither a (Left _) = Left a;
defaultEither _ b = b;
}

但是确实如此:

module DoesTypeCheck where {
import Prelude(Either(..));
defaultEither :: a -> Either b c -> Either a c;
defaultEither a (Left _) = Left a;
defaultEither _ (Right b) = Right b;
}

编译器可能有错误,任何ac 类型只能是 Left(x :: a) Right(y :: c),如果不是 Left ,则为 Right ,我们知道 Right :: b->要么是b ,要么是右(y :: c)::要么是c .

The compiler is probably buggy, an Either a c type can be only Left (x::a) or Right (y::c), if it isn't Left then it is Right, and we know that Right :: b -> Either a b so Right (y::c) :: Either a c.

推荐答案

问题是您说

defaultEither _ b = b

您是说输出值 b 与第二个输入值相同.只有这些值具有相同的类型,才有可能.但是您已经告诉编译器,输入的类型为 b c ,而输出的类型为 a c .这些是不同的类型,所以难怪编译器会抱怨.

you're saying that the output value b is the same as the second input value. And that's only possible if the values have the same type. But you've told the compiler that the input has type Either b c, while the output has type Either a c. These are different types, so no wonder the compiler complains.

我了解您要执行的操作-但是即使值 Right x (类型为 c x )正确可以是任何 d dc _ 类型,您的类型签名将输入和输出值限制为具有不同 d 的版本.这意味着您不能使用相同的变量来引用两个值.

I understand what you are trying to do - but even though a value Right x (with x of type c) on its own can be of type Either d c for any d, your type signature constrains the input and output values to versions with different ds. And that means you can't use the same variable to refer to both values.

这篇关于为什么在Haskell中不进行这种类型检查?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆