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?
The basic way to get arguments in a Haskell program is provided by the System.Environment library. We can use the getArgs function: Which is empty, since we didn't provide any arguments!
Haskell - Functions. Functions play a major role in Haskell, as it is a functional programming language. Like other languages, Haskell does have its own functional definition and declaration. Function declaration consists of the function name and its argument list along with its output.
We sometimes have to write a function that is going to be used only once, throughout the entire lifespan of an application. To deal with this kind of situations, Haskell developers use another anonymous block known as lambda expression or lambda function. A function without having a definition is called a lambda function.
The compiler will start searching for a function called "fact" with an argument. If the argument is not equal to 0, then the number will keep on calling the same function with 1 less than that of the actual argument. When the pattern of the argument exactly matches with 0, it will call our pattern which is "fact 0 = 1".
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.
An 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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With