CHAPTER 4 - DEFINING FUNCTIONS

NEW FROM OLD

Define new functions by combining one or more existing functions.

In [24]:
even :: Integral a => a -> Bool
even n = n `mod` 2 == 0

even 4
even 5
True
False
In [25]:
splitAt :: Int -> [a] -> ([a],[a])
splitAt n xs = (take n xs, drop n xs)

splitAt 4 [10..20]
([10,11,12,13],[14,15,16,17,18,19,20])
In [26]:
recip :: Fractional a => a -> a
recip n = 1/n

recip 2
0.5

CONDITIONAL EXPRESSIONS

Conditional expressions are quite useful in composing functions. Some examples follow:

In [27]:
abs :: Int -> Int
abs n = if n >= 0 then n else -n

abs (-4)
abs 4
4
4

abs takes an integer n as input and returns n if n is non-negative and -n otherwise.

Conditional expressions can be nested:

In [28]:
signum :: Int -> Int
signum n = if n < 0 then 
             -1 
           else if n == 0 then 
              0 
           else 
              1

signum (-88)
signum 88
Use guards
Found:
signum n = if n < 0 then -1 else if n == 0 then 0 else 1
Why Not:
signum n | n < 0 = -1 | n == 0 = 0 | otherwise = 1
-1
1

Note: In Haskell, conditional expressions must always have an else branch, which avoids any possible ambiguity problems with nested conditionals.

GUARDED EQUATIONS

As an alternative to conditionals, functions can also be defined using guarded equations.

In [29]:
abs n | n >= 0    = n
      | otherwise = -n
      
abs (-4)
abs 4
4
4

Guarded equations can be used to make definitions involving multiple conditions easier to read:

In [30]:
signum n | n < 0     = -1
         | n == 0    = 0
         | otherwise = 1
         
signum (-88)
signum 88
-1
1

Note: The catch all condition otherwise is defined in the Prelude by otherwise = True.

PATTERN MATCHING

Many functions have a particularly clear definition using pattern matching on their arguments.

In [31]:
not :: Bool -> Bool
not False = True
not True  = False

not maps False to True, and True to False.

Functions can often be defined in many different ways using pattern matching. For example

In [32]:
(&&) :: Bool -> Bool -> Bool
True  && True  = True
True  && False = False
False && True  = False 
False && False = False

can be defined more compactly by

In [33]:
(&&) :: Bool -> Bool -> Bool
True && True = True
_    && _    = False

However, the following definition is more efficient, because it avoids evaluating the second argument if the first argument is False:

In [34]:
(&&) :: Bool -> Bool -> Bool
True  && b = b
False && _ = False

Note: The underscore symbol _ is a wildcard pattern that matches any argument value.

Patterns are matched in order. For example, the following definition always returns False:

In [35]:
(&&) :: Bool -> Bool -> Bool
_    && _    = False
True && True = True

Tuple Patterns

In [36]:
fst :: (a,b) -> a
fst (x,_) = x

snd :: (a,b) -> b
snd (_,y) = y

fst (10,"John")
snd (10,"John")
10
"John"

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.

In [37]:
[1,2,3,4] == 1:(2:(3:(4:[])))
Use list literal
Found:
1 : (2 : (3 : (4 : [])))
Why Not:
[1, 2, 3, 4]
True

Functions on lists can be defined using x:xs patterns.

In [38]:
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.

Note:

1) x:xs patterns only match non-empty lists:

In [39]:
head []
<interactive>:2:1-14: Non-exhaustive patterns in function head

2) x:xs patterns must be parenthesised, because application has priority over (:). For example, the following definition gives an error:

In [40]:
head x:_ = x
Parse error (line 1, column 10): parse error on input ‘=’
Perhaps you need a 'let' in a 'do' block?
e.g. 'let x = 5' instead of 'x = 5'
In [41]:
head (10:(20:[]))
Use list literal
Found:
10 : (20 : [])
Why Not:
[10, 20]
10

LAMBDA EXPRESSIONS

Functions can be constructed without naming the functions by using lambda expressions.

In [42]:
(\ x -> x + x) 10
20

the nameless function that takes a number x and returns the result x + x.

Why Are Lambda's Useful?

Lambda expressions can be used to give a formal meaning to functions defined using currying.

For example:

In [43]:
add :: Int -> Int -> Int
add x y = x + y

means

In [44]:
add :: Int -> (Int -> Int)
add = \x -> (\y -> x + y)
Redundant lambda
Found:
add = \ x -> (\ y -> x + y)
Why Not:
add x y = x + y
Avoid lambda
Found:
\ x -> (\ y -> x + y)
Why Not:
(+)
Redundant bracket
Found:
\ x -> (\ y -> x + y)
Why Not:
\ x -> \ y -> x + y
Avoid lambda
Found:
\ y -> x + y
Why Not:
(x +)

Lambda expressions can be used to avoid naming functions that are only referenced once.

For example:

In [45]:
odds n = map f [0..n-1]
         where
            f x = x*2 + 1

can be simplified to

In [46]:
odds n = map (\x -> x*2 + 1) [0..n-1]
In [47]:
odds 5
[1,3,5,7,9]

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:

In [48]:
1 + 2

(+) 1 2
3
3

This convention also allows one of the arguments of the operator to be included in the parentheses.

For example:

In [49]:
(1+) 2

(+2) 1
3
3

In general, if $ \lambda $ is an operator then functions of the form ($ \lambda $), (x$ \lambda $) and ($ \lambda $y) are called sections.

Why Are Sections Useful?

Useful functions can sometimes be constructed in a simple way using sections. For example:

(1+) -- successor function
(1/) -- reciprocator function
(*2) --  doubling function
(/2) -- halving function
In [50]:
(1+) 5
(1/) 2
(*2) 4
(/2) 4
6
0.5
8
2.0