如何在Prolog中编写/编辑自己的协程?
我想在Prolog中建立自己的协程. 我想添加一些额外的功能.
I would like to build my own coroutines in Prolog. I'd like to add some extra functionalities.
一种可能的解决方案是使用某些Prolog系统和Logtalk提供的术语扩展机制来重写对例如freeze/2
谓词可以执行所需的额外步骤.但是,必须小心,不要将对谓词的调用扩展到另一个目标,该目标与递归应用目标扩展的谓词调用相同,直到达到固定点为止.通过使用编译器旁路控制结构{}/1
,术语扩展机制的Logtalk实现可轻松避免此陷阱(具有可移植性的附加优点,因为您可以在大多数Prolog系统中使用Logtalk).一个愚蠢的例子是:
One possible solution would be to use the term-expansion mechanism provided by some Prolog systems and Logtalk to rewrite calls to e.g. the freeze/2
predicate to do the extra steps you want. One must be careful, however, to not expand a call to a predicate into another goal that calls the same predicate as goal-expansion is recursively applied until a fixed-point is reached. The Logtalk implementation of the term-expansion mechanism makes it easy to avoid this trap (with the additional advantage of portability as you can use Logtalk with most Prolog systems) by using a compiler bypass control construct, {}/1
. A silly example would be:
:- object(my_expansions,
implements(expanding)).
goal_expansion(
freeze(Var,Goal),
( write('If you instantiate me, I will run away!\n'),
{freeze(Var,Goal)}, % goal will not be further expanded
write('Bye!\n')
)
).
:- end_object.
然后可以将此对象用作挂钩对象,用于编译包含要扩展的对freeze/2
的调用的源文件.像这样(假设上面的对象保存在名称为my_expansions.lgt
的文件中,并且要扩展的源文件名为source.lgt
):
This object can then be used as an hook object for the compilation of source files containing calls to freeze/2
that you want to expand. Something like (assuming that the object above is saved in a file with the name my_expansions.lgt
and that the source file that you want to expand is named source.lgt
):
?- logtalk_load(my_expansions), logtalk_load(source, [hook(my_expansions)]).
有关完整的详细信息,请参阅Logtalk文档和示例.
For full details see the Logtalk documentation and examples.
可能有一种干净的方式,我不知道使用Prolog系统自己的术语扩展机制实现方式是否会执行相同的操作.有人吗?
There might be a clean way that I'm not aware of doing the same using the a Prolog system own term-expansion mechanism implementation. Anyone?