KP65
KP65

Reputation: 13585

Prolog rule help

I am new to Prolog and am experimenting around with some stuff, in particular i'm thinking about how to do a certain thing in prolog. I am aware of facts and rules, facts being something of the sort

specialCustomer(x).                     //person x is a specialcustomer

and rules:

totalSpend(x,500) :- specialCustomer(x).     //if x spends 500, he is a special customer

Would this fact and rule be valid in prolog? Is the rule wrong? How would i be able to query this through prolog? As in would a call of

totalSpend(bob,500).

be a valid call?

sorry if i am answering my own question, i just seem to be a bit...well confused!

Upvotes: 1

Views: 220

Answers (4)

Max Shawabkeh
Max Shawabkeh

Reputation: 38603

If you want to say that Bob, Jim and everyone who spends more than 500 are special customers, then define some people's spending, you would define it as follows:

specialCustomer(bob).
specialCustomer(jim).
specialCustomer(Who) :-
  totalSpend(Who, Amount),
  Amount >= 500.

totalSpend(mary, 400).
totalSpend(jack, 600).
totalSpend(pam, 500).

Then you would query it as follows:

?- specialCustomer(jim).
true.

?- specialCustomer(mary).
false.

?- specialCustomer(jack).
true.

?- specialCustomer(pam).
true.

?- specialCustomer(X).
X = bob ;
X = jim ;
X = jack ;
X = pam.

Upvotes: 2

starblue
starblue

Reputation: 56752

Maybe you want x to be a variable? For that it has to be an upper case X.

Upvotes: 1

Bullet Tooth Tony
Bullet Tooth Tony

Reputation: 43

What you probably want to express is

speccust(bob).
totalSpend(X,500) :- speccust(X).

such that bob is a special customer, and if somebody spent 500, then he is a special customer. In practice, you would save that to a file, say customer.pl, and for instance in swi-prolog load it by putting ['customer.pl']. Then, you can put queries to the database. In this case, you maybe want to know who is a special customer, then you would state:

totalSpend(Who, 500).

and receive Who = bob.

Upvotes: 0

sepp2k
sepp2k

Reputation: 370092

Everything you wrote is syntactically valid, but from your comments it doesn't seem like it does what you want it to.

specialCustomer(x).

Here you're saying specialCustomer(x) is true (and specialCustomer(anything_else) is false).

totalSpend(x,500) :- specialCustomer(x).

Here you're saying that totalSpend(x,500) is true iff specialCustomer(x) is true. Since you already defined special customer to be true, you could just as well have written

totalSpend(x,500).

Your comment makes it look as if you think that the part before the :- is the condition for the part after it, but it's the other way around.

totalSpend(bob,500).

Here you're asking whether totalSpend(bob, 500) is true, but since there is no rule for bob, it will be false.

Note that x and bob are symbols, not variables. So specialCustomer(x) will be true, but specialCustomer(bob) won't be.

Upvotes: 1

Related Questions