๐Ÿค–
B.TECH II YEAR โ€ข II SEMESTER โ€ข R22

Skill Development Course - Lab Manual

PROLOG / LISP / PySWIP โ€ข Program 10 Solution

๐Ÿ“˜ R22 Regulation ๐ŸŽ“ II Year ๐Ÿ“š II Semester ๐Ÿค– Skill Development Course ๐Ÿงช Lab Program 10
Aim

Write a Prolog predicate, countLists(Alist, Ne, Nl), using accumulators, that is true when Nl is the number of items that are listed at the top level of Alist and Ne is the number of empty lists. Suggestion: First try to count the lists, or empty lists, then modify by adding the other counter.

โ† All Programs

๐Ÿ’ป Solution

week11.pl
/* Description:

countLists(Alist, Ne, Nl) is true when
-- Nl is the number of items at the top level of Alist which are lists, and
-- Ne is the number of those lists which are empty ([]).

Accumulators are used: the counts of empty lists (E0) and of lists (L0) found so far are
passed along and the final values are returned in Ne and Nl when the end of Alist is reached.
Lists inside other lists are not counted (only the top level is examined).
*/

/* Production rules:

countLists(Alist, Ne, Nl)     start the accumulators with 0 and 0
countLists([], Ne, Nl, Ne, Nl)             end of the list: the accumulators are the answer
countLists([[]|T], E0, L0, ...)            an empty list: add 1 to both accumulators
countLists([[_|_]|T], E0, L0, ...)         a non-empty list: add 1 to the list accumulator
countLists([_|T], E0, L0, ...)             any other item is not counted

*/

% Clauses:

countLists(Alist, Ne, Nl) :-
	countLists(Alist, 0, 0, Ne, Nl).

countLists([], Ne, Nl, Ne, Nl).

countLists([[]|T], E0, L0, Ne, Nl) :- !,
	E1 is E0 + 1,
	L1 is L0 + 1,
	countLists(T, E1, L1, Ne, Nl).

countLists([[_|_]|T], E0, L0, Ne, Nl) :- !,
	L1 is L0 + 1,
	countLists(T, E0, L1, Ne, Nl).

countLists([_|T], E0, L0, Ne, Nl) :-
	countLists(T, E0, L0, Ne, Nl).

๐Ÿ“ค Output

w11.txt
% Queries:

?- countLists([a,[],[b,c],[],d,[e]], Ne, Nl).
Ne = 2,
Nl = 4.

?- countLists([], Ne, Nl).
Ne = 0,
Nl = 0.

?- countLists([a,b,c], Ne, Nl).
Ne = 0,
Nl = 0.

?- countLists([[],[],[]], Ne, Nl).
Ne = 3,
Nl = 3.

?- countLists([[a],[[]],[]], Ne, Nl).
Ne = 1,
Nl = 3.

?- countLists([1,[2,3],[],[[4]],5], Ne, Nl).
Ne = 1,
Nl = 3.
โ† Program 9 Program 11 โ†’
โ† Back to Skill Development Course Lab Programs ๐Ÿ“š All Lab Manuals