我找到了一个乘法矩阵的代码.
% SWI-Prolog has transpose/2 in its clpfd library
:- use_module(library(clpfd)).
% N is the dot product of lists V1 and V2.
dot(V1, V2, N) :- maplist(product,V1,V2,P), sumlist(P,N).
product(N1,N2,N3) :- N3 is N1*N2.
% Matrix multiplication with matrices represented
% as lists of lists. M3 is the product of M1 and M2
mmult(M1, M2, M3) :- transpose(M2,MT), maplist(mm_helper(MT), M1, M3).
mm_helper(M2, I1, M3) :- maplist(dot(I1), M2, M3).
Run Code Online (Sandbox Code Playgroud)
如果我打字:mult([[1,2],[3,4]],[[5,6],[7,8]],X).
那我就明白了 X = [[19, 22], [43, 50]].
但我怎么能得到一个 X = [[1*5+2*7, 1*6+2*8], [3*5+4*7, 3*6+4*8]] .
PS我是prolog的新手.谢谢!
这很简单:不要使用is/2评估算术表达式,只需将它们保留为未评估状态,并使用复合项而不是其数值.我为产品/ 3做了:而不是
product(N1,N2,N3) :- N3 is N1*N2.
Run Code Online (Sandbox Code Playgroud)
我写:
product(N1, N2, N1*N2).
Run Code Online (Sandbox Code Playgroud)
您只需要编写相应版本的sumlist/2.