1
votes

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.

2
I can not reproduce this error. If I run this in swipl, it works. - Willem Van Onsem
@WillemVanOnsem really? I don't know what version I am using, but it marks an error. Also, the definition that I have in my notes says it's only 1 parameter - Lw. K
Are you sure you made no mistake with the parenthesis in the querying? I copied your queries and it worked (well I did not verify that the facts are in the "interpreter database", but there were no errors). - Willem Van Onsem
@WillemVanOnsem What querying? I doesn't even let me querying because it doesn't even compile. The 3 asserts are going to be in the text editor, no? - Lw. K
Ah, I did them interactively in Prolog's swipl. But in a file it makes no sense to do asserta's, etc. as "naked expressions". Since asserta(exp) is equal to exp in the head of the file. You can only do these in the body of predicates. - Willem Van Onsem

2 Answers

1
votes

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.

0
votes

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.