开发者

About rules in prolog . .

开发者 https://www.devze.com 2023-02-16 17:36 出处:网络
In my program I have some rules like: tellme(X) :- knows(X). tellme(friends1(X)) :-tellme(X). tellme(friends2(X)) :-tellme(X).

In my program I have some rules like:

tellme(X) :- knows(X).
tellme(friends1(X)) :-  tellme(X).
tellme(friends2(X)) :-  tellme(X).
tellme(friends3(开发者_StackOverflow中文版X)) :-  tellme(X).
.
.
.
tellme(friends25(X)) :- tellme(X).

Now this friends1, friends2, friends3 ..... are dependent on N which is a variable. Here, for example value of my N is 25. So is this possible to write a rule to generate these rules till N or do I have to manually write these rules for N times. Any suggestions or solutions are welcomed. Thank you very much for your attention.


You can generate any sort and amount of code in most modern Prolog environment using term expansion, with some help from the universal operator. The following example works for SWI:

term_expansion(gen_tellme(N), Terms) :-
    findall((tellme(F) :- tellme(X)),
            (between(1, N, I), atom_concat(friend, I, Fi), F =.. [Fi, X]),
            Terms).

gen_tellme(25). % generates 25 copies of the tellme clause.

That said, embedding information into the predicate name, i.e., the friend number, is generally not a good design. Why not rewrite the code using friend(N, X), where N is the number?


You may have some success with a binary functor friends(N,X) instead of one functor per N. You may want to change tellme and knows to take two arguments as well. (knows(X) has no immediate meaning to me, so I don't entirely get what you're after.)

If, for some reason, that's not what you want, you can make a new functor with something like (untested)

friends_functor(N, Functor) :-
    number(N),
    atom_concat(friend, N, Functor).

Then use asserta or assertz. I really don't see why you'd want to do this, though.

0

精彩评论

暂无评论...
验证码 换一张
取 消