Functions with Multiple Arguments
Explore the use of tuples in Haskell functions to manage multiple input parameters and multiple return values. Understand tuple pattern matching, learn the rules of pattern linearity, and use accessor functions like fst and snd. Gain practical skills writing functions that operate on tuples and combine results effectively.
We'll cover the following...
Now that we know about tuples, let’s see how we can use them in functions. In principle, there are two use cases:
- using tuples as the argument type of functions to write functions that take multiple parameters.
- using tuples as the return type of functions to write functions that have multiple results.
Tuples as arguments
Let’s write a function which computes the perimeter of a rectangle when given its two sides a and b:
In the equation of perimeter, we see a new kind of pattern: the tuple pattern (a, b). It will match any tuple and bind its values to the pattern variables a and b. We then use these variables to compute the result.
*Perimeter> perimeter (2, 3)
10
We can also use literal or wildcard patterns inside tuple patterns. The function both checks whether both of its arguments are true:
Formally, a tuple pattern for the tuple type (t_1, t_2,..., t_N) has the form ...