Reputation: 1429
Say I have a structure time
with the format time(hour, minute)
. How would I go about writing a rule to compare them? Something along the lines of compareTime(time1,time2) that returns yes if time1 is strictly before time2.
I am just starting out with Prolog after years of working with C, and the entire language is very very confusing to me.
Upvotes: 4
Views: 2610
Reputation: 10672
Assuming that hours (H
, H1
, H2
) and minutes (M1
, M2
) are numbers, you can write it as:
earlier(time(H, M1), time(H, M2)) :- !, M1 < M2.
earlier(time(H1, _), time(H2, _)) :- H1 < H2.
The underscores in the 2nd line are anonymous variables, i.e. we don't bother assigning names to the minutes if we can decide on which time is earlier just by looking at the hours.
Upvotes: 5
Reputation: 10242
The standard compare/3
predicate already does what you want:
?- compare(O, time(1,1), time(1,1)).
O = (=).
?- compare(O, time(1,1), time(1,2)).
O = (<).
?- compare(O, time(1,3), time(1,2)).
O = (>).
?- compare(O, time(1,3), time(2,2)).
O = (<).
?- compare(O, time(3,2), time(2,2)).
O = (>).
so...
earlier(T1, T2) :- compare((<), T1, T2).
Upvotes: 6