本文介绍了Prolog 初学者:如何为谓词中的每个变量创建唯一值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个序言谓词:

Add( [A|B] , Answer ) :-
    ...
    ~ Add everything in the list to come up with answer
    ...

我现在想实现 AddUnique,当我给它两次变量时,它会返回列表中所有内容的唯一值除了.

I would now like to implement AddUnique that would return unique values for everything in the list except when I give it the variable twice.

以下是逻辑上等效的内容:

Here are somethings that are logically equivalent:

?- AddUnique([A, B, C], 10). 等价于: ?- Add([A, B, C], 10), A !=B, B != C, A != C.

还有:

?- AddUnique([A, B, B], 10). 等价于: ?- Add([A, B, B], 10), A !=B.

还有:

?- AddUnique([A, B, B], 10).NOT 等价于:?- Add([A, B, B]], 10), A != B, B!=B.

如果 ?- AddUnique([A,B,C,D], 4). 是给定的,它应该返回 false,因为它不能带有唯一的正整数加四.

If ?- AddUnique([A,B,C,D], 4). is given it should return false since it cannot come with unique positive integers that add to four.

如果给定 ?- AddUnique([A,A,A,A], 4).,它应该返回 A=1.

If ?- AddUnique([A,A,A,A], 4). is given it should return A=1.

问题:如何在谓词中移动 A != B, B != C, A != C. 逻辑而不执行类似这样的操作 A != A?

Question: How can I move the A != B, B != C, A != C. logic inside the predicate without doing something like this A != A?

推荐答案

这是我想出的解决方案.它只会将输入分配为小于 10 的数字,但效果很好!

This is the solution that I came up with. It will only assign the input to be numbers less than ten but works great for that!

addUnique( A, Answer ) :- 
    used(A,[0,1,2,3,4,5,6,7,8,9],_),
    add(A,Answer).

add( [A|B] , Answer ) :-
    ~ Add everything in the list to come up with answer ~.


% ================================
% Ensures that all variables are unique.  
% ================================

% Base case: Assigned variables unique values
used([], Nin, Nin).

% Have already assigned a value to this variable
used([A|B], Nin, Nout) :-
        integer(A),
        helper(B,Nin,Nout).

% Have not assigned a value to this variable yet
% Assign it and remove it from the list.  
used( [A|B] , Nin, Nout) :-
        member(A,Nin),
        delete(Nin,A,Temp),
        helper(B,Temp,Nout).

这篇关于Prolog 初学者:如何为谓词中的每个变量创建唯一值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-27 07:17