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.
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With