我正在尝试编写一个在运行时在 SWI-Prolog 中生成新约束的程序.is_true([A,means,B]) 旨在在运行时生成另一个约束:
I'm trying to write a program that generates new constraints at runtime in SWI-Prolog. is_true([A,means,B]) is intended to generate another constraint at runtime:
:- use_module(library(chr)). :- chr_constraint is_true/1. is_true([A,means,B]) ==> (is_true(A) ==> is_true(B),writeln('asserted')). is_true([[A,is,true],means,[A,is,not,false]]). is_true([something,is,true]).但是当我输入这些查询时,is_true 约束似乎不起作用.is_true([something, is, not, false]) 不返回 true:
But when I type these queries, the is_true constraint seems to have no effect. is_true([something, is, not, false]) does not return true:
?- is_true([something,is,true]). true . ?- is_true([something,is,not,false]). is_true([something, is, not, false]).在控制台中声明约束似乎也不起作用:
Asserting a constraint in the console seems to have no effect, either:
?- asserta(is_true(A>B)==>(is_true(B<A),writeln("asserted"))). true. ?- is_true(4>3). is_true(4>3).还有其他方法可以在运行时定义新的 CHR 约束吗?
Is there another way to define new CHR constraints at runtime?
推荐答案可以通过定义一个 is_true/2 谓词来解决这个问题.可以在运行时使用 assertz/1 谓词更改此谓词.这不是一个理想的解决方案,但它适用于这种特殊情况.
It is possible to work around this problem by defining an is_true/2 predicate. This predicate can be changed at runtime using the assertz/1 predicate. This isn't an ideal solution, but it works in this particular case.
现在我可以这样编写程序了:
Now I can write the program like this:
:- use_module(library(chr)). :- chr_constraint is_true/1. is_true(A) ==> is_true(A,B) | is_true(B). is_true([A,means,B]) ==> assertz(is_true(A,B)). is_true([],[]).并以这种方式在运行时添加新约束:
and add new constraints at runtime in this way:
̀?- is_true([[A,implies,B],means,[A,means,B]]). is_true([[A, implies, B], means, [A, means, B]]). ?- is_true([A>B,implies,B<A]). is_true([A>B, means, B<A]), is_true([A>B, implies, B<A]). ?- is_true(A>B). is_true(B<A), is_true(A>B).相反,为 CHR 编写元解释器"可能更有用:
Instead, it might be more useful to write a "meta-interpreter" for CHR:
:- initialization(main). :- set_prolog_flag('double_quotes','chars'). :- use_module(library(chr)). :- chr_constraint is_true/1. is_true(X) \ is_true(X) <=> true. is_true(X ==> Y),is_true(X1) ==> copy_term((X -> Y),(X2 -> Y1)),(X2=X1,(is_true(X1)->is_true(Y1));X2\=X1),writeln(Y). is_true((X;Y)) ==> is_true(X);is_true(Y). is_true((X,Y)) ==> is_true(X),is_true(Y). is_true(is_true(X)) ==> is_true(X). is_true(X),is_true(\+X) ==> false. main :- is_true(is_person(A)==>is_mammal(A)), is_true(is_mammal(A)==>is_animal(A)), is_true(is_person(sue)),is_true(is_person(bob)).更多推荐
在运行时定义 CHR 约束
发布评论