You are on page 1of 19

Lab ManualFunctional & Logic Programming

NCS-455

FUNCTIONAL AND LOGIC


PROGRAMMING LAB
(NCS-455)
LABORATORY MANUAL
FOR
Bachelor of Technology
In
Computer Science
Session: 2014-2015

Department of Computer Science & Engineering


KRISHNA ENGINEERING COLLEGE
GHAZIABAD

Krishna Engineering College, Ghaziabad

Lab ManualFunctional & Logic Programming


NCS-455

NCS-455: FUNCTIONAL AND LOGIC PROGRAMMING LAB


1. Write a function for the binary operations like addition, subtraction, multiplication
and division in LISP(3)
2. Write a function that computes the factorial of a number in LISP(Factorial for 0 is
1, and factorial for n is n*(n-1)*1).............(4)
3. Write a function that computes average of three numbers in LISP......(5)
4. Write a function that computes area of a circle in LISP....(6)
5. Write a function that computes maximum of three numbers in LISP..(7)
6. Write a function that evaluates a fully parenthesized infix arithmetic expression in
LISP.............(8)
7. Write a function that performs a depth first traversal of binary tree...(9)
8. Write a LISP program for water jug problem..(10)
9. Write a PROLOG program that answers questions about family members and
relationships includes predicates and rules which define sister, brother, father,
mother, grandchild, grandfather and uncle. The program should be able to answer
queries such as the following:..(12)
Father(x,Amit)
Grandson(x,y)
Uncle(sumit,puneet)
Mother(anita,x)
Program in SML-NJ or CAML or PROLOG for following:
10. To implement Insertion Sorting(13)
11. To implement Quick Sorting.(14)
12. To implement Bubble Sorting...(16)
13. To implement Selection Sorting(17)

Krishna Engineering College, Ghaziabad

Lab ManualFunctional & Logic Programming


NCS-455

LISP is the premier language for Artificial Intelligence applications. It is a dynamic


language: editing changes take effect immediately, without the need for recompilation. It is
primarily a functional language: all work can be done via function composition and recursion.
There is no "main program:'' the programmer can call any function from the input prompt.
The overall style of the language is organized primarily around expressions and functions rather
than statements and subroutines.
LISP is an old language, and has been updated many times. The most recent standard, Common
LISP, is a huge language.
Here is a simple Lisp procedure that concatenates two lists of items, producing a new list:
(define (append x y)
(cond ( (null x) y)
(t (cons (car x) (append (cdr x) y)))))
This may be read as follows: To produce a list consisting of the items of y appended to the items
of x, the computation is conditional (cond). If the list x is empty (null), then the result is equal to
y. Otherwise, construct (cons) a new list by placing the first item (car) of x before the result of
appending y to the rest of the items (cdr) of list x.
A list is a sequence of Lisp data objects, notated by notating its elements within parentheses and
separated by spaces. Thus (michelangelo artist (born 1475) (died 1564))is a list of four items; the
first two are symbols, and the last two are lists, each containing a symbol and an integer. The list
() is empty, containing zero items; (() ()) is a list of two empty lists.
We can apply our sample function append to two lists as follows:
(append '(fee fie) '(foe fum)) =>; (FEE FIE FOE FUM)

Krishna Engineering College, Ghaziabad

Lab ManualFunctional & Logic Programming


NCS-455

[1] Write a function for the binary operations like addition, subtraction, multiplication and
division in LISP
Theory: Lisp uses prefix notation for computation. For Example: (5+3+4)
Addition:
(+ 2 3)
5
(+ 5 3 4)
12
Subtraction:
(- 10 8)
2
(- 2 10)
-8
(- 10 8 6)
-4
Multiplication:
(* 5 5)
25
(* 2 2 2)
8
Division:
(/ 5 5)
1
(/ 10 2 5)
1
(/ 10 2 4)
5/4
(/ 2 5 5)
2/25

Krishna Engineering College, Ghaziabad

Lab ManualFunctional & Logic Programming


NCS-455

[2] Write a function that computes the factorial of a number in LISP(Factorial for 0 is 1,
and factorial for n is n*(n-1)*1)
Code:
(
defun factorial (number)
(if (= number 0) 1
(* number (factorial (- number 1)))
)
Output:
(Factorial 3)
6
(Factorial 0)
1

Krishna Engineering College, Ghaziabad

Lab ManualFunctional & Logic Programming


NCS-455

[3] Write a function that computes average of three numbers in LISP.

Code:
(
defun avg3(a b c)
(princ the average of 3 nos is : )
(/ (+ a b c) 3)
)
Output:
(Avg3 1 2 3)
The average of 3 nos is : 2

Krishna Engineering College, Ghaziabad

Lab ManualFunctional & Logic Programming


NCS-455

[4] Write a function that computes area of a circle in LISP


Code:
(
defun circle()
(princ enter the radius : )
(setq r (read))
(princ the area of circle is :)
(* 3.14 r r)
)
Output:
(circle)
Enter the radius :
2
The area of circle is : 12.56

Krishna Engineering College, Ghaziabad

Lab ManualFunctional & Logic Programming


NCS-455

[5] Write a function that computes maximum of three numbers in LISP


Code:
(
defun max3(a b c)
(cond((> a b)(cond((> a c) a)
(t c)))
((> b c) b)
(t c ))
)
Output:
(max3 7 1 4)
7

Krishna Engineering College, Ghaziabad

Lab ManualFunctional & Logic Programming


NCS-455

[6] Write a function that evaluates a fully parenthesized infix arithmetic expression in
LISP
Code: (20 * 5 / 5 ) + 10
(+ (* (/ 5 5) 20) 10)
Output:
30

(1+ (2*3))
(+ (* 2 3) 1) =7

Krishna Engineering College, Ghaziabad

Lab ManualFunctional & Logic Programming


NCS-455

[7] Write a function that performs a depth first traversal of binary tree.
Theory: An exhaustive search method. DFS is a search algorithm that follows each path to its
greatest depth before moving on to the next path.
(defun dfs (state depth limit)
(setf *nodes* 0)
(setf *expanded* 0)
(setf *branches* 0)
(setf *limit* limit)
(setf *result* (dfs1 state depth))
(print (list *nodes* *expanded* *branches*))
*result*
)
;;; dfs1 expands a node and calls dfs2 to recurse on it
(defun dfs1 (state depth)
(setf *nodes* (+ 1 *nodes*))
(cond
((goalp state) (list state))
((zerop depth) nil)
((> *nodes* *limit*) nil)
((let ((children (new-states state)))
(setf *expanded* (+ 1 *expanded*))
(setf *branches* (+ (length children) *branches*))
(let ((result (dfs2 children (- depth 1))))
(and result (cons state result)))))))
;;; dfs2 recurses on each sibling from a single node, calling dfs1
(defun dfs2 (states depth)
(cond
((null states) nil)
((dfs1 (car states) depth))
((dfs2 (cdr states) depth))))

10

Krishna Engineering College, Ghaziabad

Lab ManualFunctional & Logic Programming


NCS-455

[8] Write a LISP program for water jug problem.


Theory: we have a Four Gallon Jug of Water and a Three Gallon Jug of Water and a Water
Pump. The challenge of the problem is to be able to put exactly two gallons of water in the Four
Gallon Jug, even though there are no markings on the Jugs
(defvar *start* '(0 0))
(defun first-jug (state) (car state))
(defun second-jug (state) (cadr state))
(defun mk-state (f s) (list f s))
(defun goalp (state)
(eq (first-jug state) 2))
(defun new-states (state)
(remove-null
(list
(fill-first state)
(fill-second state)
(pour-first-second state)
(pour-second-first state)
(empty-first state)
(empty-second state))))
(defun remove-null (x)
(cond
((null x) nil)
((null (car x)) (remove-null (cdr x)))
((cons (car x) (remove-null (cdr x))))))
(defun fill-first (state)
(cond
((< (first-jug state) 4) (mk-state 4 (second-jug state))))))
(defun fill-second (state)
(cond
((< (second-jug state) 3) (mk-state (first-jug state) 3))))
(defun pour-first-second (state)
(let (
(f (first-jug state))
(s (second-jug state)))
(cond
((zerop f) nil)
; Cant pour nothing
((= s 3) nil)
; Second full
((<= (+ f s) 3)
; Empty first into second
(mk-state 0 (+ f s)))
(t
; Fill second from first
(mk-state (- (+ f s) 3) 3)))))
(defun pour-second-first (state)
(let (
(f (first-jug state))
(s (second-jug state)))
(cond
((zerop s) nil)

11

; Cant pour nothing

Krishna Engineering College, Ghaziabad

Lab ManualFunctional & Logic Programming


NCS-455
((= f 4) nil)
; First full
((<= (+ f s) 4)
; Empty second into first
(mk-state (+ f s) 0))
(t
; Fill first from second
(mk-state 4 (- (+ f s) 4))))))
(defun empty-first (state)
(cond
((> (first-jug state) 0) (mk-state 0 (second-jug state)))))
(defun empty-second (state)
(cond
((> (second-jug state) 0) (mk-state (first-jug state) 0))))

12

Krishna Engineering College, Ghaziabad

Lab ManualFunctional & Logic Programming


NCS-455

[9] Write a PROLOG program that answers questions about family members and
relationships includes predicates and rules which define sister, brother, father, mother,
grandchild, grandfather and uncle. The program should be able to answer queries such as
the following:
Father(x,Amit)
Grandson(x,y)
Uncle(sumit,puneet)
Mother(anita,x)
Domains
List = string*
Predicates
Father(string, string)
Grandson(string, string)
Uncle(string, string)
Mother(string, string)
Clauses
Father(Suraj,Amit) //father of suraj is amit
Father(Rohit,Raj)
Grandson (Suraj,Suresh)
Father(Rohit,Raj)
Mother(anita,suraj)
Mother(anita,vimal)
Uncle(sumit,puneet)
Uncle(rahul,puneet)
Grandson(suresh,amit)
Goal:
Father(x,Amit)
x= Suraj
1 Solution

13

Krishna Engineering College, Ghaziabad

Lab ManualFunctional & Logic Programming


NCS-455

[10] Implement Insertion sort using PROLOG.


Theory: Insertion Sort is an efficient algorithm for sorting a small number of elements.
INSERTION-SORT (A)
1. for j = 2 to n
2.
key A [j]
3.
// Insert A[j] into the sorted sequence A[1..j-1]
4.
ji1
5.
while i > 0 and A[i] > key
6.
A[i+1] A[i]
7.
ii1
8.
A[j+1] key
Code in LISP:
Domains
list = integer*.

Predicates
insert(integer, list, list).
append(list, list, list).
insort(list, list).
Clauses
append([],L,L).
append([H|T],L,[H|NT]):-append(T,L,NT).
insert(X,[],[X]).
insert(X,[H|T],NL):-X<H, append([X],[H|T],NL).
insert(X,[H|T],[H|NL]):-X>H, insert(X,T,NL).
insort([], []).
insort([H|T],FS):-insort(T,NT), insert(H,NT,FS).

14

Krishna Engineering College, Ghaziabad

Lab ManualFunctional & Logic Programming


NCS-455

[11] Implement Quick Sort using PROLOG


Pseudo Code:
Quicksort(A,p,r) {
if (p < r) {
q <- Partition(A,p,r)
Quicksort(A,p,q)
Quicksort(A,q+1,r)
}
}

Partition(A,p,r)
x <- A[p]
i <- p-1
j <- r+1
while (True) {
repeat
j <- j-1
until (A[j] <= x)
repeat
i <- i+1
until (A[i] >= x)
if (i<-=""> A[j]
else
return(j)
}
}

Code in LISP:
Domains
list = integer*.
Predicates
quicksort(list,list).
split(integer,list,list,list).
concatenate(list,list,list).
printlist(list).
Clauses
quicksort([],[]).
quicksort([Head|Tail],SortedList) :split(Head,Tail,SList,BList),
quicksort(SList,SList1),
quicksort(BList,BList1),
concatenate(SList1,[Head|Blist1],SortedList),
printlist(SortedList).
split(_,[],[],[]).
split(Item,[Head1|Tail1],[Head1|SList],BList) :15

Krishna Engineering College, Ghaziabad

Lab ManualFunctional & Logic Programming


NCS-455

Item > Head1 , ! ,


split(Item,Tail1,SList,BList).
split(Item,[Head1|Tail1],SList,[Head1|BList]) :split(Item,Tail1,SList,BList).
concatenate([],List,List).
concatenate([Item|List1],List2,[Item|List3]) :concatenate(List1,List2,List3).
printlist([]) :- nl.
printlist([Head|Tail]) :write(Head," "),
printlist(Tail).

Output
Goal: quicksort([2,4,1,3,5,9,6],L).
1
3
6
69
569
34569
1234569
L=[1,2,3,4,5,6,9]
1 Solution

16

Krishna Engineering College, Ghaziabad

Lab ManualFunctional & Logic Programming


NCS-455

[12] Program to sort using Bubble Sort in PROLOG


The Algorithm Pseudocode:
bubblesort (A, N)
{ repeat the following steps until the list is sorted
put 1 into i
repeat while i < N
if A[i] > A[i+1]
then swap A[i], A[i+1]
end if
add 1 to i
end repeat
end repeat
}end bubblesort
Code in LISP:
Domains
list = integer*.
Predicates
bubblesort(list,list).
swap(list,list).
printlist(list).
Clauses
bubblesort(InputList,SortList) :swap(InputList,List) , ! ,
printlist(List),
bubblesort(List,SortList).
bubblesort(SortList,SortList).
swap([X,Y|List],[Y,X|List]) :- X > Y.
swap([Z|List],[Z|List1]) :- swap(List,List1).
printlist([]) :- nl.
printlist([Head|List]) :write(Head, " "),
printlist(List).

Output:
17

Krishna Engineering College, Ghaziabad

Lab ManualFunctional & Logic Programming


NCS-455

Goal: bubblesort([2,3,1,4],L).
2134
1234
L=[1,2,3,4]
1 Solution
Goal: bubblesort([2,4,1,3,5,9,6],L).
2143596
1243596
1234596
1234569
L= [1,2,3,4,5,6,9]
1 Solution

18

Krishna Engineering College, Ghaziabad

Lab ManualFunctional & Logic Programming


NCS-455

[13] Program to implement Selection Sort in PROLOG


The next largest (or smallest) element in the array is repeatedly found and moved to its final
position in the sorted array.
The Algorithm Pseudocode:
selectionSort (A, N)
put 1 into j -- j is used to step through the B list
repeat until j > N
put minimum(A[j]...A[N],N-j+1) into min
swap A[j], A[min]
add 1 to j
end repeat
return A
end selectionSort
Code in LISP:
Domains
list = integer*.
Predicates
smallest(list,integer).
replace(integer,integer,list,list).
sel(list,list).
Clauses
smallest([X],X).
smallest([H|T],X) :- smallest(T,X), H>X.
smallest([H|T],H) :-smallest(T,X), H<=X.
replace(X,Y,[],[]).
replace(X,Y,[H|T],[Y|NT]) :- H=X, replace(X,Y,T,NT).
replace(X,Y,[H|T],[H|NT]) :- H<>X, replace(X,Y<T,NT).
sel([],[]).
sel([X],[X]).
sel([H|T],[X|NT]):- smallest([H|T],X), H=Y, sel(T,NT),!.
sel(([H|T],[X|NS]):- smallest([H|T],X), H<>X, replace(X,H,T,NT), sel(NT,NS),!.

19

Krishna Engineering College, Ghaziabad

You might also like