Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prolog: Finding the second largest element in a list

Tags:

People also ask

How do you get the second element in a list in Prolog?

You can move unification into the head of the clause and simply write: second([_, Second| _], Second). The notation for lists is to write the initial elements separated by commas and then a vertical bar to separate the list tail, i.e. the list containing the rest of the elements.

How do you find the max element in a list in Prolog?

The maximum number in a list in Prolog ? max([],A):-print(A),!. max([Head | Tail] , A):-A =< Head ,A1 is Head , max(Tail,A1) ; max(Tail,A). Show activity on this post.


I know how to find the largest element of a list—no problem, but how should I go about finding the second largest element?

Say the predicate is secondlargest(+List,?Val) and succeeds if Val is the second largest element in the List.

If there is a tie for largest, then second largest is the same as largest...