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).
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).
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)
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)