I have a function in Haskell that is defined as follows:
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. 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?
CodePudding user response:
Haskell values have types. Each value has a type. One type. It can't be two different types at the same time.
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.
if
expression has a type. 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
. Then so must be y
.