2014-11-24 48 views
-1

獲取給定的數據庫,例如添加動態數量的數字

input(80). 
input(30). 
input(25). 
input(90). 

計算輸入量超過50倍100,僅限於採取/ 1輸入。 例如

%compute(?integer). 
compute(I). 
I = 200 %seeing as input(80) and input(90) matches the condition of being above 50 

我曾嘗試以下序言代碼來模擬天生的計算功能,不成功:

compute(I) :- input(G), G>50, I is I+100. 

,我打算將我+ 100不起作用。

+0

你'compute'不起作用,因爲從邏輯上說,*'計算(我)'爲真,如果'G'是輸入,' G> 50','I是I + 100'。 「我」沒有初始值,如果有的話,它第一次成功了一次'G> 50'。你真的想要聚合所有可能的值,可以用'findall'完成。 – lurker 2014-11-24 18:43:47

回答

1

Prolog逐個搜索匹配,並返回每個輸入的查詢結果,而不是全部輸入。要收集所有匹配值,您可以使用bagof,setoffindall metapredicates。 這裏是做你定義什麼代碼:

input(80). 
input(30). 
input(25). 
input(90). 

compute(I) :- 
    findall(X, (input(X), X>50), L), % Find all X's that are 'input' and >50 into L 
    length(L,Len),     % Find the length of L and put into Len 
    I is Len * 100.     % I is Len times 100 
+0

這工作,謝謝你尤金Sh。 :) – user3711518 2014-11-24 19:02:41

+0

@false,對不起,我刪除了我的評論。這不是很清楚。 – lurker 2014-11-24 21:56:56