Search code examples
prolog

What is the simple way to find the max length of a list in prolog?


I'm new to learn the Prolog, I have a list, which looks like -> [[6, 7, 8,9], [6, 7, 8, 9], [6, 7, 8, 9], [7, 8, 9], [7, 8, 9],[5,6,7]], I want to find the all max length lists in the list, In this case, it should return [[6,7,8,9],[6,7,8,9],[6,7,8,9]]

my code


maxlist([A],A).
maxlist([A,B|Rest],Max):-
    maxlist([B|Rest],Maxrest),
    max(A,Maxrest,Max).

max(A,B,A):-
    length(A,N1),
    length(B,N2),
    N1>N2.
max(A,B,B):-
    length(A,N1),
    length(B,N2),
    N2>N1. 

I could only find the one, I don't know how I find all, please don’t solve this predicate in complicate way or use complicates functor, it’s hard to understand for me.


Solution

  • Another possible solution is:

    maxlist(ListOfLists, Answer) :-
        maxlist(ListOfLists, -inf, [], Answer).
    
    maxlist([], _, Answer, Answer).
    
    maxlist([List|Lists], Max, Acc, Answer) :-
        length(List, N),
        (   N = Max ->  maxlist(Lists, Max, [List|Acc], Answer)
        ;   N > Max ->  maxlist(Lists,  N,  [List],     Answer)
        ;               maxlist(Lists, Max, Acc,        Answer) ).
    

    Examples:

    ?- maxlist([[6,7,8,9], [6,7,8,9], [6,7,8,9], [7,8,9], [7,8,9], [5,6,7]], M).
    M = [[6, 7, 8, 9], [6, 7, 8, 9], [6, 7, 8, 9]].
    
    ?- maxlist([[1,2,3],[4,5,6,7,8,9],[0]], M).
    M = [[4, 5, 6, 7, 8, 9]].
    
    ?- maxlist([[1,2,3], [4,5,6,7], [8], [9,0,1], [2,3,4,5]], M).
    M = [[2, 3, 4, 5], [4, 5, 6, 7]].