2014-03-19 59 views
0

您好我在序言一個簡單的時鐘,測量時間在5分鐘間隔Prolog的整數比較

nextTime(Hrs:Mins1, Hrs:Mins2) :- nextMins(Mins1, Mins2). 
nextTime(Hrs1:'55', Hrs2:'00') :- nextHrs(Hrs1, Hrs2). 

nextHrs('12', '13'). 
nextHrs('13', '14'). 
nextHrs('14', '15'). 
nextHrs('15', '16'). // and so on 

nextMins('00', '05'). 
nextMins('05', '10'). 
nextMins('10', '15'). 
nextMins('15', '20'). // and so on 

現在我想寫一個謂語,讓我說時間t2是否已晚或時間t1之前,它聽起來很簡單,但我不知道如何比較謂詞中的兩個整數。

我試過的東西喜歡:

after(H1:M1, H2:M2) :- (H1 < H2). 

arithmetic(X,Y) :- (X<Y). 
after(H1:M1, H2:M2) :- arithmetic(H1,H2). 

進出口真正的新的Prolog所以上面似乎傻了一些。 所以我的實際問題是如何比較Prolog中謂詞定義中的兩個整數。

+0

是否有原因使用字符串而不是數字而不是數字?如果您使用整數,@CapelliC顯示的解決方案將按需要工作。 – lurker

回答

2

一個有用的Prolog功能它是'Standard Order of Terms'。然後,你可以寫

after(T1, T2) :- T1 @< T2. 
+0

只要時間是'HH:MM',這將工作得很好,其中HH和MM是整數而不是字符串。所以''3:30'@''13:40'''是錯誤的,但是'3:30 @<13:40.'是真的。 – lurker

+0

@mbratch:也許OP已經意識到了這個問題,因爲他發佈了前導零的原子... – CapelliC

+0

是的,這是一個很好的觀點。如果在字符串格式中使用前導零,那麼這將工作得很好。這很有道理。 – lurker

1

您沒有任何整數:你有原子原子'9'比較大於原子12

只要你的原子總是2個十進制數字(的'09'代替'9'),你可以使用compare/3

after(H1:M1,H2,M2) :- compare('>' , H1:M1 , H2:M2) . 

on_or_after(H1:M1,H2:M2) :- compare('>' , H1:M1 , H2:M2) . 
on_or_after(H1:M1,H2:M2) :- compare('=' , H1:M1 , H2:M2) . 

如果你改變你的謂語使用整數代替的原子

nextHrs(12, 13). 
nextHrs(13, 14). 
nextHrs(14, 15). 
nextHrs(15, 16). // and so on 

nextMins(00, 05). 
nextMins(05, 10). 
nextMins(10, 15). 
nextMins(15, 20). // and so on 

你可以使用arithmetic comparison operators和簡單的寫類似:

compare_time(H1:M1 , H2:M2 , '<') :- H1 < H2 . 
compare_time(H1:M1 , H1,M2 , '<') :- M1 < M2 . 
compare_time(HH:MM , HH:MM , '=') . 
compare_time(H1:M1 , H2:M2 , '>') :- H1 > H2 . 
compare_time(H1:M1 , H1:M2 , '>') :- M1 > M2 . 

如果你保持你的原子作爲持續2位數的文本價值,你仍然可以做同樣的事情,但你必須使用the standard order of terms operators,而不是算術比較操作符。

compare_time(H1:M1 , H2:M2 , '<') :- H1 @< H2 . 
compare_time(H1:M1 , H1,M2 , '<') :- M1 @< M2 . 
compare_time(HH:MM , HH:MM , '=') . 
compare_time(H1:M1 , H2:M2 , '>') :- H1 @> H2 . 
compare_time(H1:M1 , H1:M2 , '>') :- M1 @> M2 . 
+0

如果你使用'@<'等,就像@CapelliC指出的那樣,你不需要單獨檢查小時和分鐘,因爲如果小時和分鐘是整數,Prolog會在比較時做「正確」的事情,因爲例如,'3:25 @<13:20'(這將是「真」)。所以你的'compare_time(...,'<')'只需要一個子句:'compare_time(T1,T2,'<'): - T1 @ lurker

+0

尼古拉斯,作爲我的聲明的附錄,OP可以使用字符串數小時和分鐘,然後使用'T1 @ lurker