开发者

Time comparison in Prolog

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 ju开发者_如何学Cst starting out with Prolog after years of working with C, and the entire language is very very confusing to me.


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).


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜