1
votes

I've been trying to find how I could do this, I'm trying to sort facts like: package(X,Y,N), where N is a number. I want to create a list with the X values, ordered by the value of N (lowest to highest). Tried using :

gera_caminho_tempo(,L):- findall(package(N,,S), package(,,S), Packages), msort(Packages, L).

But no results, any ideas?

1

1 Answers

3
votes

For such tasks, check out the standard predicate keysort/2.

In your case, you can create pairs of the form N-package(X,Y,N), using for example:

?- findall(N-package(X,Y,N), package(X,Y,N), Pairs0).

Once you have obtained Pairs0, you can use keysort/2 to obtain the pairs sorted by key, where the first component of each pair acts as its key:

?- findall(N-package(X,Y,N), package(X,Y,N), Pairs0),
   keysort(Pairs0, Pairs).

I leave relating such sorted pairs to only the sorted packages as an easy exercise.