Title: COMP313A Functional Programming (1)
1COMP313AFunctional Programming (1)
2Main Differences with Imperative Languages
- Say more about what is computed as opposed to how
- Pure functional languages have no
- variables
- assignments
- other side effects
- Means no loops
3Differences
- Imperative languages have an implicit state
(state of variables) that is modified (side
effect). - Sequencing is important to gain precise,
deterministic control over the state - assignment statement needed to change the binding
for a particular variable (alter the implicit
state)
4- Imperative factorialnx
- a1while n gt 0 do
- begin a a n
- n n-1
- end
5Differences
- Declarative languages have no implicit state
- Program with expressions
- The state is carried around explicitly
- e.g. the formal parameter n in factorial
- Looping is accomplished with recursion rather
than sequencing
6- Haskell
- fac Int -gt Int
- fac n
- n 0 1
- n gt 0 fac(n-1) n
- otherwise 0
Scheme (define fac (lambda (n) (if (
n 0) 1 ( n (fac (- n 1))))))
7Advantages
- similar to traditional mathematics
- referential transparency makes programs more
readable - higher order functions give great flexibility
- concise programs
8Referential Transparency
- the value of a function depends only on the
values of its parameters - for example Haskell
- x x
- where x f a
9Evolution of Functional languagesLambda Calculus
- Alonzo Church
- Captures the essence of functional programming
- Formalism for expressing computation by functions
- Lambda abstraction
- In Scheme
- In Haskell
(lx. 1 x)
(lambda(x) ( 1 x)))
add1 Int -gt Int add1 x 1 x
10Lambda Calculus
- application of expressions
- reduction rule that substitutes 2 for x in the
lambda (beta reduction)
(lx. 1 x) 2
(lx. 1 x) 2 Þ ( 1 2) Þ 3
(lx. x x) ( 2 3) i.e. ( 2 3) / x)
11Lambda Calculus
- (lx.E)
- variable x is bound by the lambda
- the scope of the binding is the expression E
- (lx. y x)
- (lx. y x)2 Þ ( y 2)
- (lx. ((ly. ((lx. x y) 2)) x) y) Þ
12Lambda Calculus
- Each lambda abstraction binds only one variable
- Need to bind each variable with its own lambda.
- (lx. (ly. x y))
13Lisp
- McCarthy late 1950s
- Used Lambda Calculus for anonymous functions
- List processing language
- First attempt built on top of FORTRAN
14LISP
- McCarthys main contributions were
- the conditional expression and its use in writing
recursive functions
Scheme (define fac (lambda (n) (if (
n 0) 1 (if (gt n 0) ( n (fac
(- n 1))) 0))))
Scheme (define fac2 (lambda (n) (cond
(( n 0) 1) ((gt n 0) ( n (fac2
(- n 1)))) (else 0))))
Haskell fac Int -gt Int fac n n 0 1
n gt 0 fac(n-1) n otherwise 0
Haskell fac Int -gt Int fac n if n 0
then 1 else if n gt 0 then fac(n-1) n
else 0
15Lisp
- 2. the use of lists and higher order operations
over lists such as mapcar
Scheme (define mymap (lambda (f a b)
(cond ((and (null? a) (null? b)) '())
(else (cons (f (first a) (first b))
(mymap f (rest a)
(rest b)))))))
Haskell mymap (Int -gt Int-gt Int) -gt Int -gt
Int -gtInt mymap f mymap f (xxs)
(yys) f x y mymap f xs ys add Int -gt Int
-gt Int add x y x y
Scheme (mymap (3 4 6) (5 7 8))
Haskell mymap add 3, 4, 6 5, 7, 8
16Lisp
- cons cell and garbage collection of unused cons
cells
Scheme (cons 1 (3 4 5 7)) (1 3 4 5 7)
Haskell cons Int -gt Int -gt Int cons x xs
xxs
Scheme (define mymap (lambda (f a b)
(cond ((and (null? a) (null? b)) '())
(else (cons (f (first a) (first b))
(mymap f (first a)
(first b)))))))
17Lisp
- use of S-expressions to represent both program
and data - An expression is an atom or a list
- But a list can hold anything
-
18Scheme (cons 1 (3 4 5 7)) (1 3 4 5 7)
Scheme (define mymap (lambda (f a b)
(cond ((and (null? a) (null? b)) '())
(else (cons (f (first a) (first b))
(mymap f (first a)
(first b)))))))
19ISWIM
- Peter Landin mid 1960s
- If You See What I Mean
- Landon wrote can be looked upon as an attempt
to deliver Lisp from its eponymous commitment to
lists, its reputation for hand-to-mouth storage
allocation, the hardware dependent flavour of its
pedagogy, its heavy bracketing, and its
compromises with tradition
20Iswim
- Contributions
- Infix syntax
- let and where clauses, including a notion of
simultaneous and mutually recursive definitions - the off side rule based on indentation
- layout used to specify beginning and end of
definitions - Emphasis on generality
- small but expressive core language
21let in Scheme
- let - the bindings are performed sequentially
(let ((x 2) (y 3)) (let ((x 7) (z
( x y))) Þ ? ( z x)))
(let ((x 2) (y 3)) Þ ? ( x y))
22let in Scheme
- let - the bindings are performed in parallel,
i.e. the initial values are computed before any
of the variables are bound
(let ((x 2) (y 3)) (let ((x 7) (z
( x y))) Þ ? ( z x)))
(let ((x 2) (y 3)) Þ ? ( x y))
23letrec in Scheme
- letrec all the bindings are in effect while
their initial values are being computed, allows
mutually recursive definitions
(letrec ((even? (lambda (n)
(if (zero? n) t
(odd? (- n 1)))))
(odd? (lambda (n)
(if (zero? n) f
(even? (- n 1)))))) (even? 88))
24ML
- Gordon et al 1979
- Served as the command language for a proof
generating system called LCF - LCF reasoned about recursive functions
- Comprised a deductive calculus and an interactive
programming language Meta Language (ML) - Has notion of references much like locations in
memory - I/O side effects
- But encourages functional style of programming
25ML
- Type System
- it is strongly and statically typed
- uses type inference to determine the type of
every expression - allows polymorphic functions
- Has user defined ADTs
26SASL, KRC, and Miranda
- Used guards
- Higher Order Functions
- Lazy Evaluation
- Currying
add x y x y add 1
switch Int -gt a -gt a -gt a switch n x y n gt 0
x otherwise y
SASL fac n 1, n 0 n fac (n-1),
ngt0
multiplyC Int -gt Int -gt Int Versus multiplyUC
(Int, Int) -gt Int
Haskell fac n n 0 1 n gt0
n ( fac(n-1)
27SASL, KRC and Miranda
- KRC introduced list comprehension
-
- Miranda borrowed strong data typing and user
defined ADTs from ML
comprehension Int -gt Int comprehension ex
2 n n lt- ex
28COMP313AFunctional Programming (1)
29LISP
- McCarthys main contributions were
- the conditional expression and its use in writing
recursive functions
Scheme (define fac (lambda (n) (if (
n 0) 1 (if (gt n 0) ( n (fac
(- n 1))) 0))))
Scheme (define fac2 (lambda (n) (cond
(( n 0) 1) ((gt n 0) ( n (fac2
(- n 1)))) (else 0))))
Haskell fac Int -gt Int fac n n 0 1
n gt 0 fac(n-1) n otherwise 0
Haskell fac Int -gt Int fac n if n 0
then 1 else if n gt 0 then fac(n-1) n
else 0
30Lisp
- 2. the use of lists and higher order operations
over lists such as mapcar
Scheme (define mymap (lambda (f a b)
(cond ((and (null? a) (null? b)) '())
(else (cons (f (first a) (first b))
(mymap f
(rest a) (rest b)))))))
Haskell mymap (Int -gt Int-gt Int) -gt Int -gt
Int -gtInt mymap f mymap f (xxs)
(yys) f x y mymap f xs ys add Int -gt Int
-gt Int add x y x y
Scheme (mymap (3 4 6) (5 7 8))
Haskell mymap add 3, 4, 6 5, 7, 8
31Lisp
- cons cell and garbage collection of unused cons
cells
Scheme (cons 1 (3 4 5 7)) (1 3 4 5 7)
Haskell cons Int -gt Int -gt Int cons x xs
xxs
Scheme (define mymap (lambda (f a b)
(cond ((and (null? a) (null? b)) '())
(else (cons (f (first a) (first b))
(mymap f (first
a) (first b)))))))
32Lisp
- use of S-expressions to represent both program
and data - An expression is an atom or a list
- But a list can hold anything
-
33Scheme (cons 1 (3 4 5 7)) (1 3 4 5 7)
Scheme (define mymap (lambda (f a b)
(cond ((and (null? a) (null? b)) '())
(else (cons (f (first a) (first b))
(mymap f (first a)
(first b)))))))
34ISWIM
- Peter Landin mid 1960s
- If You See What I Mean
- Landon wrote can be looked upon as an attempt
to deliver Lisp from its eponymous commitment to
lists, its reputation for hand-to-mouth storage
allocation, the hardware dependent flavour of its
pedagogy, its heavy bracketing, and its
compromises with tradition
35Iswim
- Contributions
- Infix syntax
- let and where clauses, including a notion of
simultaneous and mutually recursive definitions - the off side rule based on indentation
- layout used to specify beginning and end of
definitions - Emphasis on generality
- small but expressive core language
36let in Scheme
- let - the bindings are performed sequentially
(let ((x 2) (y 3)) (let ((x 7) (z
( x y))) Þ ? ( z x)))
(let ((x 2) (y 3)) Þ ? ( x y))
37let in Scheme
- let - the bindings are performed in parallel,
i.e. the initial values are computed before any
of the variables are bound
(let ((x 2) (y 3)) (let ((x 7) (z
( x y))) Þ ? ( z x)))
(let ((x 2) (y 3)) Þ ? ( x y))
38letrec in Scheme
- letrec all the bindings are in effect while
their initial values are being computed, allows
mutually recursive definitions
(letrec ((even? (lambda (n)
(if (zero? n) t
(odd? (- n 1)))))
(odd? (lambda (n)
(if (zero? n) f
(even? (- n 1)))))) (even?
88))
39- Emacs was/is written in LISP
- Very popular in AI research
40ML
- Gordon et al 1979
- Served as the command language for a proof
generating system called LCF - LCF reasoned about recursive functions
- Comprised a deductive calculus and an interactive
programming language Meta Language (ML) - Has notion of references much like locations in
memory - I/O side effects
- But encourages functional style of programming
41ML
- Type System
- it is strongly and statically typed
- uses type inference to determine the type of
every expression - allows polymorphic functions
- Has user defined ADTs
42SASL, KRC, and Miranda
add x y x y silly_add x y x add 4 (3
a)
- Used guards
- Higher Order Functions
- Lazy Evaluation
- Currying
switch Int -gt a -gt a -gt a switch n x y n gt 0
x otherwise y
SASL fac n 1, n 0 n fac
(n-1), ngt0
multiplyC Int -gt Int -gt Int
Versus multiplyUC (Int, Int) -gt Int
Haskell fac n n 0 1 n gt0
n fac(n-1)
43SASL, KRC and Miranda
- KRC introduced list comprehension
-
- Miranda borrowed strong data typing and user
defined ADTs from ML
comp_example Int -gt Int comp_example ex
2 n n lt- ex
44The Move to Haskell
- Lots of functional languages in late 1970s and
1980s - Tower of Babel
- Among these was Hope
- strongly typed
- polymorphism but explicit type declarations as
part of all function definitions - simple module facility
- user-defined concrete data types with pattern
matching
45The Move to Haskell
- 1987 considered lack of common language was
hampering the adoption of functional languages - Haskell was born
- higher order functions
- lazy evaluation
- static polymorphic typing
- user-defined datatypes
- pattern matching
- list comprehensions
46Haskell
- as well
- module facility
- well defined I/O system
- rich set of primitive data types
47Higher Order Functions
- Functions as first class values
- stored as data structures, passed as arguments,
returned as results - Function is the primary abstraction mechanism
- increase the use of this abstraction
- Higher order functions are the guts of
functional programming
48Higher Order FunctionsComputations over lists
- Mapping
- add 5 to every element of a list.
- add the corresponding elements of 2 lists
- Filtering
- Selecting the elements with a certain property
- Folding
- Combine the items in a list in some way
49List Comprehension
- Double all the elements in a list
- Using primitive recursion
- doubleAll Int -gt Int
- doubleAll
- doubleAll xxs 2 x doubleAll xs
- Using list comprehension
- doubleAll Int -gt Int
- doubleAll xs 2 x x lt- xs
50Primitive RecursionversusGeneral Recursion
- sum Int -gt Int
- sum 0
- sum (xxs) x sum xs
- qsort Int -gt Int
- qsort
- qsort (x xs)
- qsort y ylt-xs , yltx x qsort
y y lt- xs , ygtx
51COMP313AFunctional Programming (3)
52Higher Order Functions
- Functions as first class values
- stored as data structures, passed as arguments,
returned as results - Function is the primary abstraction mechanism
- increase the use of this abstraction
- Higher order functions are the guts of
functional programming
53Higher Order FunctionsComputations over lists
- Mapping
- add 5 to every element of a list.
- add the corresponding elements of 2 lists
- Filtering
- Selecting the elements with a certain property
- Folding
- Combine the items in a list in some way
54List Comprehension
- Double all the elements in a list
- Using primitive recursion
- doubleAll Int -gt Int
- doubleAll
- doubleAll xxs 2 x doubleAll xs
- Using list comprehension
- doubleAll Int -gt Int
- doubleAll xs 2 x x lt- xs
55Primitive RecursionversusGeneral Recursion
- sum Int -gt Int
- sum 0
- sum (xxs) x sum xs
- qsort Int -gt Int
- qsort
- qsort (x xs)
- qsort y ylt-xs , yltx x qsort
y y lt- xs , ygtx
56Some Haskell Syntax
Write a function to calculate the maximum of
three numbers i.e. maxThree Int -gt Int -gt Int
maxThree x y z x gt y x gt z x
y gt z y otherwise
z
57Write a function to calculate the average of
three numbers averageThree Int-gt Int -gt Int
-gt Float averageThree x y z (x y z) /
3
funny x x x peculiar y y funny x x
x peculiar y y
58Tuples and Lists
Examples of lists 345, 67, 34, 9 a,
h, z Fred, foo Examples of
tuples (Fred, 471) (apples, 3.41)
(baseball_bat, aluminium 60.0)
Strings are lists of char i.e. Char f,
r, e, d fred
59Types
type album (String, String, Int) type
collection album
60Some more examplespattern matching
Write a function which will extract all the even
numbers from a list
Lets first create an isEven predicate isEven n
(n mod 2 0)
evenList evenList ex n n lt- ex ,
isEven n
evenList2 evenList2 (xxs) isEven x
x evenList2 xs otherwise
evenList2 xs
61Write a function listpairs which returns a list
of the pairs of corresponding elements in two
lists listpairs a -gt b -gt
(a,b) gtgtlistpairs 3, 4, 5 6, 7, 8 gtgt
(3,6), (4, 7), (5,8) Would this
work? listpairs xs ys (m,n) m lt- xs, n lt-
ys
62COMP313AFunctional Programming (4)
63Lecture Outline
- A little bit of revision
- Higher Order Functions
- Functions as arguments
- Functions as values
64Some more examplespattern matching
Write a function which will extract all the even
numbers from a list
Lets first create an isEven predicate isEven n
(mod n 2 0)
evenList evenList ex n n lt- ex ,
isEven n
evenList2 evenList2 (xxs) isEven x
x evenList2 xs otherwise
evenList2 xs
65List Comprehension
- Given a function isDigit
- isDigit Char -gt Bool
- which returns True if a character is a digit,
write a function digits which will find all the
digits in a string - digits str
- aChar aChar lt- ,
66Map
- double x 2 x
- doubleAll xs map double xs
- doubleAll 4, 5, 6
- 8, 10, 12
67Implementing Map using List Comprehension
- map (a -gt b) -gt a -gt b
- map f xs f x x lt- xs
68Functions as Argumentsfold
- gt foldr1 () 4, 5, 6
- gt 15
69foldr1 (non empty list)
- foldr1 (a -gt a -gt a) -gt a -gt a
- foldr1 f x x
- foldr1 f (xxs) f x (foldr f xs)
-
What does this tell us abut the characteristics
of function f Produces an error when given an
empty list How could we define foldr to work
with an empty list
70foldr f s s foldr f s (xxs)
f x (foldr f s xs)
711 More Higher Order FunctionFilter
- isEven n
- (mod n 2 0)
- gt filter isEven 2, 4, 6, 7, 1
- gt??
- isEven returns a predicate (returns a Bool)
72Implementing Filter using list comprehension
filter p xs x x lt- xs, p x p returns a
Bool
73Some exercises
- Write functions to
- Return the list consisting of the squares of the
integers in a list, ns. - Return the sum of squares of items in a list
- Check whether all the items of a list are greater
than zero using filter
74Functions as values
- functions as data
- function composition sqr
(succ 5) -
- concat (map
bracketedWithoutVowels xs) - concatenates a list of lists
into a single list - flattens a list
75Functions as valuesFunction Composition (.)
- (sqr . succ)
5 - The output of one function becomes the input of
another
f.g
a
a
b
c
c
g
f
(.) (b -gt c) -gt (a -gtb) -gt (a -gt c)
type of (f.g)
type of f
type of g
76f . g x as opposed to (f . g) x Function
application binds more tightly than
composition e.g not . not True or succ
.pred 5
77Functions as values and results
- twice fun ( fun . fun )
- fun is a function
- The result is fun composed with itself
- For this to work fun has to have ..
- and twice ( ) -gt ( )
- gt twice succ 2
- gt 4
78Expressions Defining Functions
- addnum Int -gt (Int -gt Int)
- addnum n addN
- where
- addN m n m
- When addnum 10 say is called returns a function
addN which adds 10 to m
79Maingt addNum 4 5 9 Maingt addNum 4 ERROR -
Cannot find "show" function for Expression
addNum 4 Of type Integer -gt Integer
80test Int -gt Int -gt Int test x y x gt y
f y otherwise 4
where f addnum 4
81COMP313AFunctional Programming (4)
82Lecture Outline
- A little bit of revision
- Higher Order Functions
- Functions as arguments
- Functions as values
83Some more examplespattern matching
Write a function which will extract all the even
numbers from a list
Lets first create an isEven predicate isEven n
(mod n 2 0)
evenList evenList ex n n lt- ex ,
isEven n
evenList2 evenList2 (xxs) isEven x
x evenList2 xs otherwise
evenList2 xs
84List Comprehension
- Given a function isDigit
- isDigit Char -gt Bool
- which returns True if a character is a digit,
write a function digits which will find all the
digits in a string - digits str
- aChar aChar lt- ,
85Map
- double x 2 x
- doubleAll xs map double xs
- doubleAll 4, 5, 6
- 8, 10, 12
86Implementing Map using List Comprehension
- map (a -gt b) -gt a -gt b
- map f xs f x x lt- xs
87Functions as Argumentsfold
- gt foldr1 () 4, 5, 6
- gt 15
88foldr1 (non empty list)
- foldr1 (a -gt a -gt a) -gt a -gt a
- foldr1 f x x
- foldr1 f (xxs) f x (foldr f xs)
-
What does this tell us abut the characteristics
of function f Produces an error when given an
empty list How could we define foldr to work
with an empty list
89foldr f s s foldr f s (xxs)
f x (foldr f s xs)
901 More Higher Order FunctionFilter
- isEven n
- (mod n 2 0)
- gt filter isEven 2, 4, 6, 7, 1
- gt??
- isEven returns a predicate (returns a Bool)
91Implementing Filter using list comprehension
filter p xs x x lt- xs, p x p returns a
Bool
92Some exercises
- Write functions to
- Return the list consisting of the squares of the
integers in a list, ns. - Return the sum of squares of items in a list
- Check whether all the items of a list are greater
than zero using filter
93Functions as values
- functions as data
- function composition sqr
(succ 5) -
- concat (map
bracketedWithoutVowels xs) - concatenates a list of lists
into a single list - flattens a list
94Functions as valuesFunction Composition (.)
- (sqr . succ)
5 - The output of one function becomes the input of
another
f.g
a
a
b
c
c
g
f
(.) (b -gt c) -gt (a -gtb) -gt (a -gt c)
type of (f.g)
type of f
type of g
95f . g x as opposed to (f . g) x Function
application binds more tightly than
composition e.g not . not True or succ
.pred 5
96Functions as values and results
- twice fun ( fun . fun )
- fun is a function
- The result is fun composed with itself
- For this to work fun has to have ..
- and twice ( ) -gt ( )
- gt twice succ 2
- gt 4
97Expressions Defining Functions
- addnum Int -gt (Int -gt Int)
- addnum n addN
- where
- addN m n m
- When addnum 10 say is called returns a function
addN which adds 10 to m
98Maingt addNum 4 5 9 Maingt addNum 4 ERROR -
Cannot find "show" function for Expression
addNum 4 Of type Integer -gt Integer
99test Int -gt Int -gt Int test x y x gt y
f y otherwise 4
where f addnum 4
100COMP313A Programming Languages
- Functional Programming (5)
101Lecture Outline
- Higher order functions
- Functions as arguments
- Some recapping and exercises
- Some more functions as data and results
102Expressions Defining Functions
- addnum Int -gt (Int -gt Int)
- addnum n addN
- where --
local definition - addN m n m
- When addnum 10 say is called returns a function
addN which adds 10 to m
103test Int -gt Int -gt Int test x y x gt y
somefun f y otherwise 4
where f addnum 4
104Lambda in Haskell
\m -gt n m addNum n (\m -gt n m)
Write a function test n that returns a function
which tests if some argument is lt to n. Use a
lambda.
105Partial Application of Functions
add Int -gt Int -gt Int add x y xy
4
5
4
106Partial Application of Functions
add4 Int -gt Int add4 xs map (add 4) xs
add4 (Int -gt Int) add4 map (add 4)
How would we use partial applications of
functions to get the same result as the addNum
n example?
107Types of partial applications
- The type of function is
- t1 -gt t2 -gt tn -gt t
- and it is applied to arguments
- e1 t1, e2 t2 , ek tk
- if k lt n (partial application) then cancel the
ones that match t1 tk - leaving
- tk1 -gt tk2 -gt -gt tn
108Types of Partial Function Application
add Int -gt Int -gt Int add 2 Int
-gtInt add 2 3 Int
109Operator Sections
filter (gt0) . map (1) Find operator sections
sec1 and sec2 so that map sec1. filter sec2 Has
the same effect as filter (gt0) . map (1)
110Partial Application of Functionsand Operator
Sections
- elem Char -gt Char -gt Bool
- elem ch whitespace
- where whitespace is the string \t\n
111Partial Application of Functionsand Operator
Sections
- i.e. whitespace \t\n
- The problem with partial application of function
is that the argument of interest may not always
be the first argument - So
- member xs x elem x xs
- and
- member whitespace
- Alternatively we can use a lambda function
- \ch -gt elem ch whitespace
112Partial Application of Functionsand Operator
Sections
- To filter all non-whitespace characters from a
string - filter (not . member whitespace)
- filter (\ch -gt not (elem ch whitespace))
113Write a recursive function to extract a word from
a string
whitespace \n\t getword String -gt
String getword getword (x xs)
--how do we know we have a word
-- otherwise build the
word
- - recursively
getword the quick brown
114Write a recursive function to extract a word from
a string
Can write something more general - pass the
test as an argument getUntil (a -gt Bool)
-gt a -gt a getUntil p getUntil
p (xxs) p x otherwise
x getUntil p xs
115Write a recursive function to extract a word from
a string
Okay but now how do we get a word getWord xs
getUntil p xs where
- - local definition
p x member whitespace x
116Write a recursive function to extract a word from
a string
But we dont really need the local definition We
can use our partial function instead getWord xs
getUntil p xs where
- - local definition
p x member whitespace x getWord xs
getUntil (member whitespace) xs
117Write a recursive function to extract a word from
a string
Finally The last word getWord getUntil
(member whitespace) ---get characters until a
whitespace is found
118Currying and Uncurrying
- functions of two or more arguments take arguments
in sequence, one at a time. - this is the curried form.
- named after Haskell Curry
- Uncurried version puts the arguments into a pair
- addUC (Int, Int) -gt Int
- addUC (x,y) (x y)
119curried versus uncurried
- Curried has neater notation
- Curried permits partial application
- Can easily convert from one to the other
curry f (x y) f x y uncurry f x y f (x y)
120Type Checking in HaskellMonomorphic Type Checking
- Expressions
- literal, variable, constant, function applied to
some arguments - type checking function application
- what do we need to consider
121f must have a function type t
e must have type s
f e
the result has type t
122ord c Int 3Int
ord c Int False
123Type Checking Function Definitions
fib Int -gtInt fib n n 0 0 n
1 1 n gt1 fib (n-2) fib (n-1)
- Each of the guards must be of type ?
- The value returned in each clause must be of type
? - The pattern n must be consistent with type
argument ?
124COMP313A Programming Languages
125Lecture Outline
- Conceptual foundations of Logic Programming
- The Basics of Logic Programming
- Predicate Calculus
- A little bit of logic programming
- Prolog
126Conceptual Foundations
- What versus how
- specification versus implementation
- Declarative Programming
- Programmer declares the logical properties that
describe the property to be solved - From this a solution is inferred
- Inference engine
127An example
Searching for an element in a list Predicate
is_in(x,L) true whenever element x is in the list
L.
For all elements x and lists L is_in(x,L) IFF L
x or L L1 . L2
and (is_in (x,L1) or is_in(x,
L2))
128Example continuedImplementation
- Need to know how to split a list into right and
left sublists - How to order the elements stored in the list
129A solution in C
int binary_search(const int val, const int size,
const int array) int high, low, mid if size
lt 0 return (-1) high size low
0 for() mid (high low) / 2 if
(mid low) return (val ! arraylow)
?-1mid if (val lt arraymid) high
mid else if (val gt arraymid) low
mid else return mid
130A Declarative Solution
- Given an element x and a list L, to prove that x
is in L, - proceed as follows
- Prove that L is x
- Otherwise split L into L1 . L2 and prove one of
the following - (2.1) x is in L1, or
- (2.2) x is in L2
131A sorting example
A predicate sort(X,Y) Sort(X,Y) is true if the
nonempty list Y is the sorted version of X Use
two auxiliary predicates permutation(X,Y) and
is_sorted(Y)
For all integer lists X,Y sort(X,Y) iff
permutation(X,Y) and sorted(Y)
132Logic and Logic Programming
- First-order predicate calculus
- Logic statements
- Examples
- John is a man. man(John).
- John is a human. human(John).
- Tristan is the son of Margaret.
son(Margaret,Tristan). - A horse is a mammal. loathes(Margaret,
Heavy_Metal). - 0 is a natural number . natural(0).
- Mammals have four legs and no arms or two legs
and two arms. - For all X, mammal (x) -gt legs(x,4) and arms(x,0)
or legs(x,2) and arms(x,2). - Humans have two legs and two arms.
- For all X, human(x) -gt legs(x,2) and arms(x,2).
- If x is a natural number then so is the successor
of x. - For all x, natural(x) -gt natural(successor(x)).
133First-Order Predicate Calculus
- Constants
- Predicates
- Functions
- Variables that stand for as yet unamed quantities
- Atomic sentences
- Connectives construct more complex sentences
- Quantifiers
- Punctuation
- Arguments to predicates can only be terms
variables, constants and functions
134First-Order Predicate Calculus cont
- Quanitifiers
- Universal, existential
- Express properties of entire collections of
objects - Universal quantifiers make statements about every
object, "x - A cat is a mammal
- "x Cat(x) Þ Mammal(x)
- Cat(Spot) Þ Mammal(Spot) Ù
- Cat(Rebecca) Þ Mammal(Rebecca) Ù
- Cat(Felix) Þ Mammal(Felix) Ù
- Cat(Richard) Þ Mammal(Richard) Ù
- Cat(John) Þ Mammal(John) Ù
-
135First-Order Predicate Calculus cont
- Existential Quantifiers make statements about
some objects, x - Spot has a sister who is a cat
- x Sister(x, Spot) Ù Cat(x)
- (Sister(Spot, Spot) Ù Cat(Spot)) Ú
- (Sister(Rebecca, Spot) Ù Cat(Rebecca)) Ú
- (Sister(Felix, Spot) Ù Cat(Felix)) Ú
- (Sister(Richard, Spot) Ù Cat(Richard)) Ú
- (Sister(John, Spot) Ù Cat(John)) Ú
136First-Order Predicate Calculus cont
- Connections between and "
- Negation
- Everyone dislikes rugby º Noone likes rugby
- "x ØLikes (x, rugby) º Øx Likes(x, rugby)
- Everyone likes icecream º Noone dislikes icecream
- "x Likes (x, icecream) º Øx ØLikes(x, icecream)
137First-Order Predicate Calculus cont
- " is a conjunction over the universe of objects
- Is a disjunction over the universe of objects
- "x ØP º Øx P
- Ø "x P º x ØP
- "x P º Øx ØP
- Ø "x ØP º x P
138De Morgans Laws
- ØPÙØQ º (PÚQ)
- Ø(PÙQ) º ØPÚØQ
- PÙQ º Ø(ØPÚØQ)
- Ø(ØPÙØQ) º PÚ Q
139Using First-Order Predicate Calculus
- Marcus was a man
- Marcus was a Pompeian
- All Pompeians were Romans
- Caesar was a ruler
- All Romans were either loyal to Caesar or hated
him
140- Everyone is loyal to someone
- People only try to assassinate rulers they are
not loyal to - Marcus tried to assassinate Caesar
- Was Marcus loyal to Caesar?
- Prove Ø loyalto(Marcus, Caesar)
141- Turn the following sentences into formulae in
first order predicate logic - John likes all kinds of food
- Apples are food
- Chicken is food
- Anything anyone eats and isnt killed by is food
- Bill eats peanuts and is still alive
- Sue eats everything Bill eats
- Prove that John likes peanuts using backward
chaining
142A little bit of Prolog
- Objects and relations between objects
- Facts and rules
- parent(pam, bob). parent(tom,bob).
- parent(tom, liz). parent(bob, ann).
- parent(bob, pat). parent(pat, jim).
- ? parent(bob, pat).
- ? parent(bob, liz).
- ? parent(bob, ben).
- ? parent(bob, X).
- ? parent(X, Y).
143Prolog
- grandparent (X,Y) - parent(X, Z), parent(Z, Y).
- For all X and Y
- X is the grandparent of Y if
- X is a parent of Z and
- Z is a parent of Y
- sister (X,Y) - parent(Z, X), parent(Z, Y),
female(X) - For all X and Y
- X is the sister of Y if
- Z is the parent of both X and Y and
- X is a female