Personal Blog : My OUM(Open University Malaysia) journey starting from Jan 2011 till graduate.
Everyone can copy the contents in this blog and please leave some credit or a backlink to me... -Thank You-

Monday, April 8, 2013

KNOWLEDGE MODELING AND REPRESENTATION - PROLOG

Prolog Programming.



(a) Find the last element in weekdays list.
            (i)      %  Find the last element in weekdays list .
% last(X, weekdays) ,  X is the last element of the list weekdays .
% (element, weekdays) (?,?) .
% Note : last(?element,? weekdays)
last(X,[X]).
last(X,[weekdays]).
X=Friday

 




(b) Find the N'th element in weekdays list. (N=2).
            (i)      % Find the N'th element of a list.
% The first element in the list is number 1.
% nth1(X, weekdays,N), X is the N'th element of the weekdays
% (nth1,list,integer) (?,?,+)
% Note to readers: nth1(?Index, ?List, ?element) is predefined.
nth1 (X,[X|_],1).
nth1(X,[_| weekdays], N),  N > 1, N1 is N - 1, nth1(X, weekdays, N1).
X=tuesday
   



(c) Reverse a list
(i)        % reverse(L1weekdays,L2weekdays) :- L2weekdays is the list obtained from L1weekdays by reversing the orders of the elements.
% (list,list) (?,?)
% Note : reverse(+List1weekdays, -List2weekdays) is predefined
reverse(L1weekdays,L2weekdays) , reverse (L1weekdays,L2weekdays,[]).
reverse ([],L2weekdays,L2weekdays) :- !.
reverse ([X|Xsenarai],L2weekdays,M),  reverse (Xsenarai,L2weekdays,[X|M]).









(d) Duplicate the elements in weekdays list.
(i)        % * Duplicate the elements in weekdays list * .
% dupli(X, weekdays) ,  X is the last element of the list weekdays .
% (element, weekdays) (?,?) .
% Note : dupli(?element,? weekdays)
dupli(X,[X]).
dupli(X,[weekdays]).





(f) Drop every N’th element from a weekdays list. (2nd element).
(i)        % drop(L1 weekdays,N,L2 weekdays) :- L2 weekdays is obtained from L1 weekdays by dropping every N'th element.
% (list,integer,list) (?,+,?)
drop(L1weekdays,N,L2weekdays) , drop(L1 weekdays, N, L2 weekdays, N).
% drop(L1 weekdays,N,L2 weekdays,N),  L2 weekdays is obtained from L1 weekdays by first copying N-1 elements
% and then dropping an element , dropping every
% N'th element.
% (list,integer,list,integer) (?,+,?,+)
drop([],_,[],_).
drop([_|Xweekdays],N,Yweekdays,1) :- drop(Xweekdays,N,Yweekdays,N).
drop([X|Xweekdays],N,[X|Yweekdays],K) :- N > 1, N1 is N - 1, drop(X weekdays,N,Yweekdays,N1).





(h) Rotate weekdays list N places to the left. (N=3)





(i) Remove the N'th element from a list. (2nd element)





(j) Extract a slice from a list.(position 2 and 4).


 

No comments:

Post a Comment

Table Grade