How do I find the longest list in a list of lists?

前端 未结 6 1018
说谎
说谎 2020-12-07 04:06

I have a list of lists, and I need to find the longest one of them. If there are more than one with the same length it\'s the same which it returns. Thanks.

6条回答
  •  萌比男神i
    2020-12-07 04:47

    We define longest/2 based on meta-predicate max_of_by/3 used in tandem with length/2:

    longest(Xss,Ys) :-
       max_of_by(Ys,Xss,length).
    

    Sample queries:

    ?- longest([[1],[2]],Xs).      % we expect   multiple solutions
      Xs = [1]                
    ; Xs = [2].                    % we    _get_ multiple solutions
    
    ?- longest([[2,1,3],[7,5],[1,8,2,3,1],[2,7,1,4]],Xs).
    Xs = [1,8,2,3,1].              % succeeds deterministically
    

提交回复
热议问题