Prolog max length of a list in a list of lists

58 views Asked by At

My goal is to return the longest list in a list of lists. For example: [[1,2,3],[1,2]]-> [1,2,3].

I wrote this

list_max_len([L],L).
list_max_len([X,Y|T],L):-
   length(X) >=length(Y),
   list_max_len([X|T],L).
list_max_len([X,Y|T],L):-
   length(X) < length(Y),
   list_max_len([Y|T],L).

But i got this error:

enter image description here

can someone explain what it is?

1

There are 1 answers

0
Nicholas Carey On

It is unclear exactly what Prolog implementation you're using. However, length/1 is not a predicate that would compute the length of a list. That, standard/ISO predicate is length/2.

Try something like this (assuming that you're allowed to use the in-built length/2:

list_max_len( [L|Ls] , N ) :- % To figure out the length of the longest list in a list-of-lists, 
  length(L,M) ,               % - compute the length of the 1st list, and
  list_max_len(Ls,M,N).       % - examine the remainder, seeding the current max
  .                           % Easy!

list_max_len( [L|Ls] , M , N ) :-  % to compute the length of the longest list in a list-of-lists....
  length(L,X) ,                    % - get the length of the head
  M1 is max(M,X),                  % - pick the larger of the current max and the length of the head
  list_max_len(Ls,M1,N)            % - recurse down
  .                                % Easy!