简体   繁体   中英

Why is my Haskell function argument required to be of type Bool?

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?

Haskell values have types. 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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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