2013-11-25 28 views
2

我是XSB序言新手,我試圖解決這個問題。XSB序言:列表出現問題

我有產品的價格和一些訂單。它看起來像這樣:

price(cola,3).       
price(juice,1).   
price(sprite,4). 
// product for ex. is cola with a price of 3 (something, it doesn't matter which currency) 

order(1, [cola,cola,sprite]). 
order(2, [sprite,sprite,juice]).  
order(3, [juice,cola]).  // the number here is the number of the order 
          // and the list represents the products that 
          // belong to that order 

現在,我的任務是寫一個名爲bill/2的新函數。此功能應該取訂單的編號,然後以相同的訂單(清單)總結產品的所有價格。

喜歡的東西:

|?-bill(1,R). 

R= 10 ==> ((cola)3 + (cola)3 + (sprite)4 = 10)    

|?-bill(2,R). 

R= 9 ==> ((sprite)4 + (sprite4 + (juice)1 = 9) 

等等...我知道怎麼去訂單的數量,但我不知道如何從列表中獲取每個產品,才能進去它的價格,所以我可以總結一下。

在此先感謝。

回答

0

在普通的Prolog,先把所有數字在列表中,再總結列表:

bill(Ord, Tot) :- 
    order(Ord, Items), 
    findall(Price, (member(I, Items), price(I, Price)), Prices), 
    sum_list(Prices, Tot). 

但由於XSB有可用的製表,有可能是一個更好的辦法,使用一些聚集功能。

+0

'setof/3'''''allal' – false

+0

@false:bagof then,or will lose duplicate items prices – CapelliC

+0

您假設多個答案意味着多個(不同的)解決方案是一個非常脆弱的解決方案。也就是說,它遲早會崩潰。但我同意不能用'setof'來逐字替換'findall' – false