Prolog - Update a value in list of list - prolog

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.

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.

Related

System State in Prolog

I have a small program that runs in python. Basically, it has a pretty simple loop: Query a Prolog program, do something with the result, change some state back in Prolog.
I have written a logical way (no mutations) to change a state in Prolog.
The queries use a state as their argument, and result in a new state. The question is, where do I store the new state?
I can pass it back and forth from Prolog to Python, but as the state grows large it might become problematic.
I can also store a global variable, but that seems like a bad solution.
This is the basic flow of my program:
some_query(OldState, NewState) :-
% do some stuff here
python code:
state = '[]'
while Not_Exit:
query = MyLogic(state) # state is not actually used here (python-wise), just to pass it to prolog
result = prologBridge.Query(query)
state = result["NewState"] # how do I change that in Prolog without passing the state back and forth?
EDIT:
The state contains a list of terms, and state changes revolve around adding and removing terms. For example. S1 = [T1, T2, T3] changes into S2 = [T2, T3, T4].
Possible solutions:
Store state or other facts in a file that you reconsult in Prolog.
Use data bases to persist state
Keep Prolog running as a separate process in the background, then current state should be available.
What is your choice ? what about functional programming ?
As long as each query runs in the same Prolog session (i.e., you don't start a new Prolog each time), you can use Prolog's built-in database. This is a store of "dynamic" Prolog clauses that can be modified at runtime.
You declare a dynamic predicate using a :- dynamic directive. You remove old facts using rectract or retractall and assert new ones using asserta or assertz. Querying a dynamic predicate is done by calling it as usual.
For example, you can declare your state like this:
:- dynamic mystate/1.
A predicate querying the state, computing the next one, and updating the database, looks like this:
query_and_update_state :-
mystate(OldState),
some_query(OldState, NewState),
write('new state: '),
write(NewState),
nl,
retractall(mystate(_)),
asserta(mystate(NewState)).
This assumes the existence of your some_query predicate. Some initial state must be set at the beginning as well. For example, if the state is just a counter:
init_state :-
retractall(mystate(_)),
asserta(mystate(0)).
some_query(Old, New) :-
succ(Old, New).
Running this interactively:
?- init_state.
true.
?- query_and_update_state.
new state: 1
true.
?- query_and_update_state.
new state: 2
true.
?- query_and_update_state.
new state: 3
true.
?- query_and_update_state.
new state: 4
true.
Your Python code would call init_state once and then call query_and_update_state repeatedly, presumably for some side effect. (It's not clear to me from your question.)
Caveat: If you're worried about the costs of copying the state, you might not be happy about this either. Asserting a state and querying it both involve making a complete deep copy of the data structure. Such a Prolog-Prolog copy might indeed be cheaper than a Prolog-Python copy. But depending on your Python-Prolog bridge, maybe it doesn't make a deep copy and could be cheaper? I don't know.

Prolog: Storing result of an operation

just started programming with prolog and I'm having a few issues. I wanna store the result on an operation , for example:
transformer(kilo,1000).
transformer(hecto,100).
transformer(deca,10).
transformer(unite,1).
transformer(deci,0.1).
transformer(centi,0.01).
transformer(milli,0.001).
transformerT(sec,1).
transformerT(min,60).
transformerT(h,3600).
plus(V1,U,V2,U,UniteType,R,U) :-
dif(UniteType,temps),R is V1+V2.
plus(V1,U1,V2,U2,UniteType,R,unite) :-
dif(UniteType,temps),
dif(U1,U2),
trans(U1,Res1),
trans(U2,Res2),
R is V1*Res1+V2*Res2.
I want to store the result of this operation to call it later (like the ANS or M Buttons in a calculator) in another operation. Is it Possible?
If you want the information to survive a program termination (i.e. a return to the Prolog REPL, aka. toplevel) you can use predicates asserta/2 and assertz/2.
See this section for SWI Prolog, should be similar for SICStus: Database
Alternatively you may want to keep the program "alive" and store information in a term that is passed between predicates. Association lists library(assoc) or, for SWI Prolog, built-in dicts, or simpler data structure like lists can be used for that.

Summing an already outputted list

This is the knowledge base I am working with:
localLib('AHorowitz','Stormbreaker',2).
localLib('AHorowitz','Scorpia',4).
localLib('AHorowitz','Ark Angel',6).
The key for the knowledge base is as follows:
localLib(W,B,C) where
W=Writer
B=Book
C=Acknowledgements
I would like to write a rule that adds up all the acknowledgements of the writer.
This is the code I have written so far:
getAcknowledgement(W,X):- findall(C,localLib(W,_,C),X).
This rule helps me list all the acknowledgements in separate list e.g.
?- getAcknowledgement('AHorowitz',X).
X = [2, 4, 6]
I am now getting stuck on how to add these items. I know of the sum_list built in and though I know it is not correct the thing I want to achieve is this:
getAcknowledgement(W,X):- findall(C,localLib(W,_,C),X).
sum_list(X,[getAcknowledgement]).
/* I would like to sum the output that I receive from the first rule above.
The KB has been simplified in this example to 3 clauses however in reality
there are 1000.*/
How would I go about doing this, any help would be great?
It sounds like you want to find the count of acknowledgements by writer.
bagof/3 is your friend here. It
bagof(+Template, :Goal, -Bag)
Unify Bag with the alternatives of Template. If Goal has free variables besides the one
sharing with Template, bagof/3 will backtrack over the alternatives of these free
variables, unifying Bag with the corresponding alternatives of Template. The construct
+Var^Goal tells bagof/3 not to bind Var in Goal. bagof/3 fails if Goal has no
solutions.
findall/3 is
equivalent to bagof/3 with all free variables bound with the existential operator (^),
except that bagof/3 fails when Goal has no solutions.
So...this should get you the summed count of knowledgements for a given writer, or, if Writer is unbound, on backtracking, it will find the solutions for all writers, one at a time.
acknowledgements_by_writer( Writer , Acknowledgements ) :-
bagof( N , local_lib(Writer,_,N) , Ns ) ,
sum_list(Ns,Acknowledgments).
If you want the overall count of acknowledgements, something like this ought to do you
total_acknowledgements(T) :-
findall(N,local_lib(,,N),Ns),
sum_list(Ns,T).

Status variable in Prolog

I need to code a process in which the program should run some rules base on a "Status variable", then I need to be able to change this Status variable in order to continue with the process. But I do not know if there is something like a "Status variable", any idea of how can I achieve it?
Your "status variable" could be a fact, which gets asserted (or retracted) to reflect the desired signal, although I don't think you can make such changes concurrent with a proof executing.
I think it would be cleaner to assert whatever state you need when the original process "gets stuck", and instead issue a new query when the status changes which could then use that state.
A declarative alternative to using a dynamic variable, as Scott suggested in his answer, is to use a stream variable. The idea would be to create and initialize a new stream variable, pass it (as a logic variable) to your rules, and update it with a new value when require. The rules would access (or update) at any time the current value of the stream variable. An example, using Logtalk implementation of stream variables, should make it clear (you can use Logtalk as a library with most Prolog compilers, including SWI-Prolog):
?- {library(streamvars)}.
% [ /Users/pmoura/logtalk/library/streamvars.lgt loaded ]
% (0 warnings)
true.
?- streamvars::new(SV, 1).
SV = [_G9, v(1)|_G13].
Notice that the stream variable, SV is represented by a list with a unbound tail, which allows us to add new values to it. The streamvars object provides predicates for creating a new stream variable, accessing its current value, and updating its value. A simple usage would be:
?- streamvars::new(SV, 1), streamvars::'=>'(SV, V1), streamvars::'<='(SV, 2), streamvars::'=>'(SV, V2).
SV = [v(_G31), v(1), v(2)|_G34],
V1 = 1,
V2 = 2.
The =>/2 and <=/2 predicates have corresponding operator definitions for some syntactic sugar, although those are not used above. Your rules would use these access and update predicates as necessary, with the stream variable being passed (threaded) from rule to rule.
The full documentation of the streamvars can be consulted at:
http://logtalk.org/library/streamvars_0.html
The source code can in turn be consulted at:
https://github.com/LogtalkDotOrg/logtalk3/blob/master/library/streamvars.lgt
The code is simple and you can easily adapted it to your application. A possible downside of using this implementation of stream variables is that, as shown above, all past elements are kept. If that's a problem in your case, then you will need to resort to non-declarative solutions such as using a dynamic predicate or mutables (i.e. global variables), which are provided in some Prolog systems.

In Prolog (SWI), how to build a knowledge base of user supplied pairs and assert to be equal

I am very new to Prolog and trying to learn.
For my program, I would like to have the user provide pairs of strings which are "types of".
For example, user provides at command line the strings "john" and "man". These atoms would be made to be equal, i.e. john(man).
At next prompt, then user provides "man" and "tall", again program asserts these are valid, man(tall).
Then the user could query the program and ask "Is john tall?". Or in Prolog: john(tall) becomes true by transitive property.
I have been able to parse the strings from the user's input and assign them to variables Subject and Object.
I tried a clause (where Subject and Object are different strings):
attribute(Subject, Object) :-
assert(term_to_atom(_ , Subject),
term_to_atom(_ , Object)).
I want to assert the facts that Subject and Object are valid pair. If the user asserts it, then they belong to together. How do I force this equality of the pairs?
What's the best way to go about this?
Questions of this sort have been asked a lot recently (I guess your professors all share notes or something) so a browse through recent history might have been productive for you. This one comes to mind, for instance.
Your code is pretty wide of the mark. This is what you're trying to do:
attribute(Subject, Object) :-
Fact =.. [Object, Subject],
assertz(Fact).
Using it works like this:
?- attribute(man, tall).
true.
?- tall(X).
X = man.
So, here's what you should notice about this code:
We're using =../2, the "univ" operator, to build structures from lists. This is the only way to create a fact from some atoms.
I've swapped subject and object, because doing it the other way is almost certainly not what you want.
The predicate you want is assertz/1 or asserta/1, not assert/2. The a and z on the end just tells Prolog whether you want the fact at the beginning or end of the database.
Based on looking at your code, I think you have a lot of baggage you need to shed to become productive with Prolog.
Prolog predicates do not return values. So assert(term_to_atom(... wasn't even on the right track, because you seemed to think that term_to_atom would "return" a value and it would get substituted into the assert call like in a functional or imperative language. Prolog just plain works completely differently from that.
I'm not sure why you have an empty variable in your term_to_atom predicates. I think you did that to satisfy the predicate's arity, but this predicate is pretty useless unless you have one ground term and one variable.
There is an assert/2, but it doesn't do what you want. It should be clear why assert normally only takes one argument.
Prolog facts should look like property(subject...). It is not easy to construct facts and then query them, which is what you'd have to do using man(tall). What you want to say is that there is a property, being tall, and man satisfies it.
I would strongly recommend you back up and go through some basic Prolog tutorials at this point. If you try to press forward you're only going to get more lost.
Edit: In response to your comment, I'm not sure how general you want to go. In the basic case where you're dealing with a 4-item list with [is,a] in the middle, this is sufficient:
build_fact([Subject,is,a,Object], is_a(Subject, Object)).
If you want to isolate the first and last and create the fact, you have to use univ again:
build_fact([Subject|Rest], Fact) :-
append(PredicateAtoms, [Object], Rest),
atomic_list_concat(PredicateAtoms, '_', Predicate),
Fact =.. [Predicate, Subject, Object].
Not sure if you want to live with the articles ("a", "the") that will wind up on the end though:
?- build_fact([john,could,be,a,man], Fact).
Fact = could_be_a(john, man)
Don't do variable fact heads. Prolog works best when the set of term names is fixed. Instead, make a generic place for storing properties using predefined, static term name, e.g.:
is_a(john, man).
property(man, tall).
property(john, thin).
(think SQL tables in a normal form). Then you can use simple assertz/1 to update the database:
add_property(X, Y) :- assertz(property(X, Y)).

Resources