2012-03-26 28 views
4

行列を乗算するコードが見つかりました。行列乗算プロローグ

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

P.S.を得ることができる方法私はプロローグの初心者です。 ありがとう!

答えて

6

これは簡単です:is/2で算術式を評価するのではなく、単純に評価されずに数値の代わりに複合項を使用するだけです。私は、製品/ 3のためにそれを実行します。その代わり

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

の私が書く:

product(N1, N2, N1*N2). 

あなただけsumlist/2の対応するバージョンを記述する必要があります。

+0

sumlist/2の変更方法を教えてください。 –

+0

私はあなたに示した変更に類似しています:sumlist/2をとり、is/2で算術式を評価する代わりに、和自体を項として表現します(今度は*の代わりにfunctor +を使用します)。 – mat

+0

あなたは表示できますか?私は理解していません... –