2016-10-25 428 views
3

我需要爲Prolog創建笛卡爾積計算器。它應該是這樣的:Prolog - 笛卡爾積計算器

輸入:product([1,2,3], [a,b], X).

輸出:X = [[1,a],[2,a],[3,a],[1,b],[2,b],[3,b]].

我知道有在互聯網上的例子,但我想寫自己的東西。

這是我的代碼,我認爲它非常接近,但由於某些原因,它不能正常工作。任何想法,傢伙?

% call new with 4 parameters (so we can keep List1 in memory) 
product(L1,L2,L3):- product(L1,L2,L3,L1). 

% stop when both List1 and List2 are empty 
product([], [], [], []). 

% first list is empty, recreate it and work it again with the next element of second list (and shorten memory) 
product([], [_|T2], List3, [H4|T4]):- 
    product([H4|T4], T2, List3, T4). 

%go through first list and always first element of second list to our answer 
product([H1|T1], [H2|T2], [[H1,H2]|T3], List4):- 
    product(T1, [H2|T2], T3, List4). 

回答

2

作爲由編碼器(1)表示,則應將終端從子句

改變
product([], [], [], []). 

product(_, [], [], _). 

但ins't足夠。

您shuold從

product([], [_|T2], List3, [H4|T4]):- 
    product([H4|T4], T2, List3, T4). 

澈第三條改爲

product([], [_|T2], List3, L4):- 
    product(L4, T2, List3, L4). 

我的意思是:在一個錯誤消耗保存清單1.

有了您的版本,從

product([1,2,3,4,5], [a,b,c,d], X), 

你只有

[[1,a],[2,a],[3,a],[4,a],[5,a],[1,b],[2,b],[3,b],[4,b],[5,b],[2,c],[3,c],[4,c],[5,c],[3,d],[4,d],[5,d]] 

那就是:你鬆[1,c][1,d][2,d]

+0

謝謝! (+1)指出第二個錯誤! – coder

+0

是的,這有效,我明白爲什麼。謝謝你們倆。 – PadaKatel

3

您應該更改條款:

product([], [], [], []). 

到:

product(_, [], [], _). 

這是因爲當L2變成空它要求產品(L1,[],L3,L4),其中L1和L4不是空的。您的鹼情況下必須是當L2變空(然後L3變空作爲輸出列表)和其他列表可以具有元素:

?- product([1,2,3], [a,b], X). 
X = [[1, a], [2, a], [3, a], [1, b], [2, b], [3, b]] ; 
false.