问题描述
我正在尝试编写一条规则,该规则可以返回两个列表(相同长度)中每个元素的乘积之和.
I am trying to write a rule that can return the sum of the product of each element from two lists (same length).
这是我现在拥有的:
sum(0, _, []).
sum(Result, [H1|T1], [H2|T2]) :-
sum(Remaining,T1, T2),
Remaining is Result - (H1*H2).
如果未实例化列表之一,则它将不起作用.为了实现以下目的,我需要进行哪些更改?
It won't work when one of the list is not instantiated. What changes I need to make in order to make the following possible?
sum([1,2],X,3).
X = [3,0].
谢谢.
推荐答案
您正在计算的内容通常称为点积(也称为标量积或内部积).
What you are calculating is commonly referred to as a dot product (also known as scalar product or inner product).
您编写的内容不允许使用库.那肯定是指外部库,而不是SWI Prolog中的标准库,对吧?
You write you are not allowed to use libraries. That surely refers to external libraries---not to the standard library that is part of SWI Prolog, right?
以下谓词list_list_dotProduct/3
大致对应于您实现的代码.它使用有限域约束(#>=)/2
和(#=)/2
来进行非单向整数运算:
The following predicate list_list_dotProduct/3
roughly corresponds to the code you implemented. It uses finite domain constraints (#>=)/2
and (#=)/2
to allow for non-unidirectional integer arithmetic:
:- use_module(library(clpfd)).
list_list_dotProduct([],[],0).
list_list_dotProduct([X|Xs],[Y|Ys],Sum) :-
X #>= 0,
Y #>= 0,
Sum #= X*Y + Sum0,
list_list_dotProduct(Xs,Ys,Sum0).
考虑以下查询:
?- list_list_dotProduct([1,2],Xs,3), label(Xs).
Xs = [1, 1] ;
Xs = [3, 0].
作为额外的好处,这是一个替代实现,该实现基于预定义的谓词same_length/2
,ins/2
和scalar_product/4
:
As an added bonus, here's an alternative implementation that is based on the predefined predicates same_length/2
, ins/2
, and scalar_product/4
:
list_list_dotProduct(Xs,Ys,Prod) :-
same_length(Xs,Ys),
Xs ins 0..sup,
Ys ins 0..sup,
scalar_product(Xs,Ys,#=,Prod).
这篇关于序言:将2个列表与其中1个列表相乘是否未实例化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!