Search code examples
prologpredicate

Prolog, X is older than Y


I need to write a predicate that gives true if X is older than Y. MY codes are below. I don't see anything wrong yet. Please help me.

born(jan, date(20, 3, 1977)).

born(joris, date(17, 3, 1995)).

born(jesus, date(24, 12, 0)).

born(joop, date(30, 4, 1989)).

before(date(_, _, Year1), date(_, _, Year2)) :-
      Year1 < Year2.

before(date(_, Month1, Year ), date(_, Month2, Year)) :-
      Month1 < Month2.

before(date(Day1, Month, Year ), date(Day2, Month, Year)) :-
      Day1 > Day2.

older(X, Y) :-
      X \= Y,
      born(X, B1),
      born(Y, B2),
      before(B1, B2). 

Query shoul give this.

?- older(jesus, Y).
jan,
joris,
joop.

Solution

  • The comparison X\= Y in older/2 is being issued when either X and/or Y may be uninstantiated which will fail. You have to issue that comparison after you know they are instantiated with proper values, i.e. after calling born/2 for each of them:

    older(X, Y) :-
          born(X, B1),
          born(Y, B2),
          X \= Y,
          before(B1, B2). 
    

    Also, as mentioned in the comments, the third clause of before/2 should be:

    before(date(Day1, Month, Year ), date(Day2, Month, Year)) :-
          Day1 < Day2.
    

    Sample run:

    ?- older(jesus, Y).
    Y = jan ;
    Y = joris ;
    Y = joop ;
    false.