检查动态谓词是否包含值的方法

时间:2020-10-08 21:51:53

标签: list prolog predicate

Prolog的新手。 目标是检查动态谓词是否包含特定值。 可以通过以下方式进行操作,但不起作用:

:- dynamic storage/1. 

not(member(Z,storage)), // checking if Z is already a member of storage - this does not work. 
assert(storage(Z)). // asserting Z if above is true

您能解释一下该怎么做吗?

1 个答案:

答案 0 :(得分:2)

喜欢吗?

:- dynamic storage/1. 

append_to_database_but_only_once(Z) :- 
   must_be(nonvar,Z),      % Z must be bound variable (an actual value)
   \+ storage(Z),          % If "storage(Z)" is true already, fail!
   assertz(storage(Z)).    % ...otherwise append to the database

等等:

?- append_to_database_but_only_once(foo).
true.

?- storage(X).
X = foo.

?- append_to_database_but_only_once(foo).
false.

请注意,您不需要使用member/2查询任何数据结构或列表。使用assertz/1,您将更改Prolog数据库本身!因此,之后您只需要执行相应的查询storage(Z)