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

问题描述

我有一个序言谓词:

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

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

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?

推荐答案

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

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

07-05 03:54