Thelouras
Thelouras

Reputation: 880

Prolog predicate that compares values in facts

This is my first time using Prolog

I have employees

employee(eID,firstname,lastname,month,year) 

example :

employee(1,liz,white,4,2000).
employee(2,ted,johnson,5,1998).

I want to make a predicate senior(X,Y) that will return true if the first employee is older in the company.

I have this:

senior(X,Y) : -
  employee(X,firstname,lastname,month,year),
  employee(Y,firstname,lastname,month,year),
  X.year < Y.year.

but this always return false. I can't understand the reason.

How can I make this predicate work?

Upvotes: 0

Views: 377

Answers (2)

jasonix
jasonix

Reputation: 96

Is it mandatory that you do this with one rule? You could use one rule for comparing employees who were hired in different years, and a second rule for comparing employees who were hired in the same year. To expand on this, let's say you have employees listed this way:

employee(eid,year,month,day)

and, of course, a list of employees. You could use the following three rules:

% For employees that were hired in different years.
senior(Eid1,Eid2) :-
    employee(Eid1,X,_,_),
    employee(Eid2,Y,_,_),
    X<Y.

% For employees that were hired in the same year, different month.
senior(Eid1,Eid2) :-
    employee(Eid1,Year,X,_);
    employee(Eid2,Year,Y,_);    % Notice how one common variable "Year" is used
    X<Y.

% For employees that were hired in the same year, same month, different day,
% the rule is "expanded" from the previous one.
senior(Eid1,Eid2) :-
    employee(Eid1,Year,Month,X);
    employee(Eid2,Year,Month,Y);
    X<Y.

Make sure you don't forget and replace "Year" and/or "Month" with underscores, because then somebody hired on 2010-01-01 (ISO 8601) would be shown as senior to someone hired on 2005-12-12.

Then again, perhaps you should catalogue all dates in ISO 8601:2004. No matter how big your employee list, you could write a small script to convert

employee(eID,firstname,lastname,month,year)

to

employee(eID,firstname,lastname,yyyymm)

Upvotes: 1

Paulo Moura
Paulo Moura

Reputation: 18663

In Prolog, variables start with either an underscore or an upper case letter. E.g. firstname is an atom, i.e. a constant, but FirstName is a variable. But, in your specific question, you don't care about the employee names. Thus, you can replace those arguments by the anonymous variable:

senior(X,Y) : -
  employee(X, _, _, Xmonth, Xyear),
  employee(Y, _, _, Ymonth, Yyear),
  ...

Can you now complete the code by writing the necessary comparisons using the Xmonth, Xyear, Ymonth, and Yyear variables?

Upvotes: 1

Related Questions