Atef Magdy
Atef Magdy

Reputation: 122

Prolog - Update a value in list of list

I have a fact :

available_resources([[r1, 0], [r2, 0]]).

I need when a specified condition is true increase the zero by 1 . like:

release(X):-
        allocated(X , R1):-
        increase r1 by one 

I don't know how to update a fact.

Upvotes: 1

Views: 193

Answers (1)

David Tonhofer
David Tonhofer

Reputation: 15316

You are asking about "changeable state". As in functional languages (i.e. LISP et al.), this is harder to come by in Prolog! (For a functional view in the context of Clojure, see Values and Change: Clojure’s approach to Identity and State)

What you can do is have a specific value for "time". Then you can have facts in the Prolog database like these:

available_resources(10, [this, and, that]).
available_resources(20, [hither, and, yon]).

Here we state that at time 10, the resources were [this, and, that], and at time 20, the resources were [hither, and, yon].

Then you can use assertz to add facts to the database and retract to remove old ones.

release(X) :- available_resources(Tprev, Rprev),
              compute_new_resource_term(X,Rprev,Rcur),
              % get current time from an extralogical oracle              
              get_time(Tcur), 
              retract(available_resources(Tprev, Rprev)),
              assertz(available_resources(Tcur,Rcur)).

But if you do not need to have the "resources" term survive across program runs (i.e. through a return to the toplevel), you wuld just construct new terms and hand them from predicate to predicate without storing them in the database.

Upvotes: 2

Related Questions