Lopson
Lopson

Reputation: 1217

Calculating Time Difference in Prolog

I'm having some trouble writing a relatively simple predicate in Prolog. This predicate is supposed to receive two arguments in the format Hours:Minutes, calculate the difference between the two and check if that value is greater or equal to 40 minutes.

Here's what I have so far:

time(Time1, Time2):- 
    X:Y =:= Time1, A:B =:= Time2, calculate_time(X, Y, A, B).

calculate_time(X, Y, A, B):-
    Y - X =:= 0,
    B - A >= 40, !.
calculate_time(X, Y, A, B):-
    Y - X > 0.

This, as you can imagine, is giving an error, namely:

?- time(10:00, 10:55).
 ERROR at  clause 1 of user:time/2 !!
 INSTANTIATION ERROR- in arithmetic: expected bound value

So, as far as I can understand, he thinks that he's been given four arguments. Why is he reacting this way? Also, at the beginning of the file, I have the following commands:

:-op(500,xfy,:).
:-op(600,xfy,/).

This predicate is supposed to be a part of a larger program, so these two lines need to stay in the file. I'm not using any module and I'm using YAP.

Any help would be appreciated!

Upvotes: 1

Views: 1913

Answers (2)

Yhprums
Yhprums

Reputation: 189

Returns true if time difference is greater or equal to 40 minutes.

Program:

time(A:B,X:Y):- 
    HOURS is X - A,
    MINUTES is Y - B,
    LENGTH is HOURS*60 + MINUTES,
    LENGTH >= 40.

test1:

?- time(06:40,09:45).
true.

test2:

?- time2(09:40,09:45).
false.

Upvotes: 0

gusbro
gusbro

Reputation: 22585

You have two problems. The first one is that you are using =:=/2 which tests whether two numeric expressions evaluates to the same, but you are feeding it with a structure instead of numeric expressions.

It also seems that your logic is not totally right (last clause does not make sense, you are subtracting the minutes from the hours of the first time)

Upvotes: 2

Related Questions