Prolog: Multiplying 2 lists with 1 of them not ins

2019-07-24 19:16发布

问题:

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.

回答1:

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:

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

Consider the following query:

?- list_list_dotProduct([1,2],Xs,3), label(Xs).
Xs = [1, 1] ;
Xs = [3, 0].

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