Q: ordering symptom list prolog I have a dynamic list that contains a number of symptoms with a value of certainty.
ES: [symptom (a, 0.93), symptom (b, 0.56), symptom (c, 0.59), symptom (d, 0.80)]
I want to order the list in descending order according to the value of certainty.
ES: [symptom (a, 0.93), symptom (d, 0.80), symptom (c, 0.59), symptom (b, 0.56)]
Who can help me? Thanks

A: The fastest way is usually to map the list to another list and sort that with keysort/2. Here, I assume that you want the names sorted too, provided they have the same value.
element_to_pair(E, k(NegV,N) - E) :-
   E = symptom(N,V),
   NegV is -V.

nigrosort(Xs, Ys) :-
   maplist(element_to_pair,Xs, Ks),
   keysort(Ks, Ls),
   pairs_values(Ls, Ys).

Such tiny predicates as this element_to_pair/2 often do not deserve a name of its own. It is too much to remember. With library(lambda) you can write more compactly:
:- use_module(library(lambda)).

nigrosort(Xs, Ys) :-
   maplist(\E^(k(NegV,N)-E)^( E = symptom(N,V), NegV is -V ),Xs, Ks),
   keysort(Ks, Ls),
   pairs_values(Ls,Ys).


A: Which prolog environment are you using? SWI_Prolog has the predicate predsort, which can reorder a list using a custom predicate.

A: ..., predsort(compare_symptoms, L, Ordered), ...

compare_symptoms(<, symptom(_, PA), symptom(_, PB)) :-
  PA > PB.
compare_symptoms(>, _, _).

Note that we must avoid to return equality, or the system will remove symptoms with the same probability.

A: In case you are using ECLiPSe, you can use the sort/4predicate that allows to specify which argument of a term to use for sorting:
sort(2, >=, Symptoms, OrderedSymptoms)

