59
Functional Programming and Logical Programming

Functional Programming and Logical Programming

Embed Size (px)

DESCRIPTION

This slide contains introduction to Functional programming,Scheme,Questions on scheme,Introduction to Logical programming,Prolog ,Questions on Prolog and a Brief comparison of Functional and Logical Programming

Citation preview

Contenty Functional Programmingy y y

Introduction Scheme Questions on scheme

y Logical programmingy y y

Introduction Prolog Questions on prolog

y Comparison of functional and logical programming

2

Functional Programmingy Functional programming language is based on mathematical functions. y functional languages are applicative because they achieve their effect by the applications of functions y In purely functional programming, the concept of assignment does not exist. y In function programming there is no problem of side affects.3

y Advantagey y

It doesnt have aliasing problem. It can be easily used for parallel machines.

y Disadvantagey

There is no dedicated hardware, generally implemented with interpreters.

4

Schemey Scheme is dialect of Lisp. y It is a pure functional programming language. y It was developed in MIT in 1975 by Sussman and

Steele. y Scheme is generally used for teaching purposes. y It uses static scoping y Scheme permits two types of objects,y y

Atoms Lists5

y Atoms can be either,y Numeric atoms

28 -14.23 y Quoted string atoms Any String

y List is a sequence of atoms separated by blanks and

parentheses. (1 2 3) ((a b) c d) y Simple list is a list that doesnt have a sublist.eg: (a b c)6

Numeric atoms and Primitive Functionsy Primitive arithmetic functions such +,-,* and / are

available in scheme. y Scheme can perform arithmetic on the contents of atoms.y (+ 2 5)

7

(+ 2 5 7) 14

y Scheme does not have any precedence rules for its

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 + 3The + operator (and other arithmetic) operators can take any number of arguments.

The same as:

(2+3)*(1+2)8

y 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)) y Comments begin with a semicolon and continue until the end of line. (define pi 3.14) ;bind a variable to a value y Scheme ignores the distinction between uppercase and lower case. y Names in scheme can have letters, digits, special characters except parenthesis ; they must not begin with a digit.9

Covert these mathematical functions to schemey (2+5)*(7-3) In scheme we write this like this. o

(*(+25)(-73))

28

y -b + b2 - 4ac 2a o ( / (+( -b )(sqrt (-(sq b)(*4 a c)))) (*2 a)) y Define functions by lambda expression. o Cube (x)

( (x) (* x x x )) y OR else can define like this. o (Define (cube x) (* x x x ))10

Functionsy To define a function,(Define (function_name parameters) (expression) )

y Output functions,(Display expression) or (NEWLINE)

11

yIF Condition(IF predicate then_expression else_expression) (Define (factorial n) (If (= n 0)) 1 (* n (factorial (- n 1))) )

12

yCOND functionthis 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 CDRy CAR functiony Returns the first element in a given list

eg: (Car (A B C)) (Car ((A B) C D))

returns A returns (A B)

y CDR functiony Returns the remainder in a given list after the car has been

removed eg: (Cdr (A B C)) (Cdr ((A B) C D))

returns (B C) returns (C D)15

yCONS functiony y

Builds a list from two arguments, first is either an atom or a list , the second is usually a list. Insets its first parameter as the new car of its 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

yLIST functiony

Constructs a list from a variable number if parameters.

(List apple orange grape) returns (apple orange grape)

17

yEQ? functiony

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

yEQV? Functiony y

Test two atoms for equality when it is not known whether they are symbolic or numeric . EQ? or = is faster than EQV?

yLIST? Functiony

Returns #T if its single argument is a list #F otherwise

19

yNULL? Functiony

Tests if its 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 Eg. 5=5*4*3*2*1 5*4! (Define (factorial x) (cond ((=x 0) 1) ((=x 1) 1) (else(*x (factorial (- x 1)))) ))

factorial.Base case (Stop at this point)

Recursion is used here

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

y 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

y 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

y 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

y This is a scheme function to get the SUM of the list.

(define (sum list) (if (null? list) 0 (+ (car list) (sum (cdr list))))) y 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

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

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

y Define length function.

Eg. (1 2 3 4 ) 4(Define (length list)) (cond (null? list) 0) (else (+ 1(length (cdr list)))) ))

28

y 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

y 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.y (Define (total-reverse list)

(cond ((null? list) ()) ((list? (car list)) (cons (total-reverse(cdr list))(totalreverse(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)) 531

y 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

y 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

y 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

y 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 its 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 programmingy Logic programming is the use of mathematical logic

for computer programming.y It adopts a different approach to problem solving to

both procedural programming and functional programming.y logic programming requires a logical declarative

description of the nature of the problem.36

y Advantages y They are very high level (specify what instead of how) y They are simple and easy to learn y They are well suited for parallel machines. y Disadvantages y slowness of execution

37

Introduction to Prology Prolog is a general purpose logic programming

language associated with artificial intelligence and computational linguistics. y Prolog was developed in 1972 by Alain Colmerauer y The program logic is expressed in terms of relations, represented as facts and rules. y Modern Prolog environments support creating graphical user interfaces, as well as administrative and networked applications.38

Data types in Prology Prolog's single data type is the term. Terms are either atoms,

numbers, variables or compound terms Eg: x, blue, 'some atom'. y Numbers can be floats or integers. y 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 y 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 factsThere are two types of clauses: Facts and rules.y 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). y 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 Basicsy 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. y In Prolog, a comma is used to indicate the logical AND41

Knowledge base in Prology 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 examplesy 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) -> Yes43

Knowledge base examplesy Likes(bob,fish)

This states that bob likes fish y father(louis,al) U father(louis,violet) This states that louis is als father or violets father y married(joe,elsie). married(fred,doris). married(darren,tracey). husband(X) :- married(X,_). husband(X)- ioe,fred,darren44

Listsy

A very common data-structure in Prolog is the list.They always start and end with square bracket

y 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).y 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]y [ ] - this is a special list, it is called the empty list

because it contains nothing.

46

Lists examplesy [a,b,c] unifies with [Head|Tail] resulting in Head=a and

Tail=[b,c] y Consider the following fact. p([H|T], H, T). y 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). ?- p([a], X, Y). X=a Y=[] No

Yes47

List SearchingIn 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. 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

Questionsy 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.y 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

y 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

y 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

y 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

y 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

y 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

y 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

y 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 programmingy Functional Programming (Scheme)

Based on the mathematical concept of a function: plus(3, 5) 8 teaches(doug, s2004) cs314 y Logic Programming (Prolog): Based on the mathematical concept of a relation: plus(3, 5, 8). True statements teaches(doug, s2004, cs314).57

Group members,y DIT-08-M2-1360

P.H.C.L.Premachandra y DIT-09-M4-1763 D.A.Y.Thantriwattage y DIT-09-M4-1786 J.H.A.D.K.Jayasekara y DIT-09-M4-1790 S.D.Gunaratne

58

Thank you !59