Conditional Expressions and Pattern Matching

0
P
R
O
G
R
A
M
M
I
N
G
 
I
N
 
H
A
S
K
E
L
L
Chapter 4 - Defining Functions
1
Conditional Expressions
As in most programming languages, functions can
be defined using 
conditional expressions
.
abs :: Int 
 Int
abs n = if n 
 0 then n else -n
abs takes an integer n and returns n if it
is non-negative and -n otherwise.
2
Conditional expressions can be nested:
signum :: Int 
 Int
signum n = if n < 0 then -1 else
              if n == 0 then 0 else 1
z
In Haskell, conditional expressions must 
always
have an else branch, which avoids any possible
ambiguity problems with nested conditionals.
Note:
3
Guarded Equations
As an alternative to conditionals, functions can also
be defined using 
guarded equations
.
abs n | n 
 0     = n
      | otherwise = -n
As previously, but using guarded equations.
4
Guarded equations can be used to make definitions
involving multiple conditions easier to read:
z
The catch all condition 
otherwise
 is defined in
the prelude by otherwise = True.
Note:
signum n | n < 0     = -1
         | n == 0    = 0
         | otherwise = 1
5
Pattern Matching
Many functions have a particularly clear definition
using 
pattern matching
 on their arguments.
not :: Bool 
 Bool
not False = True
not True  = False
not maps False to True, and True to False.
6
Functions can often be defined in many different
ways using pattern matching.  For example
(&&) :: Bool 
 Bool 
 Bool
True  && True  = True
True  && False = False
False && True  = False 
False && False = False
True && True = True
_    && _    = False
can be defined more compactly by
7
True  && b = b
False && _ = False
However, the following definition is more efficient,
because it avoids evaluating the second argument
if the first argument is False:
z
The underscore symbol _ is a 
wildcard
 pattern
that matches any argument value.
Note:
8
z
Patterns may not 
repeat
 variables.  For example,
the following definition gives an error:
b && b = b
_ && _ = False
z
Patterns are matched 
in order
.  For example, the
following definition always returns False:
_    && _    = False
True && True = True
9
List Patterns
Internally, every non-empty list is constructed by
repeated use of an operator (:) called 
cons
 that
adds an element to the start of a list.
[1,2,3,4]
Means 1:(2:(3:(4:[]))).
10
Functions on lists can be defined using 
x:xs
 patterns.
head :: [a] 
 a
head (x:_) = x
tail :: [a] 
 [a]
tail (_:xs) = xs
head and tail map any non-empty list to
its first and remaining elements.
11
Note:
z
x:xs patterns must be 
parenthesised
, because
application has priority over (:).  For example,
the following definition gives an error:
z
x:xs patterns only match 
non-empty
 lists:
> head []
*** Exception: empty list
head x:_ = x
12
Lambda Expressions
Functions can be constructed without naming the
functions by using 
lambda expressions
.
x 
 x + x
the nameless function that takes a
number x and returns the result x + x.
13
z
The symbol 
 is the Greek letter 
lambda
, and is
typed at the keyboard as a backslash \.
z
In mathematics, nameless functions are usually
denoted using the 
 symbol,
 as in x 
 x + x.
z
In Haskell, the use of the 
 symbol for nameless
functions comes from the 
lambda calculus
, the
theory of functions on which Haskell is based.
Note:
14
Why Are 
Lambda's
 Useful?
Lambda expressions can be used to give a formal
meaning to functions defined using 
currying
.
For example:
add x y = x + y
add = 
x 
 (
y 
 x + y)
means
15
const :: a 
 b 
 a
const x _ = x
is more naturally defined by
const :: a 
 (b 
 a)
const x = 
_ 
 x 
Lambda expressions are also useful when defining
functions that return 
functions as results
.
For example:
16
odds n = map f [0..n-1]
         where
            f x = x*2 + 1
can be simplified to
odds n = map (
x 
 x*2 + 1) [0..n-1]
Lambda expressions can be used to avoid naming
functions that are only 
referenced once
.
For example:
17
Operator Sections
An operator written 
between
 its two arguments can
be converted into a curried function written 
before
its two arguments by using parentheses.
For example:
> 1+2
3
> (+) 1 2
3
18
This convention also allows one of the arguments
of the operator to be included in the parentheses.
For example:
> (1+) 2
3
> (+2) 1
3
In general, if 
 is an operator then functions of the
form (
), (x
) and (
y) are called 
sections
.
19
Why Are 
Sections
 Useful?
Useful functions can sometimes be constructed in
a simple way using sections.  For example:
20
Exercises
Consider a function 
safetail
 that behaves in the
same way as tail, except that safetail maps the
empty list to the empty list, whereas tail gives
an error in this case.  Define safetail using:
  
(a)
 
a conditional expression;
  
(b)
 
guarded equations;
  
(c)
 
pattern matching.
Hint: the library function null :: [a] 
 Bool can
be used to test if a list is empty.
(1)
21
True && True = True
_    && _    = False
True  && b = b
False && _ = False
Slide Note
Embed
Share

In Haskell programming, functions can be defined using conditional expressions, guarded equations, and pattern matching. Conditional expressions allow for defining functions based on conditions, while guarded equations provide an alternative approach to conditionals. Pattern matching offers a clear and concise way to define functions by matching specific patterns in the arguments. Explore these concepts in Haskell for efficient and elegant function definitions.

  • Haskell
  • Programming
  • Functions
  • Conditional Expressions
  • Pattern Matching

Uploaded on Feb 18, 2025 | 0 Views


Download Presentation

Please find below an Image/Link to download the presentation.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author.If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.

You are allowed to download the files provided on this website for personal or commercial use, subject to the condition that they are used lawfully. All files are the property of their respective owners.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author.

E N D

Presentation Transcript


  1. PROGRAMMING IN HASKELL PROGRAMMING IN HASKELL Chapter 4 - Defining Functions 0

  2. Conditional Expressions As in most programming languages, functions can be defined using conditional expressions. abs :: Int Int abs n = if n 0 then n else -n abs takes an integer n and returns n if it is non-negative and -n otherwise. 1

  3. Conditional expressions can be nested: signum :: Int Int signum n = if n < 0 then -1 else if n == 0 then 0 else 1 Note: z In Haskell, conditional expressions must always have an else branch, which avoids any possible ambiguity problems with nested conditionals. 2

  4. Guarded Equations As an alternative to conditionals, functions can also be defined using guarded equations. abs n | n 0 = n | otherwise = -n As previously, but using guarded equations. 3

  5. Guarded equations can be used to make definitions involving multiple conditions easier to read: signum n | n < 0 = -1 | n == 0 = 0 | otherwise = 1 Note: z The catch all condition otherwise is defined in the prelude by otherwise = True. 4

  6. Pattern Matching Many functions have a particularly clear definition using pattern matching on their arguments. not :: Bool Bool not False = True not True = False not maps False to True, and True to False. 5

  7. Functions can often be defined in many different ways using pattern matching. For example (&&) :: Bool Bool Bool True && True = True True && False = False False && True = False False && False = False can be defined more compactly by True && True = True _ && _ = False 6

  8. However, the following definition is more efficient, because it avoids evaluating the second argument if the first argument is False: True && b = b False && _ = False Note: z The underscore symbol _ is a wildcard pattern that matches any argument value. 7

  9. z Patterns are matched in order. For example, the following definition always returns False: _ && _ = False True && True = True z Patterns may not repeat variables. For example, the following definition gives an error: b && b = b _ && _ = False 8

  10. List Patterns Internally, every non-empty list is constructed by repeated use of an operator (:) called cons that adds an element to the start of a list. [1,2,3,4] Means 1:(2:(3:(4:[]))). 9

  11. Functions on lists can be defined using x:xs patterns. head :: [a] a head (x:_) = x tail :: [a] [a] tail (_:xs) = xs head and tail map any non-empty list to its first and remaining elements. 10

  12. Note: z x:xs patterns only match non-empty lists: > head [] *** Exception: empty list z x:xs patterns must be parenthesised, because application has priority over (:). For example, the following definition gives an error: head x:_ = x 11

  13. Lambda Expressions Functions can be constructed without naming the functions by using lambda expressions. x x + x the nameless function that takes a number x and returns the result x + x. 12

  14. Note: z The symbol is the Greek letter lambda, and is typed at the keyboard as a backslash \. z In mathematics, nameless functions are usually denoted using the symbol, as in x x + x. z In Haskell, the use of the symbol for nameless functions comes from the lambda calculus, the theory of functions on which Haskell is based. 13

  15. Why Are Lambda's Useful? Lambda expressions can be used to give a formal meaning to functions defined using currying. For example: add x y = x + y means add = x ( y x + y) 14

  16. Lambda expressions are also useful when defining functions that return functions as results. For example: const :: a b a const x _ = x is more naturally defined by const :: a (b a) const x = _ x 15

  17. Lambda expressions can be used to avoid naming functions that are only referenced once. For example: odds n = map f [0..n-1] where f x = x*2 + 1 can be simplified to odds n = map ( x x*2 + 1) [0..n-1] 16

  18. Operator Sections An operator written between its two arguments can be converted into a curried function written before its two arguments by using parentheses. For example: > 1+2 3 > (+) 1 2 3 17

  19. This convention also allows one of the arguments of the operator to be included in the parentheses. For example: > (1+) 2 3 > (+2) 1 3 In general, if is an operator then functions of the form ( ), (x ) and ( y) are called sections. 18

  20. Why Are Sections Useful? Useful functions can sometimes be constructed in a simple way using sections. For example: - successor function (1+) - reciprocation function (1/) - doubling function (*2) - halving function (/2) 19

  21. Exercises (1) Consider a function safetail that behaves in the same way as tail, except that safetail maps the empty list to the empty list, whereas tail gives an error in this case. Define safetail using: (a) a conditional expression; (b) guarded equations; (c) pattern matching. Hint: the library function null :: [a] Bool can be used to test if a list is empty. 20

  22. (2) Give three possible definitions for the logical or operator (||) using pattern matching. (3) Redefine the following version of (&&) using conditionals rather than patterns: True && True = True _ && _ = False (4) Do the same for the following version: True && b = b False && _ = False 21

More Related Content

giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#