Dynamic Prolog clause-body generation
开发者_开发技巧For an assignment I have to generate a prolog procedure body dynamically. How can I do this?
See here for the swi prolog manual description of relevant predicates.
As an example consider the following
goal :- Z =.. [foo, 1],
Y =.. [bar,2],
X =.. [',', Z, Y],
R =.. [':-', r, X],
assert(Z), assert(Y), assert(X), assert(R).
PS: Another possibility is lower class, but sometimes can be a better choice: just print out what you need to construct to a file.
to add a predicate you need to use asserta/1 or assertz/1 (assert/1 is deprecated) more if you have already declared some of the clauses of the predicate in the code you loaded you should define the predicate as dynamic using dynamic/1 more
forming the clause depends on the form of the input. if you have a list with the name of the predicate and the arguments you can use =../2 if you have the clause on a string you can use term_to_atom/2 (it works both ways)
assert/1, asserta/1, retract/1, retractAll/1, abolish/1
You can generate dynamic predicate with '(
' and ')
' enclosing body.
assert(test(X):- (X1 is X+1, write(X1)))
精彩评论