Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
685 views
in Technique[技术] by (71.8m points)

prolog - Cut at the beginning of a clause

Consider the Prolog predicated p(integer),q(integer),r(integer) with the flow model (o) and the predicate s:

p(1). q(1). r(1).
p(2). q(2). r(2).
s:-!,p(X),q(Y),r(Z),write(X,Y,Z),nl.

Give the result of the following goal: s. Justify the answer.

The result is 111,112,121,122,211,212,221,222. I have seen that the cut has no effect if it is at the beginning of a clause. Is this true?

question from:https://stackoverflow.com/questions/65642875/cut-at-the-beginning-of-a-clause

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

the cut has no effect if it is at the beginning of a clause."

Not exactly. That will depend on whether such predicate has other clauses or not.

Moreover:

  • the predicate write is unary and it cannot be called with three arguments.
  • it is better to group the clauses in the definition of the each predicate.

The correct program would be:

p(1). p(2).
q(1). q(2).
r(1). r(2).

s :- !, p(X), q(Y), r(Z), writeln(X-Y-Z).

Indeed, for this program, the cut has no effect. However, consider the following new version of the program.

p(1). p(2).
q(1). q(2).
r(1). r(2).

s :- !, p(X), q(Y), r(Z), writeln(X-Y-Z).
s :- writeln(here).                       % <= this clause will not be executed!

In this case, the cut in the first clause of predicate s will prevent the execution of the second one.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...