Functional Programming and Logical Programming
Functional Programming and Logical Programming
and
Logical Programming
Content
Functional Programming
Introduction
Scheme
Questions on scheme
Logical programming
Introduction
Prolog
Questions on prolog
Comparison of functional and logical programming
2
Functional Programming
Functional programming language is based on
mathematical functions.
functional languages are applicative because they
achieve their effect by the applications of functions
In purely functional programming, the concept of
assignment does not exist.
In function programming there is no problem of
side affects.
3
Advantage
It doesn’t have aliasing problem.
It can be easily used for parallel machines.
Disadvantage
Thereis no dedicated hardware, generally
implemented with interpreters.
4
Scheme
Scheme is dialect of Lisp.
It is a pure functional programming language.
It was developed in MIT in 1975 by Sussman and
Steele.
Scheme is generally used for teaching purposes.
It uses static scoping
Scheme permits two types of objects,
Atoms
Lists
5
Atoms can be either,
Numeric atoms
28
-14.23
Quoted string atoms
‘Any String
List is a sequence of atoms separated by blanks and
parentheses.
(1 2 3) ((a b) c d)
Simple list is a list that doesn’t have a sublist.
eg: (a b c)
6
Numeric atoms and Primitive
Functions
Primitive arithmetic functions such +,-,* and / are
available in scheme.
Scheme can perform arithmetic on the contents of
atoms.
(+ 2 5) (+ 2 5 7)
7 14
Scheme does not have any precedence rules for it’s
math operations – instead to control the order of
computation by using parentheses.
7
• A function call is written as:
(operator arg1 arg2 … argn)
• For example:
(+ 2 3) means 2 + 3
The + operator
(and other arithmetic)
operators can take
any number of
arguments.
8
‘qoute’ function causes the interpreter not to evaluate
the data, return the data without a change.
(quote (+ 2 5)) (+ 2 5) becomes a list
we can use ‘(A B) instead of (quote (A B))
Comments begin with a semicolon and continue until the
end of line.
(define pi 3.14) ;bind a variable to a value
Scheme ignores the distinction between uppercase and
lower case.
Names in scheme can have letters, digits, special
characters except parenthesis ; they must not begin with a
digit.
9
Covert these mathematical functions to
scheme
(2+5)*(7-3) In scheme we write this like this.
o (*(+25)(-73)) 28
-b + b2 - 4ac
2a
o ( / (+( -b )(sqrt (-(sq b)(*4 a c)))) (*2 a))
10
Functions
To define a function,
(Define (function_name parameters)
(expression)
)
Output functions,
(Display expression)
or
(NEWLINE)
11
IF Condition
(Define (factorial n)
(If (= n 0)) 1
(* n (factorial (- n 1)))
)
12
COND function
this is a multiple selector based on mathematical
expressions
((Cond (predicate_1 expression)
(predicate_2 expression)
…..
(predicate_n expression)
[(Else expression)]
)
13
Eg: (Define (Compare x y)
(Cond ((> x y) ‘x is greater than y’ )
((< x y) ‘x is lesser than y’)
(Else ‘x and y are equal’)
)
)
14
Use of ‘CAR’ and ‘CDR’
CAR function
Returns the first element in a given list
eg: (Car ‘(A B C)) returns A
(Car ‘((A B) C D)) returns (A B)
CDR function
Returns the remainder in a given list after the car has been
removed
eg: (Cdr ‘(A B C)) returns (B C)
(Cdr ‘((A B) C D)) returns (C D)
15
CONS function
Builds a list from two arguments, first is either an
atom or a list , the second is usually a list.
Insets it’s first parameter as the new car of it’s
second parameters.
16
LIST function
17
EQ? function
Takes two symbolic atoms as parameters .It
returns #T if both parameters are the same. Other
wise it returns #F.
18
EQV? Function
Testtwo atoms for equality when it is not known
whether they are symbolic or numeric .
EQ? or = is faster than EQV?
LIST? Function
Returns #T if it’s single argument is a list #F
otherwise
19
NULL? Function
Tests if it’s parameters to determine whether it is empty and
returns #T if it is, #F other wise.
20
Questions……
Write a scheme function for factorial.
Eg. 5=5*4*3*2*1 5*4!
(Define (factorial x) Base case (Stop at this point)
(cond ((=x 0) 1)
((=x 1) 1)
Recursion is used here
(else(*x (factorial (- x 1))))
))
22
Write a scheme function (compare x y).This compares two
numeric types atoms and displays the appropriate phrase.
Eg. (compare 3 5) y>x
(define ((compare x y)
(cond ((< x y) (Display “x is less than y”))
((> x y) (Display “x is greater than y”))
(else (Display “x and y are equal”))
))
23
Write an exponential function in scheme.
Eg. (exp x y) 23 y
x
(define ((exp x y)
(cond ((= y 1 ) x)
((= y 0) 1)
(else ( * x (exp x ( - y 1)))
))
24
This is a scheme function to get the SUM of the list.
(define (sum list)
(if (null? list) 0
(+ (car list) (sum (cdr list)))))
Define a function to return list of numbers that
squares all the numbers in the list.
(define (my_square_member list)
(if (null? list) '()
(cons (*(car list) (car list)) (my_square_member
(cdr list)))))
25
Scheme function called member takes an atom and a
simple list, It returns #T if the atom is in the list, otherwise
it returns #F. Write scheme code to implement this
function.
e.g member is (scheme is simple function language)
returns #T.
27
Define length function.
Eg. (1 2 3 4 ) 4
28
Write a recursive function to return the last item in a
given list.
Hint : make use of the length function
(define (last list)
(cond ((= (length list) 1)(car list))
(else (last (cdr list)))
))
29
Define a Scheme function named total-reverse that will take a list
as the parameter and returns a list in which all elements are
reversed (including the nested lists). For example if the function
total-reverse is applied on the list ((a b) c (d e)) the resulting list
would be ((e d) c (b a)). You may assume that the definitions for
the list and append functions are already available.
30
Write a scheme function to calculate how many non zero values are there in a given list.
(define (nonzero l)
(cond
((null? l) 0)
(else
(+ (if (= ‘0 (car l))
0
1
)
(nonzero (cdr l))
) )
)))
e.g.(nonzero ‘(4 1 0 2 0 1 3)) 5
31
Write a scheme function to append two lists and
return a list.
Eg. (1,2,3) ((ab), c,d) (1,2,3,(ab),c,d)
32
Write a function to interleave two lists and return a
list.
Eg. (my_interleave '(1 2 3 4) '(a b c d))
Output should be like this. (1 a 2 b 3 c 4 d)
33
Write a scheme function named append ,that takes
two given list arguments and construct a list
containing all the elements of two given arguments.
34
Give the scheme definition of a function called insert-
right-1st that takes 3 arguments. The function searches the
first occurrence of the second argument in the input list
and inserts the first argument to it’s right.
35
Logical programming
Logic programming is the use of mathematical logic
for computer programming.
36
Advantages
They are very high level (specify what instead of how)
They are simple and easy to learn
They are well suited for parallel machines.
Disadvantages
slowness of execution
37
Introduction to Prolog
Prolog is a general purpose logic programming
language associated with artificial intelligence and
computational linguistics.
Prolog was developed in 1972 by Alain Colmerauer
The program logic is expressed in terms of relations,
represented as facts and rules.
Modern Prolog environments support creating
graphical user interfaces, as well as administrative and
networked applications.
38
Data types in Prolog
Prolog's single data type is the term. Terms are either atoms,
numbers, variables or compound terms
Eg: x, blue, 'some atom'.
Numbers can be floats or integers.
Variables are denoted by a string consisting of letters, numbers
and underscore characters, and beginning with an upper-case
letter or underscore.
Eg: A,B,1,2
A compound term is composed of an atom called a "functor"
followed by a sequence of arguments. which are again terms.
Compound terms are ordinarily written as a functor followed by a
comma-separated list of argument terms.
Eg: playAirGuitar(Jody)
39
Rules and facts
There are two types of clauses: Facts and rules.
41
Knowledge base in Prolog
A collection of facts and rules is called a knowledge base
A knowledge base, as represented by the prolog program has
even more: in addition to the information (called facts in
prolog), and the ability to extract information, there is also the
ability to deduce new facts using prolog rules
For example, the rule
43
Knowledge base examples
Likes(bob,fish)
This states that bob likes fish
father(louis,al) U father(louis,violet)
This states that louis is al’s father or violet’s father
married(joe,elsie).
married(fred,doris).
married(darren,tracey).
husband(X) :- married(X,_).
husband(X)- ioe,fred,darren
44
Lists
A very common data-structure in Prolog is the list.
They always start and end with square bracket
Prolog also has a special facility to split the first part
of the list (called the head) away from the rest of the
list (known as the tail).
We can place a special symbol | (pronounced 'bar') in
the list to distinguish between the first item in the list
and the remaining list.
For example, consider the following.
[first,second,third] = [A|B] where A = first and
B=[second,third]
45
Here are some examples of simple lists
[a,b,c,d,e,f,g]
[apple,pears,bananas, grapes]
46
Lists examples
[a,b,c] unifies with [Head|Tail] resulting in Head=a and Tail=[b,c]
Consider the following fact.
p([H|T], H, T).
Lets see what happens when we ask some simple queries.
?- p([a,b,c], X, Y).X=a
Y=[b,c]Yes it match
?- p([], X, Y). No
?- p([a], X, Y).
X=a
Y=[] Yes
47
In order to search a list, Prolog inspects the first item in a list
and then goes on to repeat the same process on the rest of the
List Searching
fact(0,1).
fact(N,X):-N1 is N-1, fact(N1,X1), X is N*X1.
pow(X,0,1).
pow (X,Y,Z) :- Y1 is Y-1 , pow (X,Y1,Z1) , Z is X*Z1
49
Write a function called member, to determine if a given
atom belongs to a given list.
member(X,[X|L]).
member(X,[Y|L]) :- member(X,L).
50
Write a Prolog definition to get the length of a list
length ([],0).
length ([H|T],X):- length (T,X1) , X is X1+1
Queries
?length([1,2,3], N). N=3
51
Write a prolog function called append to concatenate
two given lists.
append([], L, L).
append([X|L],M,[X|N]):-append(L,M,N).
52
Write a prolog function to get the reverse of a list.
reverse([],[]).
reverse([H|T],R):-reverse(T,RT),append(RT,[H],R).
queries:
?reverse([a,b,c],M). M=[c,b,a]
53
Write a prolog function to get the reverse of a list.
reverse([],[]).
reverse([H|T],R):-reverse(T,RT),append(RT,[H],R).
queries:
?reverse([a,b,c],M). M=[c,b,a]
54
A Prolog definition to delete an atom of a list
delete(X,[],[]).
delete(X,[X|L],M):-delete(X,L,M).
delete(X,[Y|L],[Y|M]):-not(X=Y),delete(X,L,M).
queries:
?delete(a,[a,b,c,d,e],M) M =[b,c,d,e];
55
Write a prolog function to eliminate a duplicate a
duplicate elements form a list
queries
?eliminate([2,3,2,4,3],L). L=[2,4,3]
56
Comparison of functional and
logical programming
Functional Programming (Scheme)
– Based on the mathematical concept of a function:
plus(3, 5) 8
teaches(doug, s2004) cs314
• Logic Programming (Prolog):
– Based on the mathematical concept of a relation:
plus(3, 5, 8). True
teaches(doug, s2004, cs314). statements
57
Group members,
DIT-08-M2-1360 P.H.C.L.Premachandra
DIT-09-M4-1763 D.A.Y.Thantriwattage
DIT-09-M4-1786 J.H.A.D.K.Jayasekara
DIT-09-M4-1790 S.D.Gunaratne
58
Thank you !
59