我找到了一个可以对矩阵进行乘法运算的代码。
如果我输入:
% 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).
如果我输入:
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]] .
附:我是Prolog新手。谢谢!
sumlist
版本,但使用=
而不是is
。 - Nick Barnes