Prolog time comparison

Say I have a time structure with the format time(hour, minute) . How can I write 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 many years of working with C, and the whole language is very confusing to me.

+4
source share
2 answers

Assuming hours ( H , H1 , H2 ) and minutes ( M1 , M2 ) are numbers, you can write them as:

 earlier(time(H, M1), time(H, M2)) :- !, M1 < M2. earlier(time(H1, _), time(H2, _)) :- H1 < H2. 

The characters in the second line are anonymous variables, i.e. we won’t assign names in minutes if we can decide what time is earlier by just looking at the clock.

+5
source

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). 
+6
source

Source: https://habr.com/ru/post/1336732/


All Articles