Which of the following Prolog programs correctly implements: ‘If G succeeds,…
2012
Which of the following Prolog programs correctly implements: ‘If G succeeds, execute goal P; otherwise, execute goal Else’ ?
Answer: B. if_else(G, P, Else) :- call(G), !, call(P). if_else(G, P, Else) :- call(Else). — ConceptIn Prolog, goals are attempted from left to right, and backtracking tries later clauses. The cut operator (!) commits to choices made since entering…
- A.
if_else(G, P, Else) :- !, call(G), call(P). if_else(G, P, Else) :- call(Else). - B.
if_else(G, P, Else) :- call(G), !, call(P). if_else(G, P, Else) :- call(Else). - C.
if_else(G, P, Else) :- call(G), call(P), !. if_else(G, P, Else) :- call(Else). - D.
All three program fragments
Attempted by 39 students.
Show answer & explanation
Correct answer: B
Concept
In Prolog, goals are attempted from left to right, and backtracking tries later clauses. The cut operator (!) commits to choices made since entering the current predicate, so its position determines whether the fallback clause remains reachable.
Application
With ! before call(G), the predicate commits immediately. If G fails, Prolog cannot try the fallback clause, so this sequence does not implement the intended else behavior.
With call(G) before !, a failure of G occurs before commitment and therefore reaches the fallback clause. After the first success of G, ! commits to the first clause and call(P) is executed; a later failure of P does not invoke Else.
With ! after call(P), P is attempted before commitment. If G succeeds but P fails, Prolog may backtrack into the fallback clause and execute Else, which is not standard if-then-else behavior.
Cross-check
Trace the two decisive cases: when G fails, the fallback must run; when G succeeds, commitment must occur before P so that failure of P does not switch to Else. Only the ordering call(G), !, call(P) satisfies both conditions.
Result
Therefore the implementation with call(G), then !, then call(P), followed by a separate fallback clause calling Else, is the required program.