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

查看:19
本文介绍了为什么不在 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;
}

编译器可能有问题,Either ac 类型只能是Left (x::a)Right (y::c),如果不是Left那么就是Right,我们知道Right :: b ->要么是 b 所以 Right (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 与第二个输入值相同.这只有在值具有相同类型时才有可能.但是你告诉编译器输入的类型是Either b c,而输出的类型是Either 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(带有 x 类型为 c)本身可以是任何 dEither 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天全站免登陆