Prolog 中的谓词列表 [英] List of predicates in Prolog
问题描述
是否可以定义一个由谓词组成的列表以及如何调用谓词.
Is it possible to define a list, that consists of predicates and how do I call the predicates.
另外,是否可以将一个谓词传递给另一个谓词(如传递原子)?
Also, is it possible to pass one predicate to another predicate (like passing atoms)?
例子:
pre1:- something.
pre2(Predicate1, List):-
call(Predicate1),
append([Predicate1], List, R),
.....
推荐答案
你不能在列表中存储 谓词,但你可以存储 terms(或函子)并将术语称为目标.
You can't store predicates in a list, but you can store terms (or functors) and call terms as goals.
这是一个谓词,用于测试一个术语是否具有由函子列表描述的属性:
Here's a predicate that tests whether a term has the properties described by a list of functors:
has_properties([], _).
has_properties([P|Ps], X) :-
Goal =.. [P, X], % construct goal P(X)
call(Goal),
has_properties(Ps, X).
用法:
% is 4 a number, an integer and a foo?
?- has_properties([number, integer, foo], 4).
当然,此查询的答案取决于您对 foo/1
的定义.如果需要,请参阅我的 =..
说明.
The answer to this query will depend on your definition of foo/1
, of course. See my explanation of =..
if needed.
编辑:正如@false 在评论中报告的那样,没有必要使用=..
,因为Goal =.. [P, X],call(Goal)
可以替换成 call(P, X)
会产生同样的效果.不过,可能仍然值得学习 =..
,因为您可能会在其他人的代码中遇到它.
Edit: as @false reports in the comments, it's not necessary to use =..
, since Goal =.. [P, X], call(Goal)
can be replaced by call(P, X)
will have the same effect. It might still be worthwhile learning about =..
, though, as you may encounter it in other people's code.
这篇关于Prolog 中的谓词列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!