Search code examples
prolog

Sorting a knowledge database in Prolog


It's my first day with Prolog, and i need some help. I have a Konwledge database of students student(Id,fName,lName,grade), I would like to display the list of students in order of merit, I have some ideas but I can not realise theme since I'm not familiar at all with prolog programming paradigm and syntax. please recommend me a code that do this.


Solution

  • student(1, sleve, mcdichael,4).
    student(2, darryl, archideld,2).
    student(3, mario, mcrlwain, 1).
    student(4, bobson, dugnutt, 3).
    student(5, dean, wesrey, 6).
    student(6, mike, truk, 5).
    student(7, dwigt, rortugal, 7).
    
    sortedStudents(SortedStudents) :-
        findall(Grade-First-Last,
                student(_, First, Last, Grade),
                StudentData),
        sort(1, @=<, StudentData, SortedStudents).
    

    Uses findall/3 to get all the student records and turn them into a compound term of grade-firstname-lastname and sort/4 (might be SWI Prolog specific) to sort by term entry 1 (grade):

    e.g.

    ?- sortedStudents(S).
    
    S = [
    1-mario-mcrlwain,
    2-darryl-archideld,
    3-bobson-dugnutt,
    4-sleve-mcdichael,
    5-mike-truk,
    6-dean-wesrey,
    7-dwigt-rortugal
    ]