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

前端 未结 6 1014
说谎
说谎 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条回答
  •  温柔的废话
    2020-12-07 04:54

    Please consider my aproach.

    longest([L], L) :-
       !.
    longest([H|T], H) :- 
       length(H, N),
       longest(T, X),
       length(X, M),
       N > M,
       !.
    longest([H|T], X) :-
       longest(T, X),
       !.
    

    Then you can consult it:

    ?- longest([[1]], N).
    N = [1] ;
    
    ?- longest([[1],[2]], N).
    N = [2] .
    
    ?- longest([[1],[2], [3,3,3], [2]], N).
    N = [3, 3, 3] ;
    
    ?- longest([[1],[2], [3,3,3], [2]], N).
    N = [3, 3, 3].
    
    ?- longest([[1],[2], [3,3,3], [2], [4,4,4,4]], N).
    N = [4, 4, 4, 4] .
    
    ?- longest([[1],[2], [3,3,3], [2], [4,4,4,4]], N).
    N = [4, 4, 4, 4] ;
    

    Greets!

提交回复
热议问题