0

How can I sort facts on its variable Like

Student(5). Student(3). Student(2). Student(3). Student(6).

I want to make function to make them appear

Student(2). Student(3). Student(3). Student(5). Student(6).

false
  • 10,264
  • 13
  • 101
  • 209
Saeed Alasiry
  • 322
  • 5
  • 23

2 Answers2

1

I would first collect all these facts to a list using findall (example: How to create a list from facts in Prolog?) , and then sort this list (example: Sorting a list in Prolog , or just use the built-in sort/2 predicate ).

(Sent from my phone)

Community
  • 1
  • 1
Ido.Co
  • 5,317
  • 6
  • 39
  • 64
0

At the moment, they are not facts in proper Prolog, you need to write them with small letters:

student(5).
student(3).
% etc

Then, several things you can do:

?- findall(S, student(S), Students), msort(Students, Sorted).

(as suggested in the other answer)

If you want to have them actually sorted in the database, and are not afraid to change the database at run-time, you can then remove all student/1 from the database with abolish/1 and re-insert the sorted facts:

reorder_students :-
    findall(S, student(S), Students),
    msort(Students, Sorted), % do not remove duplicates
    abolish(student/1),
    forall(
        member(M, Sorted),
        assertz(student(M))
    ).

It is not a very good idea to do this repeatedly! If you have a regularly changing database of students you might consider not putting them in the database, but instead using for example an association list as in library(assoc)

  • Your first query will return L=[3,5]. How about getting L=[student(3),student(5)] because I think OP is looking for this. Also can we use setof/3? – ssbarbee Dec 28 '13 at 08:44
  • @ssBarBee Your suggestion is confusing a list of facts in the database with a list of terms. It is a matter of taste I guess. You can't use `setof/3` if you follow the exact question, as it will remove duplicates. Or am I misunderstanding your comment somehow? –  Dec 28 '13 at 08:48