Reputation: 1214
For an assignment I have to generate a prolog procedure body dynamically. How can I do this?
Upvotes: 1
Views: 1070
Reputation: 1
You can generate dynamic predicate with '(
' and ')
' enclosing body.
assert(test(X):- (X1 is X+1, write(X1)))
Upvotes: 0
Reputation: 2779
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.
Upvotes: 2
Reputation: 5858
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)
Upvotes: 0