Home > Software design >  Counting Elements in a List of Lists and Outputting Answer as a List in Prolog
Counting Elements in a List of Lists and Outputting Answer as a List in Prolog

Time:11-18

I'm new to Prolog, and struggling to do the following:

I need to write a predicate which outputs the number of list elements inside a list of lists, and output the answer itself as a list.

As an example, I would want:

clistoflists([[a,b,c,d],[e,f,g],[h,i][j,k,l]], N).
N = (4,3,2,3)

I am able to write a predicate to count the elements of a simple list:

count_list([],0).
count_list([_|T], C) :- count_list(T, CNT), C is CNT   1.

I'm just very unsure how to proceed with the more complicated list of lists, and especially providing for the desired output list.

Any guidance would be very welcome. I've been toying with this for far too long.

CodePudding user response:

The simplest solution is to use the predicates length/2 and maplist/3 as follows:

?- maplist(length, [[a,b,c,d],[e,f,g],[h,i],[j,k,l]], L).
L = [4, 3, 2, 3].

Another alternative is to create your own versions of those predicates:

maplen([], []).
maplen([X|Xs], [Y|Ys]) :-
    len(X, Y),
    maplen(Xs, Ys).

len([], 0).
len([_|Xs], N) :-
    len(Xs, M),
    N is M   1.

Example:

?- maplen([[a,b,c,d],[e,f,g],[h,i],[j,k,l]], L).
L = [4, 3, 2, 3].
  • Related