Prolog-笛卡尔积计算器 [英] Prolog - Cartesian product calculator
问题描述
我需要为Prolog创建一个笛卡尔乘积计算器.它应该像这样工作:
I need to create a Cartesian product calculator for Prolog. It should work like this:
输入:product([1,2,3], [a,b], X).
输出:X = [[1,a],[2,a],[3,a],[1,b],[2,b],[3,b]].
我知道互联网上有一些例子,但是我想自己写点东西.
I know there are examples on the Internet, but I wanted to write something myself.
这是我的代码,我认为它已经很接近了,但是由于某种原因,它并不完全有效.大家有什么想法吗?
This is my code and I think it's pretty close, but for some reason it doesn't exactly work. Any ideas, guys?
% 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).
推荐答案
正如Coder(+1)所说,您应该将terminal子句更改为
As said by Coder (+1), you should change the terminal clause from
product([], [], [], []).
到
product(_, [], [], _).
但是还不够.
您应该更改第三个子句
product([], [_|T2], List3, [H4|T4]):-
product([H4|T4], T2, List3, T4).
到
product([], [_|T2], List3, L4):-
product(L4, T2, List3, L4).
我的意思是:使用已保存列表1是一个错误.
I mean: is an error to consume the saved list 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]
.
That is: you loose [1,c]
, [1,d]
and [2,d]
.
这篇关于Prolog-笛卡尔积计算器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!