views:

692

answers:

3

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.

+3  A: 

Here is a general predicate that scans a list to find a single member defined by a given goal.

select_element(Goal, [Head | Tail], Selected) :-
    select_element(Goal, Tail, Head, Selected).


select_element(_Goal, [], Selected, Selected).

select_element(Goal, [Head | Tail], Current, FinalSelected) :-
    call(Goal, Head, Current, Selected),
    select_element(Goal, Tail, Selected, FinalSelected).

Lets say you define a predicate

get_bigger_number(N1, N2, N) :-
    N is max(N1, N2).

Now you can execute:

?- select_element(get_bigger_number, [5, 1, -2, 10, 3.2, 0], Selected).

Selected = 10

So all you need to do now is define a predicate get_longer_list(L1, L2, L), and use it instead of get_bigger_number/3.

Of course, using a general predicate like select_element/3 might not be very efficient. For example, you should try to avoid calculating the length of the same list several times, because this calculation is slow in Prolog (at least if implemented in Prolog in the standard way).

Kaarel
I'm not sure how this would be if the number are actual lists. Because the head of the list would be a a list.
Algific
select_element/3 does not care what is the nature (e.g. atomic or list) of the list elements. Everything depends on the predicate that you have to write (get_longer_list/3).
Kaarel
+2  A: 

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!

Juanjo Conti
Of course, you can also validate that the manipulated objects are actually lists.
Juanjo Conti
The complexity of your solution is O(n^2). That's too much for a simple problem like this...
Kaarel
A: 

did u ever find an answer for this? i'm looking for a code like that one, but the one posted by Juanjo Conti doesn't work for LONG lists..

hans
One answer here is "selected" so I guess the poster found the answer... :)
Kaarel