Re: comparison predicates



Guybrush Threepwood" <spambak@xxxxxxxxxxx> wrote in message
news:pan.2006.01.10.23.39.21.455183@xxxxxxxxxxxxxx
> Is it possible in SWI-Prolog to define your own comparison predicates?
> Like:
>
> <(date(_, _, Year1), date(_, _, Year2)):-
> Year1 < Year2.
>
>
> <(date(_, Month1, Year1), date(_, Month2, Year2)):-
> Year1 = Year2,
> Month1 < Month2.
>
>
> <(date(Day1, Month1, Year1), date(Day2, Month2, Year2)):-
> Year1 = Year2,
> Month1 = Month2,
> Day1 < Day2.
>


Yes.
To define an operator, use "op/3".

The "op/3" command needs to be run, for it to work,
so it needs to placed after a ":-" in your source code file.

So your file would be something like this :

% Start of file.
% I have named the operator "compare".

:- op(500, xfy, compare).

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


compare(date(_, Month1, Year1), date(_, Month2, Year2)):-
Year1 = Year2,
Month1 < Month2.


compare(date(Day1, Month1, Year1), date(Day2, Month2, Year2)):-
Year1 = Year2,
Month1 = Month2,
Day1 < Day2.

% End of file.

Consult the file, then use the new operator, like this :

?- X is date(1,2,1998) compare date(2/3/1999).
Yes.

?-


You can also use the operator between the two arguments,
when defining the operator.
As shown here :

% Start of file.
:- op(500, xfy, compare).

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


date(_, Month1, Year1) compare date(_, Month2, Year2) ):-
Year1 = Year2,
Month1 < Month2.


date(Day1, Month1, Year1) compare date(Day2, Month2, Year2) ):-
Year1 = Year2,
Month1 = Month2,
Day1 < Day2.

% End of file.


In SWI Prolog, all existing operators can be redefined,
so you can use '<' instead of 'compare', if you wish.

Perhaps you could call your operator '<date',
or use some other unique name.


--
Martin Sondergaard,
London.



.