我需要爲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).
謝謝! (+1)指出第二個錯誤! – coder
是的,這有效,我明白爲什麼。謝謝你們倆。 – PadaKatel