Testing whether all lists in a list have the same length

advertisements

I am trying to learn more about lists in Prolog, especially lists within a list. So I want to write a predicate to determine if the lists in a list are equal. So if I did this

?- equalLists([[a,b,c],[1,2,3],[d,4,e],[5,6]]).
false

So I'm trying to check each list to see if it is has the same length as the previous list. Can someone point me in the right direction?


@Peteris's solution is unnecessarily complex. You can do it like this:

equal_lengths([]).
equal_lengths([[]]).
equal_lengths([[_|_]]).
equal_lengths([X,Y|Rest]) :-
  length(X, Len),
  length(Y, Len),
  equal_lengths([Y|Rest]).

Think inductively. I'm asserting that the length of the empty list and a list of one list are "equal" (there are no/just one other to compare to). Then I say if the length of the first item equals the length of the second item, as long as the lengths of the second item and the rest match we are good.

Note: we're not explicitly saying that the length of X and Y is the same with some kind of equality test. We're letting Prolog handle that for us, by simply declaring that the length of X and Y is Len. So if the length of Y doesn't unify with the length of X, the predicate will fail.

Reversing the process

So, to write a predicate to determine if none of the lists have the same length we must observe that this time we will have to keep track of which lengths have been seen so far to check against. We must compare each list's length to all the preceeding list lengths to determine inequality. So this time our initial case will create the initial list of lengths and defer processing to another predicate like so:

unequal_lengths(X) :- unequal_lengths(X, []).

Now we again begin with similar base cases:

unequal_lengths([], _).
unequal_lengths([[]], _).
unequal_lengths([[_|_]], _).

Things get interesting when we have an actual list:

unequal_lengths([X|Rest], Lengths) :-
  length(X, Len),
  \+ member(Len, Lengths),
  unequal_lengths(Rest, [Len|Lengths]).

So we're calculating the length of this list, then asserting that this is not a length we have seen before with the handy member predicate, then passing this length along with the rest along to the remainder of the list.

Addendum: unequal w/ forall

Inspired by the other answers, you can implement unequal_lengths in a higher-order fashion like so:

unequal_lengths(Lists) :-
  findall(Len, (member(X, Lists), length(X, Len)), Lengths),
  forall(select(Len, Lengths, Remaining), \+ member(Len, Remaining)).

If you think about it, this corresponds quite closely to a formal logic expression of the problem: for every list length, there does not exist an element of the remaining list lengths corresponding to this one.