Basic Prolog (List)


1.      How to find last element from a list

Code:
lastelement([A],A).
lastelement([_|A],B):- lastelement(A,B).

Output:
lastelement([a,b,c,d],X).
X = d .

2.      How to find nth element of a list
Code:
element_at(X,[X|_],1).
element_at(X,[_|T],Y):- element_at(X,T,Y1), Y is Y1+1.
Output:
element_at(X,[a,b,c,d],2).
X = b .
3.      How to check whether the element available or not
Code:
mem([X|_],X).
mem([_|T],X):- mem(T,X).
Output:
mem([a,b,c,d],a).
true . 

4.      How to print all members
Code:
mem([X|_],X).
mem([_|T],X):- mem(T,X).
Output:
mem([a,b,c,d],X).
X = a ;
X = b ;
X = c ;
X = d ;
false.
There is a “Prolog” keyword to find member of list. We can use it directly.
4.1. ?- member(X,[a,b,c,d]).
X = a ;
X = b ;
X = c ;
X = d.
4.2. ?- member(b,[a,b,c,d]).
True
5.      How to find the length of the list
Code:
list_length([],0).
list_length([_|T],X):- list_length(T,X1),X is X1+1.
Output:
list_length([a,b,c,d],X).
X = 4.
There is a “Prolog” keyword to find the length of the list. We can use it directly.
5.1. ?- length([a,b,c,d],X).
X = 4.
6.      How to find the sum of the integer list
Code:
sumlist([],0).
sumlist([F|R],Sum):- sumlist(R,Sum1),Sum is F+Sum1.
Output:
sumlist([12,2,4],X).
X = 18.

7.      How to find minimum number of the list
Code:
minimum([X],X).
minimum([X|Xs], X) :- minimum(Xs, Y), X < Y.
minimum([X|Xs], Y) :- minimum(Xs, Y), X >= Y.
Output:
minimum([12,2,4,5],X).
X = 2 .
8.      How to find maximum number of the list
Code:
maximum([X],X).
maximum([X|Xs], X) :- maximum(Xs, Y), X > Y.
maximum([X|Xs], Y) :- maximum(Xs, Y), X =< Y.
Output:
maximum([2,4,5,12],X).
X = 12 .

9.      How to check whether the list is palindrome or not
Code:
Palindrome(L):- reverse(L,L).
Output:
Palindrome ([l,e,v,e,l]).
true.

In here, “reverse” is a keyword.
10.   How to implement Tower of Hanoi using Prolog
Code:
move(1,X,Y,_):-
               write('Move top disk '),
               write(X),
               write(' to '),
               write(Y),
               nl.
move(N,X,Y,Z):-
               N>1,
               M is N-1,
               move(M,X,Z,Y),
               move(1,X,Y,Z),
               move(M,Z,Y,X). 
               Output:
               move(3,'S','T','A').
Move top disk S to T
Move top disk S to A
Move top disk T to A
Move top disk S to T
Move top disk A to S
Move top disk A to T
Move top disk S to T
true .

11.   How to check if the given number is odd or even
Code:
odd(X):- 1 is mod(X,2).
even(X):- 0 is mod(X,2).
Output:
?- odd(12).
false.
?- odd(1).
true.
?- even(12).
true.
?- even(9).
false.
12.   How to check max number and min number
12.1.                   Max number
Code:
max(X,Y,X):- X>=Y.
max(X,Y,Y):- Y>X.
Output:
max(12,3,X).
X = 12
12.2.                  Min number
Code:
min(X,Y,X):- X=<Y.
min(X,Y,Y):- X> Y.

Output:
min(12,3,X).
X = 3.

Comments

Post a Comment

Popular posts from this blog

C# Analog Clock

SOLID Principles