[英]Why is my Haskell function argument required to be of type Bool?
I have a function in Haskell that is defined as follows:我在 Haskell 中有一个 function ,定义如下:
f2 x y = if x then x else y
When trying to determine the type of y
, I would assume it could be of any valid Haskell type, since it is not required for evaluating the if-part.在尝试确定
y
的类型时,我会假设它可以是任何有效的 Haskell 类型,因为评估 if 部分不需要它。 However, checking the type signature with但是,检查类型签名
:type f2
yields产量
f2 :: Bool -> Bool -> Bool
Why does the y
argument need to be of type Bool
in this case?在这种情况下,为什么
y
参数需要是Bool
类型?
Haskell values have types. Haskell 值具有类型。 Each value has a type.
每个值都有一个类型。 One type.
一种。 It can't be two different types at the same type.
它不能是同一类型中的两种不同类型。
Thus, since x
is returned as the result of if
's consequent, the type of the whole if... then... else...
expression is the same as x
's type.因此,由于
x
作为if
的结果返回,所以整个if... then... else...
表达式的类型与x
的类型相同。
if
expression has a type. if
表达式有类型。 Thus both its consequent and alternative expression must have that same type, since either of them can be returned, depending on the value of the test.因此,它的结果表达式和替代表达式都必须具有相同的类型,因为它们中的任何一个都可以返回,具体取决于测试的值。 Thus both must have the same type.
因此,两者必须具有相同的类型。
Since x
is also used in the test, it must be Bool
.由于
x
也用于测试,它必须是Bool
。 Then so must be y
.那么
y
也必须如此。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.