Prolog Matrix Multiplication

I found code that multiplies matrices.

% 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). 

If I type: mult([[1,2],[3,4]],[[5,6],[7,8]],X). then I get X = [[19, 22], [43, 50]].

But how can I get X = [[1*5+2*7, 1*6+2*8], [3*5+4*7, 3*6+4*8]] .

PS I'm new to the prologue. Thanks!

+4
source share
1 answer

It's easy: instead of evaluating arithmetic expressions with is / 2, just leave them unvalued and use compound terms instead of their numerical values. I do this for the product / 3: Instead

 product(N1,N2,N3) :- N3 is N1*N2. 

Writing:

 product(N1, N2, N1*N2). 

You only need to write the appropriate version of sumlist / 2.

+6
source

Source: https://habr.com/ru/post/1403444/


All Articles