Search code examples
prologpredicate

How to return difference in years in Prolog?


Say I have a db containing events:

events('Second war',1400,date(1984,1,1)).
events('First war',3000,date(1944,9,1)).

And want to make a predicate to calculate the time difference in year between a specific year and the event, that returns true if for example we enter:

timelapse('First war', 2000, 56 ).

Because the difference is 56 years, and if is entered

timelapse('First war', 2000, X ).

It returns X=56.

For now I have this function, but it gives warning and doesn't execute properly:

timelapse(E, D, DF) :- events(E,date(X,_,_),_), DY is X,
                DY > D -> DF = "invalid"; DF is D-DY.

How can I write this predicate?


Solution

  • What about this?

    timelapse(E, D, "invalid") :- 
        events(E,_,date(DY,_,_)), 
        DY > D,
        !.
    
    timelapse(E, D, DF) :- 
        events(E,_,date(DY,_,_)), 
        DF is D-DY.
    

    Note that events(E,date(X,_,_),_) from your code will not be unifiable with events('First war',3000,date(1944,9,1)) - the order is wrong.