简体   繁体   English

Prolog-将列表与列表列表相乘

[英]Prolog-Multiplying a list with a list of lists

I'm trying to simulate a product of a matrix with a vector using these two predicates: 我正在尝试使用这两个谓词来模拟矩阵与向量的乘积:

eva([], [], []).
eva([A|A1], [W], [Res|R1]) :-
    vectormultiplication(A, W, Res),
    eva(A1, W, R1).

vectormultiplication([A], [W], [A*W]).
vectormultiplication([A|A1], [W|W1], [A*W|Out1]) :-
    vectormultiplication(A1, W1, Out1).

Where the [A|A1] in eva is a matrix (or a list of lists), [W] is a vector (a list),and [Res|R1] is the resulting product. 在eva中的[A|A1]是矩阵(或列表的列表)的情况下, [W]是向量(列表), [Res|R1]是结果乘积。 vectormultiplication is supposed to go multiply each list in the list with the vector W . vectormultiplication应该将列表中的每个列表与向量W相乘。 However, this strategy just produces a false response. 但是,这种策略只会产生错误的反应。 Is there anything apparent that I'm doing wrong here that prevents me from getting the desired product? 有什么迹象表明我在这里做错了阻止我得到所需的产品吗? I'm currently using SWI Prolog version 5.10 我目前正在使用SWI Prolog版本5.10

Well, your first problem is that you think A*W is going to do anything by itself. 那么,你的第一个问题是你认为A*W会自己做任何事情。 In Prolog, that's just going to create the expression A*W , no different from *(A,W) or foo(A, W) --without is/2 involved, no actual arithmetic reduction will take place. 在Prolog中,这只是创建表达式A*W ,与*(A,W)foo(A, W)没有区别 - 不涉及is/2 ,不会发生实际的算术减少。 That's the only real problem I see in a quick glance. 这是我在快速浏览中看到的唯一真正的问题。

you have 2 other problems apart that evidenced by Daniel (+1): here a cleaned up source 丹尼尔(+1)证明你还有另外两个问题:这里是一个清理过的来源

eva([], _, []).  % here [] was wrong
eva([A|A1], W, [Res|R1]) :- % here [W] was wrong
    vectormultiplication(A, W, Res),
    eva(A1, W, R1).

vectormultiplication([A], [W], [M]) :-
    M is A*W.
vectormultiplication([A|A1], [W|W1], [M|Out1]) :-
    M is A*W,
    vectormultiplication(A1, W1, Out1).

test: 测试:

?- eva([[1,2],[3,5]],[5,6],R).
R = [[5, 12], [15, 30]]

when handling lists, it's worth to use maplist if available 处理列表时,如果可用的话,使用maplist是值得的

eva(A, W, R) :-
    maplist(vectormultiplication1(W), A, R).

vectormultiplication1(W, A, M) :-
    maplist(mult, A, W, M).

mult(A, W, M) :-
    M is A*W.

Note I changed the order of arguments of vectormultiplication1, because the vector is a 'constant' in that loop, and maplist append arguments to be 'unrolled'. 注意我改变了vectormultiplication1的参数顺序,因为向量在该循环中是一个“常量”,而maplist附加的参数是“展开的”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM