Finding the length of lists within a list in Prolog

Viewed 185

For example:

count_blocks([[b,c,f],[a,d,g],[h,e]],C).
C=[3,3,2]

I know that I can find the length of a list with:

len([], LenResult):-
    LenResult is 0.

len([X|Y], LenResult):-
    len(Y, L),
    LenResult is L + 1.

but not sure how to calculate list lengths within a list. The outer list length will always be 3 (with the possibility of empty inner lists).

2 Answers

You should perform a mapping with length. You can map with maplist/3, so you can work with:

count_blocks(L, R) :-
    maplist(length, L, R).

If you want to write all the predicates yourself you can do it like this:

len([], 0).
len([_|Y], LenResult):-
    len(Y, L),
    LenResult is L + 1.

count_blocks([],[]).
count_blocks([H|T],[N|L]):-
    len(H,N),
    count_blocks(T,L).

?- count_blocks([[b,c,f],[a,d,g],[h,e]],C).
C = [3, 3, 2].

count_blocks/2 works with the same principle as len/2. As long as there is at least one sublist H in the inputlist, calculate the length N of sublist H and put it as head element of the return list L. You get L by asking the same query for the rest list: count_blocks(T,L). If the inputlist is empty, the list of sublist-length is empty as well: count_blocks([],[]).

Related