Prolog: Multiplying 2 lists with 1 of them not instantiated?

妖精的绣舞 提交于 2019-12-11 02:16:09

问题


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


来源:https://stackoverflow.com/questions/29424471/prolog-multiplying-2-lists-with-1-of-them-not-instantiated

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!