You are on page 1of 59

Functional 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.

The same as:


(2+3)*(1+2)

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

Define functions by lambda expression.


o Cube (x) ( (x) (* x x x ))
OR else can define like this.
o (Define (cube x) (* x x x ))

10
Functions
To define a function,
(Define (function_name parameters)
(expression)
)
Output functions,
(Display expression)
or
(NEWLINE)

11
IF Condition

(IF predicate then_expression else_expression)

(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.

(Cons ‘A ‘()) returns (A)


(Cons ‘A ‘(B C)) returns (A B C)
(Cons ‘(Car lis) ‘(Cdr lis))
out put is identical to lis
(Cons ‘A ‘B) returns (A.B)

16
LIST function

Constructs a list from a variable number if


parameters.

(List ‘apple ‘orange ‘grape)


returns (apple orange grape)

17
EQ? function
Takes two symbolic atoms as parameters .It
returns #T if both parameters are the same. Other
wise it returns #F.

(EQ? ‘A ‘A) returns #T


(EQ? ‘A ‘B) returns #F
(EQ? ‘A ‘(A B)) 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.

(Null? ‘(A B)) returns #F


(Null? ()) returns #T
(Null? ‘A) returns #F
(Null? ‘(())) returns #F

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

 Write a scheme function for Fibonacci.


Eg. 1 1 2 3 5
 (Define (fab n)
(cond ((=n 1) 1)
(else (+(fib (- n 1)) (fib(- n 2))))
))
21
Write a function in scheme called sum that computes the
addition of numbers 1 to n.
 
(define sum (lambda (val)
(cond
((= val 1) 1)
(else (+ val (sum (- val 1)))
)
))
  Eg. (sum 5)  15 
Because 1+2+3+4+5

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.

(define (member atom list)


(cond((null? list) #F)
((= atom (car list) # T)
(else (member atom (cdr list))
))
26
Define a function named add1nums which returns a new
list of numbers containing all the numbers in the original
list increased by 1 and none of the non numbers.
Hint: Assume that number list is taken from numberP
function.
(Define (add1nums list)
(cond((null? list) ‘())
((numberP (car list)) (cons’(+ 1 (car list)) ‘(add1nums
(cdr list))))
(else (add1nums(cdr list)))
))

27
Define length function.
Eg. (1 2 3 4 )  4

(Define (length list))


(cond (null? list) 0)
(else (+ 1(length (cdr list))))
))

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.

(Define (total-reverse list)


(cond ((null? list) ‘())
((list? (car list)) (cons ‘(total-reverse(cdr list))(total-
reverse(car list))))
(else (cons’(total-reverse (cdr list)) (car list)))
)
)

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)

(Define append list1 list2)


(cond ((null? List1) list2)
(else (cons’(car list1) (append (cdr list1)list2)))
))

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)

(Define (my_interleave list1 list2)


(if (null? list1) list2
(cons (car list1) (my_interleave list2 (cdr list1)))))

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.

(Define (append lis1 lis2)


(Cond ((null? Lis1) lis2)
(else (cons (car lis1) (append (cdr lis1) lis2)))
)
)

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.

(Define (insert-right-1st a b list)


(Cond((= (car list ) b) (Cons ‘(car list) ‘(Cons ‘(a) ‘(cdr list))))
(else (Cons ‘(car list) ‘(insert-right-1st a b (cdr lisr))))
)
)

Eg: (insert-right-1st ‘not ‘ does ‘(my dog does have fleas ))


returns (my dog does not have fleas)

35
Logical programming
Logic programming is the use of mathematical logic
for computer programming.

It adopts a different approach to problem solving to


both procedural programming and functional
programming.

logic programming requires a logical declarative


description of the nature of the problem. 

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.

Clauses with bodies are called rules .An example


of a rule is:
c:-a;b.
color(X,C):-part_of(X,Y),color(Y,C).
Clauses with empty bodies are called facts. (A fact is
a rule whose body is always true). An example of a
fact is:
dog(tommy).
40
Prolog Basics
The basic unit of Prolog programming is a Horn
clause, a clause with at most one positive literal
The Prolog rule syntax is of the form:
p:-q1, q2, ..., qn .
where p, qi , i=1, . . . ,n are literals.
The above formula is interpreted as: If (q1 and q2
and ... and qn) then p.
 In Prolog, a comma is used to indicate the logical
AND

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

father(X, Y) :- male(X), parent(X, Y).


means that X is the father of Y in case it is both true that X is
male and that X is the parent of Y.
Some rules are very simple, such as
child(Y, X) :- parent(X, Y).
42
Knowledge base examples
Collection of facts
woman(Amanda)
woman(Jody)
playsAirGuitar(Jody)
State that Amanda and Jody are woman and Jody plays
air guitar

We can ask Prolog apple is a fruit by posing the query


?-fruit(apple) -> Yes

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]

[ ] - this is a special list, it is called the empty list


because it contains nothing.

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

list. This is done by using recursion. The search can either


stop when we find a particular item at the start of the list or
when we have searched the whole list, in which case the list
to be searched will be the empty list. In order to do this, we
have to be able to selectively pull the list apart. We have
already seen how we can go about doing this.

This method constitutes the basis of the searching method.


We shall use it to pull apart a list, looking at the first item
each time, recursively looking at the tail, until we reach the
empty list [], when we will stop.
48
Questions……
A Prolog definition to get the factorial of an element

fact(0,1).
fact(N,X):-N1 is N-1, fact(N1,X1), X is N*X1.

A Prolog definition to get the power function

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

eliminate([ ],[ ]).


eliminate([X|L],M):-member(X,L),eliminate(L,M).
eliminate([X|L],[X|M]):-eliminate(L,M).

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

You might also like