Professional Documents
Culture Documents
Theory:
Example
(1) ∶: ⟶
1= “ "
2= “ ”
3= “ ℎ ”
(2) _ ℎ ∶: ⟶
_ℎ 3 =
_ℎ =
(3) ∶: ⟶ ⟶
=
$ =
Note:- A function may have more than one argument, then each argument in the given
defining equation is checked from left to right.
1
• Following Inbuilt Functions are defined under pattern matching:
Examples:
(1) ∷ ( , $) ⟶
( , ') =
(2) ( ∷ ( , $) ⟶ $
( ( , ') = '
Note:- By convention, list arguments usually have an “s” suffix in their name. For eg:-
, etc.
Examples:
• When ,-. '[ ] is evaluated, the assignment matches the pattern and the output is
True.
• When ,-. ' (1: 2: 3: [ ] ) is evaluated, the output is False.
(2) ℎ ( ∷ [ ] ⟶
ℎ (( : ) =
(3) ∷ [ ] ⟶
( : ) =
2
• The sequence of the defining equation in a function are important as it effects the
output.
Examples:
Note:- If the last pattern is moved to the top, it would always say “not between 1 & 3”
because it would catch all the numbers and the other patterns will not be matched at all
even if 1, 2 or 3 is entered.
• Functions can often be defined in many different ways using pattern matching.
Examples:
(2) && =
_ && _ =
However, the following definition is more efficient because it avoids evaluating the
second argument, if the first argument is False.
(3) && $ = $
&& _ =
3
Note:- The underscore symbol ( _ ) is a wildcard pattern that matches any argument value.
Examples:
• Guards are a way of testing whether some property of a value (or several of them) is
true or false.
• It is similar to an if statement. The difference is that guards make the code far better
and more readable.
Examples:
$- $-
4
| $- <= 18.5 = “ ( ℎ”
| $- <= 25.0 = “ - ”
| $- <= 30.0 = “ ”
| ℎ = “ < ( -$ ”
• Guards are indicated by pipes that follows a function’s name and its parameter.
• They are indented a bit to the right and lined up.
• It is a Boolean expression.
• If it evaluates to true, then the corresponding function body is used.
• If it evaluates to false, checking drops through to the next guard and so on.
Note:- The last guard is otherwise and is simply defined as otherwise = True and
catches everything.
• The bmi function can be modified in the following manner where the user just needs
to enter his weight and height and the BMI will be calculated.
Examples:
(1) $- ∶ : (7 ) ⟹ ⟶ ⟶
$- ℎ ℎ ℎ
| ℎ /ℎ ℎ ^2 <= 18.5 = “ ( ℎ ”
| ℎ /ℎ ℎ ^2 <= 25.5 = “ - ”
| ℎ /ℎ ℎ ^2 <= 30.0 = “ ”
| ℎ =“ < ( -$ ”
• In the above example, the formula for calculating the bmi is repeated for every guard.
To overcome the repetition, where clause can be used.
(2) $- ∶ : (7 ) ⟹ ⟶ ⟶
5
$- ℎ ℎ ℎ
| $- <= 18.5 = “ ( ℎ”
| $- <= 25.0 = “ - ”
| $- <= 30.0 = “ ”
| ℎ = “ < ( -$ ”
ℎ $- = ℎ /ℎ ℎ ^2
Note:- Put the keyword where after the guards (usually its best to indent it as much as the
pipes are indented) and then define several names or functions.
ℎ ( : _) = -
( : _) = -
Reading Exercise:-
6
c) Difference between let and while.
Exercise:-