[英]Multiplying lists and list of lists in Prolog
我目前正在开发Prolog程序,在弄清楚如何实现它方面遇到很多麻烦。
我想将诸如[1,2,2,1]之类的列表放入函数中。 我希望通过执行此示例将其乘以创建一个新矩阵。
1 * [1,2,2,1] which would yield [1,2,2,1]
2 * [1,2,2,1] which would yield [2,4,4,2]
2 * [1,2,2,1] which would yield [2,4,4,2]
1 * [1,2,2,1] which would yield [1,2,2,1]
我希望它可以在矩阵中一起创建所有这些元素,例如:
[[1,2,2,1],[2,4,4,2],[2,4,4,2],[1,2,2,1]].
最后一部分是我想自己乘以零。 因此,第二个点会将第二个点归零,形成最终矩阵:
[[0,2,2,1],[2,0,4,2],[2,4,0,2],[1,2,2,0]].
我希望有一个谓词,该谓词调用另一个使每个列表都位于其中的谓词。 所以这就是我的想法:
main(A,O):-
second(A,A,O).
second([],_,[]).
second([A|As],B,[O|Os]):- %creates the list of lists.
third(A,B,O),
second(As,B,Os).
third(_,[],[]).
third(A,[B|Bs],[O|Os]):-
fourth(A,B,O),
third(A,Bs,Os). %multiplies single digit by list.
fourth(A,B,0):- A == B.
fourth(A,B,O):- O is A * B.
我得到正确的矩阵,但不能得到零对角线。
我只是想不出一种正确的方法来获取对角线为零的矩阵。 有什么想法吗?
您可以通过引入指示您所在行和列的索引并检查匹配项来实现零:
main(A, O) :-
second(A, A, 0, O).
second([], _, _, []).
second([A|As], B, R, [O|Os]) :- %creates the list of lists.
third(A, B, 0, R, O),
R1 is R + 1,
second(As, B, R1, Os).
third(_, [], _, _, []).
third(A, [B|Bs], C, R, [O|Os]) :-
fourth(A, B, C, R, O),
C1 is C + 1,
third(A, Bs, C1, R, Os). %multiplies single digit by list.
fourth(_, _, X, X, 0).
fourth(A, B, C, R, O) :- C \== R, O is A * B.
校验:
| ?- main([1,2,2,1], L).
L = [[0,2,2,1],[2,0,4,2],[2,4,0,2],[1,2,2,0]] ? ;
no
maplist_with_index
断言其作品就像maplist
但管理的指标,隐含地假设给定的谓词接受指数作为其第一个参数:
maplist_with_index(Pred, L, M) :-
maplist_with_index_(Pred, 0, L, M).
maplist_with_index_(Pred, I, [H|T], [M|Ms]) :-
Pred =.. [P|Pt],
append([P,I|Pt], [H], NewPred),
Call =.. NewPred,
call(Call, M),
I1 is I + 1,
maplist_with_index_(Pred, I1, T, Ms).
maplist_with_index_(_, _, [], []).
然后,使用该谓词的矩阵程序如下所示:
main(A, O) :-
second(A, A, O).
second(M, A, O) :-
maplist_with_index(third(A), M, O).
third(R, A, E, O) :-
maplist_with_index(fourth(R, E), A, O).
fourth(X, X, _, _, 0).
fourth(C, R, A, B, O) :- C \== R, O is A * B.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.