I am trying to write a rule that can return the sum of the product of each element from two lists (same length).
Here is what I have right now:
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].
Thanks.
What you are calculating is commonly referred to as a dot product (also known as scalar product or inner product).
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?
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:Consider the following query:
As an added bonus, here's an alternative implementation that is based on the predefined predicates
same_length/2
,ins/2
, andscalar_product/4
: