PTN
PTN

Reputation: 1692

Look up X in table Prolog

How do I get my Prolog code to return something in the database instead of just answering yes and no?

I have this small table

student('Pelt', '67890').
grade('PH100', '67890', 'C plus').

How do I write a lookup function that returns 'C plus' when I pass in 'Pelt'? This is what I have but I don't think it's going anywhere.

lookupGrade(X) :- student(X, Y), grade(W, Y, Z).

Upvotes: 1

Views: 583

Answers (1)

max66
max66

Reputation: 66200

Prolog rules don't return values as C functions.

In you want extract the grade of a student you should pass two elements to your lookupGrade; but (suggestion from Mat; thanks) I change the name in student_grade (the reason is explained at the end).

The rule could be something like

student_grade(Name, Grade) :- student(Name, Code), grade(_, Code, Grade).

Using it as

 student_grade('Pelt', G)

you "unify" in G the value 'C plus'.

Note that this rule works also in the opposite direction; with

 student_grade(N, 'C plus')

you unify 'Pelt' in N.

And this is the reason why lookupGrade is a bad name: can be a "lookup grade" if you pass an atom as name and a variable for grade; can be a "lookup student" if you pass an atom as grade and a variable for name; can be (toghether with findall/3, by example) used to find all matches student/grade if you pass to it two variables.

Upvotes: 4

Related Questions