Lw. K
Lw. K

Reputation: 25

Introducing predicates in Prolog

We start with an empty database and the following commands are given

assert(q(a,b)),assertz(q(1,2)),asserta(q(foo,blug)).

What does now the database contain?

What happens after the following commands?

retract(q(1,2)),assertz((p(X):-h(X))).

Finally, what happens after the following command?

retract(q(_,_)),fail.

MyAttempt

I introduced the following commands in Prolog

assert(q(a,b)).

assertz(q(1,2)).

asserta(q(foo,blug)).

but it marked an error saying that q should be of 1 parameter and not 2.

Could someone please help me? How can I fix this? Any kind of help would be greatly appreciated

Thank you in advance.

Upvotes: 1

Views: 80

Answers (2)

Will Ness
Will Ness

Reputation: 71119

The fail in retract(q(_,_)),fail. makes it loop until no more q/2s are left in the database.

How it works is, Prolog wants to prove a goal it is given; so when our goal ends with an explicit fail, that fail always fails so the overall goal fails too; but Prolog wants to prove it and so continues to try to prove it, so it "retries" any outstanding goals' choice-points still in place "above" that fail.

Simply put, it retries the retract(q(_,_)) goal.

Each retract(q(_,_)) goal retracts one instance of q/2 from our data knowledge base. So with this failure-driven loop, they all are removed and the final result is still a failure.

In a pure setting only this result counts -- a goal's failure or success. But assert and retract-kind of predicates are called for their side-effects, not for their success or failure. Their side effect is, that they affect the state of our data base.

In fact, normally a failure-driven loop would look like

retract(q(_,_)),fail ; true.

to achieve the same effect, but succeed (instead of failing), to signal, well, success in achieving its intended effect.

Upvotes: 1

Lw. K
Lw. K

Reputation: 25

By reading theory we could conclude the following.

To the first question,

q(foo,blug).

q(a,b).

q(1,2).

To the second question,

q(foo,blug).

q(a,b).

p(A):-h(A).

To the third question, I think removes all the predicates q. I don't know what is the action of ',fail' here.

Upvotes: 0

Related Questions