PROGRAMMING IN HASKELL

Preview:

DESCRIPTION

PROGRAMMING IN HASKELL. Author: Prof Graham Hutton Functional Programming Lab School of Computer Science University of Nottingham, UK (Used with Permission). The > prompt means that the system is ready to evaluate an expression. For example:. > 2+3*4 14 > (2+3)*4 20 - PowerPoint PPT Presentation

Citation preview

1

PROGRAMMING IN HASKELL

Author: Prof Graham HuttonFunctional Programming LabSchool of Computer ScienceUniversity of Nottingham, UK(Used with Permission)

2

The > prompt means that the system is ready to evaluate an expression.

For example:

> 2+3*414

> (2+3)*420

> sqrt (3^2 + 4^2)5.0

3

The Standard PreludeThe library file Prelude.hs provides a large number of standard functions. In addition to the familiar numeric functions such as + and *, the library also provides many useful functions on lists.Because of the predefinitions, GHCi may

complain if you try to redefine something it already has a definition for.

Select the first element of a list:

Single line comments are preceded by ``--'' and continue to the end of the line.

> head [1,2,3,4,5]1

4

Remove the first element from a list:

> tail [1,2,3,4,5][2,3,4,5]

Select the nth element of a list:

> [1,2,3,4,5] !! 23

Select the first n elements of a list:

> take 3 [1,2,3,4,5][1,2,3]

5

Remove the first n elements from a list:

> drop 3 [1,2,3,4,5][4,5]

Calculate the length of a list:

> length [1,2,3,4,5]5

Calculate the sum of a list of numbers:

> sum [1,2,3,4,5]15

6

Calculate the product of a list of numbers:

> product [1,2,3,4,5]120

Append two lists:

> [1,2,3] ++ [4,5][1,2,3,4,5]

Reverse a list:

> reverse [1,2,3,4,5][5,4,3,2,1]

7

Examples

Mathematics Haskell

f(x)

f(x,y)

f(g(x))

f(x,g(y))

f(x)g(y)

f x

f x y

f (g x)

f x (g y)

f x * g y

8

Haskell ScriptsAs well as the functions in the standard

prelude, you can also define your own functions;

New functions are defined within a script, a text file comprising a sequence of definitions;

By convention, Haskell scripts usually have a .hs suffix on their filename. This is not mandatory, but is useful for identification purposes.

9

My First Script

double x = x + x

quadruple x = double (double x)

When developing a Haskell script, it is useful to keep two windows open, one running an editor for the script, and the other running GHCi.

Start an editor, type in the following two function definitions, and save the script as test.hs:

10

Leaving the editor open, click on the file to open ghci using that file:

> quadruple 1040

> take (double 2) [1,2,3,4,5,6][1,2,3,4]

Now both Prelude.hs and test.hs are loaded, and functions from both scripts can be used:

11

factorial n = product [1..n]

average ns = sum ns `div` length ns

Leaving GHCi open, return to the editor, add the following two definitions, and resave. From withinGHCi, enter :r (to reload the changed file)

These functions are defined via an equation

div is enclosed in back quotes, not forward;

x `f` y is just syntactic sugar for f x y.

Note:

12

> :rReading file "test.hs"

> factorial 103628800

> average [1,2,3,4,5]3

GHCi does not automatically detect that the script has been changed, so a reload command must be executed before the new definitions can be used:

13

Naming RequirementsFunction and argument names must begin

with a lower-case letter. For example:

myFun fun1 arg_2 x’

By convention, list arguments usually have an s suffix on their name. For example:

xs ns nss

14

The Layout Rule

In a sequence of definitions, each definition must begin in precisely the same column:

a = 10

b = 20

c = 30

a = 10

b = 20

c = 30

a = 10

b = 20

c = 30

15

means

The layout rule avoids the need for explicit syntax to indicate the grouping of definitions.We can introduce local variables on the right hand side via a “where” clause.

a = b + c where b = 1 c = 2d = a * 2

a = b + c where {b = 1; c = 2}d = a * 2

implicit grouping

explicit grouping

16

Useful Commands in GHCiCommand Meaning

:load name load script name:reload reload current script:edit name edit script name:edit edit current script:type expr show type of expr:? show all commands:quit quit

17

Exercises

N = a ’div’ length xs where a = 10 xs = [1,2,3,4,5]

Try out the examples of this lecture

Fix the syntax errors in the program below, and test your solution.

(1)

(2)

18

Show how the library function last that selects the last element of a list can be defined using the functions introduced in this lecture.

(3)

Similarly, show how the library function init that removes the last element from a list can be defined in two different ways.

(5)

Can you think of another possible definition for last?

(4)

19

PROGRAMMING IN HASKELL

Types and Classes

20

What is a Type?A type is a name for a collection of related values. For example, in Haskell the basic type

TrueFalse

Bool

contains the two logical values:

21

Algebraic types

there are still things we are missing such as The types for the months January… December. The type whose elements are either a number

or a string.  (a house will either have a number or name, say)

A type of tree. All of these can be modeled as algebraic

types.

22

The simplest form of an algebraic type is an enumerated type.

data Season = Spring | Summer | Fall | Winterdata Weather = Rainy | Hot | Cold data Color = Red | Blue| Green|Yellow deriving (Show,Eq,Ord)data Ordering = LT|EQ|GT  --  built into the Ordering Class A more complicated algebraic type (the product type) allows for the

type constructor to have types associated with it.data Student = USU String  Intdata Address = None | Addr Stringdata Age = Years Intdata Shape = Circle Float | Rectangle Float Floatdata Tree a = Branch (Tree a) (Tree a) | Leaf adata Point a = Pt a a

Thus, Student is formed from a String (call it st) and an Int (call it x) and the element Student formed from them will be recognized as USU st x

23

The general form of the algebraic type is

data TypeName   = Con1 T11 .. T1n |      Con2 T21..T2m |Each Coni is a constructor which may be

followed by zero or more types.  We build elements of TypeName by applying this constsructor functions to arguments.

24

Algebraic types can also be recursive

data Expr = Lit Int | Add Expr Expr | Sub Expr Expr

data Tree = Nil | Node Int Tree Tree

printBST:: Tree -> [Int]printBST Nil = []printBST (Node x left right) = (printBST left) +

+ [x]++ (printBST right) main> printBST (Node 5 (Node 3 Nil Nil) Nil)[3,5]

25

Type ErrorsApplying a function to one or more arguments of the wrong type is called a type error.

> 1 + FalseError

1 is a number and False is a logical value, but + requires two

numbers.

26

Types in HaskellIf evaluating an expression e would

produce a value of type t, then e has type t, written

e :: t

Every well formed expression has a type, which can be automatically calculated at compile time using a process called type inference.

27

All type errors are found at compile time, which makes programs safer and faster by removing the need for type checks at run time.

In GHCi, the :type command calculates the type of an expression, without evaluating it:

> not FalseTrue

> :type not Falsenot False :: Bool

28

Basic TypesHaskell has a number of basic types, including:

Bool - logical valuesChar - single characters

Integer - arbitrary-precision integersFloat - floating-point numbers

String - strings of charactersInt - fixed-precision integers

29

List Types

[False,True,False] :: [Bool]

[’a’,’b’,’c’,’d’] :: [Char]

In general:

A list is sequence of values of the same type:

[t] is the type of lists with elements of type t.

30

The type of a list says nothing about its length:

[False,True] :: [Bool]

[False,True,False] :: [Bool]

[[’a’],[’b’,’c’]] :: [[Char]]

Note:

The type of the elements is unrestricted. For example, we can have lists of lists:

31

Tuple Types (like a struct or record)

A tuple is a sequence of values of different types:

(False,True) :: (Bool,Bool)

(False,’a’,True) :: (Bool,Char,Bool)

In general:(t1,t2,…,tn) is the type of n-tuples whose ith components have type ti for any i in 1…n.

32

The type of a tuple shows its size:

(False,True) :: (Bool,Bool)

(False,True,False) :: (Bool,Bool,Bool)

(’a’,(False,’b’)) :: (Char,(Bool,Char))

(True,[’a’,’b’]) :: (Bool,[Char])

Note:

The type of the components is unrestricted:

33

Function Types

not :: Bool Bool

isDigit :: Char Bool

In general:

A function is a mapping from values of one type to values of another type:

t1 t2 is the type of functions that map values of type t1 to values to type t2.

34

The arrow is typed at the keyboard as ->.

The argument and result types are unrestricted. For example, functions with multiple arguments or results are possible using lists or tuples:

Note:

addPair :: (Int,Int) IntaddPair (x,y) = x+y

zeroto :: Int [Int]zeroto n = [0..n]

35

We can also define a function via pattern match of the arguments.

error is a built-in error function which causes program termination and the printing of the string.

fac 0 = 1fac (n+1) = product [1..(n+1)] or…fac2 n | n <  0    = error "input to fac is negative"

      | n == 0    = 1       | n >  0    = product [1..n]

36

n+k -- patterns

useful when writing inductive definitions over integers. For example:

x ^ 0     = 1 -- defines symbol as an operator

x ^ (n+1) = x*(x^n) fac 0 = 1fac (n+1) = (n+1)*fac n ack 0 n = n+1ack (m+1) 0 = ack m 1ack (m+1) (n+1) = ack m (ack (m+1) n)

37

The infix operators are really just functions. Notice the pattern matching.

(++) :: [a] -> [a] -> [a] [] ++ ys = ys (x:xs) ++ ys = x : (xs++ys)

38

Functions with multiple arguments are also possible by returning functions as results:

add’ :: (Int Int) Intadd’ :: Int (Int Int)add’ x y = x+y

add’ takes an integer x and returns a function add’ x. In turn, this function

takes an integer y and returns the result x+y.

Curried Functions

In a curried function, the arguments can be partially applied. This allows us to get multiple functions with one declaration. In this case, we have a two parameter version of add’ and a one parameter version by passing add’ 5 (for example)

39

addPair and add’ produce the same final result, but addPair takes its two arguments at the same time, whereas add’ takes them one at a time:

Note:

Functions that take their arguments one at a time are called curried functions, celebrating the work of Haskell Curry on such functions.

addPair :: (Int,Int) Int

add’ :: Int (Int Int)

40

Why curried functions? Curry – named for inventor - Haskell Curry. It is also called

partial application. Currying is like a nested function a function of a function… If we don’t supply all the arguments to a curried function, we

create a NEW function (that just needs the rest of its arguments). Why is that useful? It allows function reuse we can pass the new function to be used in a case that

needs fewer arguments. For example: map (f) [1,3,5,6] applies f to each element of the list f needs to work with a single argument Because of currying, we can pass (+3), (^4), (*2) (add 5) functions are objects – we can pass them around as such

41

FunctionsFunction application is curried, associates

to the left, and always has a higher precedence than infix operators.

Thus ``f x y + g a b'' parses as ``((f x) y) + ((g a) b)''

42

So why do we want a curried function? Suppose we had already defined add’ and

had the need to add 5 to every element of a list.

Doing something to every element is a list is a common need. It is called “mapping”

Instead of creating a separate function to add five, we can call map (add’ 5) [1,2,3,4,5] or even map (+5) [1,2,3,4,5]

43

Functions with more than two arguments can be curried by returning nested functions:

mult :: Int (Int (Int Int))mult x y z = x*y*z

mult takes an integer x and returns a function mult x, which in turn takes an

integer y and returns a function mult x y, which finally takes an integer z and

returns the result x*y*z.

44

Why is Currying Useful?Curried functions are more flexible than functions on tuples, because useful functions can often be made by partially applying a curried function.

For example:

add’ 1 :: Int Int

take 5 :: [Int] [Int]

drop 5 :: [Int] [Int]

45

Currying Conventions

The arrow associates to the right.

Int Int Int Int

To avoid excess parentheses when using curried functions, two simple conventions are adopted:

Means Int (Int (Int Int)).

46

As a consequence, it is then natural for function application to associate to the left. (Similar to a parse tree where the expression lower in the tree has the highest precedence).mult x y z

Means ((mult x) y) z.

Unless tupling is explicitly required, all functions in Haskell are normally defined in curried form.

47

Polymorphic FunctionsA function is called polymorphic (“of many forms”) if its type contains one or more type variables.

length :: [a] Int

for any type a, length takes a list of values of type a and returns an

integer.

48

In contrast, a monomorphic function works on only type typeinc:: Int ->Intinc x = x+1

49

length :: [a] ->IntType variables can be instantiated to

different types in different circumstances:

Note:

Type variables must begin with a lower-case letter, and are usually named a, b, c, etc.

> length [False,True]2

> length [1,2,3,4]4

a = Bool

a = Int

50

Many of the functions defined in the standard prelude are polymorphic. For example: fst :: (a,b) a first element

head :: [a] a first in list

take :: Int [a] [a] pull so many from beginning

zip :: [a] [b] [(a,b)]

pull off pairwise into tuples

id :: a a identity

51

Overloaded Functions

Type classes provide a structured way to control polymorphism.

sum :: Num a [a] a

for any numeric type a, sum takes a list of values of type a and returns a

value of type a.

52

Constrained type variables can be instantiated to any types that satisfy the constraints:

Note:

> sum [1,2,3]6

> sum [1.1,2.2,3.3]6.6

> sum [’a’,’b’,’c’]ERROR

Char is not a numeric

type

a = Int

a = Float

53

Num - Numeric typesEq - Equality typesOrd - Ordered types

Haskell has a number of type classes, including:

For example:(+) :: Num a a a a (==) :: Eq a a a Bool

(<) :: Ord a a a BoolSee types by entering :t (==)

54

Hints and TipsWhen defining a new function in Haskell, it

is useful to begin by writing down its type;

Within a script, it is good practice to state the type of every new function defined;

When stating the types of polymorphic functions that use numbers, equality or orderings, take care to include the necessary class constraints.

55

Exercises

[’a’,’b’,’c’]

(’a’,’b’,’c’)

[(False,’0’),(True,’1’)]

([False,True],[’0’,’1’])

[tail,init,reverse]

What are the types of the following values?(1)

56

second xs = head (tail xs)

swap (x,y) = (y,x)

pair x y = (x,y)

double x = x*2

palindrome xs = reverse xs == xs

twice f x = f (f x)

What are the types of the following functions?(2)

Check your answers using GHCi.(3)

57

PROGRAMMING IN HASKELL

Defining Functions

58

Conditional ExpressionsAs in most programming languages, functions can be defined using conditional expressions.

abs :: Int Intabs n = if n 0 then n else -n

abs takes an integer n and returns n if it is non-negative and -n

otherwise.

59

Conditional expressions can be nested:

signum :: Int Intsignum n = if n < 0 then -1 else if n == 0 then 0 else 1

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

Note:

60

Guarded EquationsAs 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.

61

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

The catch all condition otherwise is defined in the prelude by otherwise = True.

Note:

signum n | n < 0 = -1 | n == 0 = 0 | otherwise = 1

62

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

not :: Bool Boolnot False = Truenot True = False

not maps False to True, and True to False.

63

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

both :: Bool Bool BoolTrue `both` True = TrueTrue `both` False = FalseFalse `both` True = False False `both` False = False

True`both` True = True_ `both` _ = False

can be defined more compactly by

64

True `both` b = bFalse `both` _ = False`

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

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

Note:

65

Patterns may not repeat variables. For example, the following definition gives an error:

b && b = b_ && _ = False

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

_ && _ = FalseTrue && True = True

66

List PatternsInternally, every non-empty list is constructed by repeated use of an operator (:) called “cons” (for construct ) that adds an element to the start of a list. Note this is NOT the same as concatenation of lists.

[1,2,3,4]

Means 1:(2:(3:(4:[]))).

67

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

head :: [a] ahead (x:_) = x

tail :: [a] [a]tail (_:xs) = xs

head and tail map any non-empty list to its first and remaining

elements.

68

Note:

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

x:xs patterns only match non-empty lists:

> head []Error

head x:_ = x

69

Integer Patterns

pred :: Int Intpred (n+1) = n

As in mathematics, functions on integers can be defined using n+k patterns, where n is an integer variable and k>0 is an integer constant.

pred maps any positive integer to its predecessor.

70

Note:

n+k patterns must be parenthesised, because application of = has priority over +. For example, the following definition gives an error:

n+k patterns only match integers k.

> pred 0Error

pred n+1 = n

71

Lambda ExpressionsFunctions 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.

twoTimes x x+x

similar to the named function

72

The symbol is the Greek letter lambda, and is typed at the keyboard as a backslash \.

In mathematics, nameless functions are usually denoted using the symbol, as in x x+x.

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:

73

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

74

const :: a b aconst 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:

75

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:

76

Turning infix functions into prefix ones SectionsAn infix operator written between its two

arguments can be converted into a curried function written before its two arguments by using parentheses.

For example:> 1+23

> (+) 1 23

77

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

For example:

> (1+) 23

> (+2) 13

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

78

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

- successor function

- reciprocation function

- doubling function

- halving function

(1+)

(*2)

(/2)

(1/)

79

ExercisesConsider 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)

80

Give three possible definitions for the logical or operator (or) using pattern matching.

(2)

Redefine the following version of (and) using conditionals rather than patterns:

(3)

True `and` True = True_ `and` _ = False

Do the same for the following version:(4)

True `and` b = bFalse `and` _ = False

81

PROGRAMMING IN HASKELL

82

Set ComprehensionsIn mathematics, the comprehension notation can be used to construct new sets from old sets.Comprehension has two meanings in English: a. understanding b. the act of process or comprising or including{x2 | x {1...5}}

The set {1,4,9,16,25} of all numbers x2 such that x is an element of the set

{1…5}.

83

Lists ComprehensionsIn Haskell, a similar comprehension notation can be used to construct new lists from old lists.

[x^2 | x [1..5]]

The list [1,4,9,16,25] of all numbers x^2 such that x is an element of the

list [1..5].

84

Note:

The expression x [1..5] is called a generator, as it states how to generate values for x.

Comprehensions can have multiple generators, separated by commas. For example:

> [(x,y) | x [1,2,3], y [4,5]]

[(1,4),(1,5),(2,4),(2,5),(3,4),(3,5)]

85

Changing the order of the generators changes the order of the elements in the final list:

> [(x,y) | y [4,5], x [1,2,3]]

[(1,4),(2,4),(3,4),(1,5),(2,5),(3,5)]

Multiple generators are like nested loops, with later generators as more deeply nested loops whose variables change value more frequently.

86

> [(x,y) | y [4,5], x [1,2,3]]

[(1,4),(2,4),(3,4),(1,5),(2,5),(3,5)]

For example:

x [1,2,3] is the last generator, so the value of the x component

of each pair changes most frequently.

87

Dependant GeneratorsLater generators can depend on the variables that are introduced by earlier generators.

[(x,y) | x [1..3], y [x..3]]

The list [(1,1),(1,2),(1,3),(2,2),(2,3),(3,3)]

of all pairs of numbers (x,y) such that x,y are elements of the list [1..3] and y

x.

88

Using a dependant generator we can define the library function that concatenates a list of lists:

concat :: [[a]] [a]concat xss = [x | xs xss, x xs]

For example:

> concat [[1,2,3],[4,5],[6]]

[1,2,3,4,5,6]

89

Arithmetic sequencesThere is a shorthand notation for lists whose elements form an arithmetic series. [1..5]    -- yields [1,2,3,4,5][1,3..10] -- yields [1,3,5,7,9] In the second list, the difference between the first two elements is used to compute the remaining elements in the series.

90

GuardsList comprehensions can use guards to restrict the values produced by earlier generators.

[x | x [1..10], even x]

The list [2,4,6,8,10] of all numbers x such that x is an

element of the list [1..10] and x is even.

91

factors :: Int [Int]factors n = [x | x [1..n], n `mod` x == 0]

Using a guard we can define a function that maps a positive integer to its list of factors:

For example:

> factors 15

[1,3,5,15]

92

A positive integer is prime if its only factors are 1 and itself. Hence, using factors we can define a function that decides if a number is prime:

prime :: Int Boolprime n = factors n == [1,n]

For example:

> prime 15False

> prime 7True

93

Using a guard we can now define a function that returns the list of all primes up to a given limit:

primes :: Int [Int]primes n = [x | x [2..n], prime x]

For example:

> primes 40

[2,3,5,7,11,13,17,19,23,29,31,37]

94

The Zip FunctionA useful library function is zip, which maps two lists to a list of pairs of their corresponding elements.

zip :: [a] [b] [(a,b)]

For example:

> zip [’a’,’b’,’c’] [1,2,3,4]

[(’a’,1),(’b’,2),(’c’,3)]

95

Using zip we can define a function returns the list of all pairs of adjacent elements from a list:

For example:

pairs :: [a] [(a,a)]pairs xs = zip xs (tail xs)

> pairs [1,2,3,4]

[(1,2),(2,3),(3,4)]

96

Using pairs we can define a function that decides if the elements in a list are sorted:

For example:

sorted :: Ord a [a] Boolsorted xs = and [x y | (x,y) pairs xs]

> sorted [1,2,3,4]True

> sorted [1,3,2,4]False

97

Using zip we can define a function that returns the list of all positions of a specified value in a list:

positions :: Eq a a [a] [Int]positions x xs = [i | (x’,i) zip xs [0..n], x == x’] where n = length xs - 1

For example:

> positions 0 [1,0,0,1,0,1,1,0][1,2,4,7]

98

String Comprehensions

A string is a sequence of characters enclosed in double quotes. Internally, however, strings are represented as lists of characters.

"abc" :: String

Means [’a’,’b’,’c’] :: [Char].

99

Because strings are just special kinds of lists, any polymorphic function that operates on lists can also be applied to strings. For example:

> length "abcde"5

> take 3 "abcde""abc"

> zip "abc" [1,2,3,4][(’a’,1),(’b’,2),(’c’,3)]

100

Similarly, list comprehensions can also be used to define functions on strings, such as a function that counts the lower-case letters in a string:

lowers :: String Intlowers xs = length [x | x xs, isLower x]

For example:

> lowers "Haskell"

6

101

ExercisesA triple (x,y,z) of positive integers is called pythagorean if x2 + y2 = z2. Using a list comprehension, define a function

(1)

pyths :: Int [(Int,Int,Int)]

that maps an integer n to all such triples with components in [1..n]. For example:

> pyths 5[(3,4,5),(4,3,5)]

102

A positive integer is perfect if it equals the sum of all of its factors, excluding the number itself. Using a list comprehension, define a function

(2)

perfects :: Int [Int]

that returns the list of all perfect numbers up to a given limit. For example:

> perfects 500

[6,28,496]

103

(xsi * ysi )i = 0

n-1

Using a list comprehension, define a function that returns the scalar product of two lists.

The scalar product of two lists of integers xs and ys of length n is give by the sum of the products of the corresponding integers:

(3)

104

PROGRAMMING IN HASKELL

Recursive Functions

105

IntroductionAs we have seen, many functions can naturally be defined in terms of other functions.

factorial :: Int Intfactorial n = product [1..n]

factorial maps any integer n to the product of the integers between 1 and

n.

106

Expressions are evaluated by a stepwise process of applying functions to their arguments.

For example:factorial 4

product [1..4]=

product [1,2,3,4]=

1*2*3*4=

24=

107

Recursive FunctionsIn Haskell, functions can also be defined in terms of themselves. Such functions are called recursive.

factorial 0 = 1factorial (n+1) = (n+1) * factorial n

factorial maps 0 to 1, and any other positive integer to the product of

itself and the factorial of its predecessor.

108

For example:factorial 3

3 * factorial 2=

3 * (2 * factorial 1)=

3 * (2 * (1 * factorial 0))=

3 * (2 * (1 * 1))=

3 * (2 * 1)=

=6

3 * 2=

109

Note:factorial 0 = 1 is appropriate because 1 is

the identity for multiplication: 1*x = x = x*1.

The recursive definition diverges on integers 0 because the base case is never reached:

> factorial (-1)

Error: Control stack overflow

110

Why is Recursion Useful?

Some functions, such as factorial, are simpler to define in terms of other functions.

Many functions can naturally be defined in terms of themselves.

Properties of functions defined using recursion can be proved using the simple but powerful mathematical technique of induction.

111

Recursion on Lists

Recursion is not restricted to numbers, but can also be used to define functions on lists.

product :: [Int] Intproduct [] = 1product (n:ns) = n * product ns

product maps the empty list to 1, and any non-empty list to its head multiplied by the product

of its tail.

112

For example:

product [2,3,4]

2 * product [3,4]=

2 * (3 * product [4])=

2 * (3 * (4 * product []))=

2 * (3 * (4 * 1))=

24=

113

Using the same pattern of recursion as in product we can define the length function on lists.

length :: [a] Intlength [] = 0length (_:xs) = 1 + length xs

length maps the empty list to 0, and any non-empty list to

the successor of the length of its tail.

114

For example:

length [1,2,3]

1 + length [2,3]=

1 + (1 + length [3])=

1 + (1 + (1 + length []))=

1 + (1 + (1 + 0))=

3=

115

Using a similar pattern of recursion we can define the reverse function on lists.

reverse :: [a] [a]reverse [] = []reverse (x:xs) = reverse xs ++ [x]

reverse maps the empty list to the empty list, and any non-empty list to the reverse of its tail appended to its

head.

116

For example:

reverse [1,2,3]

reverse [2,3] ++ [1]=

(reverse [3] ++ [2]) ++ [1]=

((reverse [] ++ [3]) ++ [2]) ++ [1]=

(([] ++ [3]) ++ [2]) ++ [1]=

[3,2,1]=

117

Permutation Examplepermute :: Eq a => [a] -> [[a]]permute [] = [[]]permute xs = [x:ys | x<-xs, ys <- permute

(delete' x xs)]

118

Multiple ArgumentsFunctions with more than one argument can also be defined using recursion. For example:

Zipping the elements of two lists:

zip :: [a] [b] [(a,b)]zip [] _ = []zip _ [] = []zip (x:xs) (y:ys) = (x,y) : zip xs ys

119

drop :: Int [a] [a]drop 0 xs = xsdrop (n+1) [] = []drop (n+1) (_:xs) = drop n xs

Remove the first n elements from a list:

(++) :: [a] [a] [a][] ++ ys = ys(x:xs) ++ ys = x : (xs ++ ys)

Appending two lists:

120

QuicksortThe quicksort algorithm for sorting a list of integers can be specified by the following two rules:

The empty list is already sorted;

Non-empty lists can be sorted by sorting the tail values the head, sorting the tail values the head, and then appending the resulting lists on either side of the head value.

121

Using recursion, this specification can be translated directly into an implementation:

qsort :: [Int] [Int]qsort [] = []qsort (x:xs) = qsort smaller ++ [x] ++ qsort larger where smaller = [a | a xs, a x] larger = [b | b xs, b x]

This is probably the simplest implementation of quicksort in any programming language!

Note:

122

For example (abbreviating qsort as q):

q [3,2,4,1,5]

q [2,1] ++ [3] ++ q [4,5]

q [1] q []++ [2] ++ q [] q [5]++ [4] ++

[1] [] [] [5]

123

Exercises(1) Without looking at the standard prelude,

define the following library functions using recursion:

and :: [Bool] Bool

Decide if all logical values in a list are true:

concat :: [[a]] [a]

Concatenate a list of lists : concat([2,3,4],[3,4,5],[4]) =

[2,3,4,3,4,5,4]

124

(!!) :: [a] Int a

Select the nth element of a list:

elem :: Eq a a [a] Bool

Decide if a value is an element of a list:

replicate :: Int a [a]

Produce a list with n identical elements:

125

(2)Define a recursive function

merge :: [Int] [Int] [Int]

that merges two sorted lists of integers to give a single sorted list. For example:

> merge [2,5,6] [1,3,4]

[1,2,3,4,5,6]

126

(3) Define a recursive function

Lists of length 1 are already sorted;

Other lists can be sorted by sorting the two halves and merging the resulting lists.

msort :: [Int] [Int]

that implements merge sort, which can be specified by the following two rules:

Recommended