I’m writing a program that checks if a list contains sub-lists of unique length:
e.g. diffLengthLists([[2],[3,4]]) should return true whereas diffLengthLists([[3],[4]]) should return false.
Here’s my code:
diffLengthLists(A):- is_list(A),
diffLength(A,[_]).
diffLength([A|B], [C|D]):- length(A, C),
diffLength(B, D),
unique([C|D]).
unique([A|B]):- \+member(A, B), unique(B).
unique([]).
So I’m basically adding the length of each sub-list to another list, [C|D], and then check if the elements in [C|D] are unique.
However, my program doesn’t work the way expected. What am I doing wrong here? Is there a better (clearer) way to write this program?
Thanks for your help in advance!
EDIT: I tested the helper predicates and the issue seems to be arising from diffLength however, I don’t understand why it isn’t working.
I added unique([]). to the code and now that predicate works properly.
This solution terminates, if all lengths of all lists are known. That is what your homework was about.
But it does not terminate for
diffLengthLists([[],[],_])when it should fail. It is very difficult to accomplish an implementation that would terminate in all possible cases.In SWI, the following is predefined, so no need to define it. But other systems need it:
For
maplist/3see this post.And here is another solution, that terminates for above goal:
Find out a case where this predicate does not terminate, when it should fail!