作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我需要为 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).
最佳答案
在 SWI-Prolog 中,也可以使用 findall/3 生成笛卡尔积。和 member/2谓词:
:- initialization(main).
:- set_prolog_flag(double_quotes, chars).
main :-
product([1,2,3], [a,b], X),
writeln(X).
product(A,B,C) :-
findall([X,Y],(member(X,A),member(Y,B)),C).
该程序打印
[[1,a],[1,b],[2,a],[2,b],[3,a],[3,b]]
.
关于list - Prolog - 笛卡尔积计算器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40244936/
我是一名优秀的程序员,十分优秀!