Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 326
CMD Avatar asked Nov 21 '21 11:11

CMD


People also ask

How to get arguments in a Haskell program?

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!

What is a function in Haskell?

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.

What is a lambda expression in Haskell?

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.

How does the compiler know that fact 0 = 1?

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".


1 Answers

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.

like image 160
Will Ness Avatar answered Oct 16 '22 06:10

Will Ness