Reputation: 148
I am a newbie in Prolog. I have this facts:
user(alice).
user(bob).
money(alice,10).
money(bob,20).
The facts means that alice have 10 dollars and bob 20 dollars. In order to learn Prolog, i want to develop a function to transfer money between two users. My function should take in input the name of the receiver and the amount and add the quantity to the receiver.
example: add(alice,20)
and the output should be 30. Actually my function is:
add(X,Y,Z) :- Z is money(X,M) + Y.
but it doesn't work.
How i can implement it? Thanks
Upvotes: 1
Views: 77
Reputation: 18663
First, as you want to modify the facts for the predicate money/2
as the users exchange money, you need to declare the predicate dynamic:
:- dynamic(money/2).
Second, as Prolog is a relational language, not a functional language, you cannot write expressions as Z is money(X,M)
. Instead you need to write something like:
add(User, Money) :-
% remove old clause and access how much money the user holds
retract(money(User, Current)),
% compute the updated amount of money the user will be holding
Updated is Current + Money,
% add updated fact
assertz(money(User, Updated).
Upvotes: 1