I have facts like that : student(stud01, 'Programming 1', 90). student(stud01, 'Math 1', 78). student(stud01, 'Statistics 1', 94). student(stud01, 'Electronics 1', 81). student(stud01, 'Management', 66). student(stud01, 'English', 83).
i want to build a predict that take the student id and and put all its grade in list and after that take the max grade
i try this : stuGrade(ID,List):- stuGrade([],ID,List).
stuGrade(TmpList,ID,List):- student(ID,Course,Grade), not(mem([ID],TmpList)), !, append_List([Grade],TmpList,NewTmpList), stuGrade(List,ID,NewTmpList).
stuGrade(List,ID,List).
maxStudentGrade(ID,Max):- stuGrade(ID,L), max(L,Max).
but the problem that after using ?-trace. i see that the output list containing only the first grade (90) how can i slove this problem
CodePudding user response:
Suppose that you begin with ?- stuGrade(stu01, List).
Then you will get the first student entry at least. And you say there is some issue after that.
So, a simple way to check is to test by using the first part of the query, such that,
?- ID = stu01, TmpList = [],
student(ID,Course,Grade),
not(mem([ID],TmpList)), !.
When you find its result is false
, stop and check the last predicate.
Using break points
trace/0
and nodebug/0
are nice tools.
You may want to check issues by like the following,
stuGrade(TmpList, ID, List) :-
student(ID, Course, Grade),
trace, % <------------------ Put a break point here.
not(mem([ID], TmpList)),
nodebug, % <----------------- Here, stop tracing.
!,
append_List([Grade], TmpList, NewTmpList),
stuGrade(List, ID, NewTmpList).
Good luck.
CodePudding user response:
And you code...
stuGrade(ID,List):- stuGrade([],ID,List).
stuGrade(TmpList, ID, List):-
student(ID, Course, Grade),
not(mem([ID], TmpList)),
!,
append_List([Grade], TmpList, NewTmpList),
stuGrade(List, ID, NewTmpList).
stuGrade(List,ID,List).
Not bad. But, consider the first clause of stuGrade/3
.
When you get a Grade
, it's prepended to TmpList
and you get NewTmpList
. But at the next line, the newly built list is put as the third argument, as you know that it's for the final returned List
.
It cannot be that. The first parameter of stuGrade/3
, TmpList
, is the accumulating parameter. Then NewTmpList
might be placed as the first argument of the recursive query, such that stuGrade(NewTmpList, ID, List)
.