【问题标题】:Way to check if dynamic predicate contains a value检查动态谓词是否包含值的方法
【发布时间】:2020-10-08 21:51:53
【问题描述】:
对 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
你能解释一下这应该怎么做吗?
【问题讨论】:
标签:
list
prolog
predicate
【解决方案1】:
像这样?
:- 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)。