Can we say:
Sum is 0.
Sum is Sum + 2.
in Prolog, if we want a value to be retained or want to keep making changes to that variable?
Can we say:
Sum is 0.
Sum is Sum + 2.
in Prolog, if we want a value to be retained or want to keep making changes to that variable?
if we want a value to be retained or want to keep making changes to that variable?
We receive an existing thing via variable name (which is a reference to a globally accessible structure), build a new thing from it, and fill the reference to this new thing into another variable name:
DataOut is 2*DataIn. % assuming DataIn is numeric, multiply by 2
bar(DataIn,DataOut) :-
DataIn = f(X), % Disassemble, pick out X, assuming DataIn is a term "f(X)"
DataOut = g(X). % Assemble, wrapping X into g
baz(f(X),g(X)). % the same as bar/2 above, written compactly
The "things" are never stored, they are just passed around between predicates.
In particular, for a loop, you don't store anything.
Here is one which sums the values between From
and To
:
% loop(From:integer,To:integer,Sum:integer).
loop(From,From,From).
loop(From,To,Sum) :-
To > From,
ToMinus is To-1,
loop(From,ToMinus,LowerSum),
Sum is LowerSum+To.
We have a little advantage relative to functional languages in that the thing can actually grow at "as yet unset places". So you can also pass a "thing" and have it grow:
quux(Data) :-
Data = f(X,Y), % Disassemble, assuming Data is a term "f(X,Y)"
(var(Y) % If Y is still an unbound variable
-> Y = g(Z) % then set it to a fresh unbound variable wrapped in g
; true). % Otherwise do nothing
And so:
?- Data=f(X,Y),quux(Data).
Data = f(X,g(_16532)),
Y = g(_16532).
?- Data=f(1,2),quux(Data).
Data = f(1,2).
However, once you have gotten used to this idea, you may indeed store the things for "later usage" by various means:
Read these:
Yes we can say that, but the result will be
fail.
failure, because 0 is 0+2
is the same as 0 is 2
which fails to hold.
If we want to somehow record a progression of knowledge refinement in our program, we can use numbered variables, as one option:
Sum1 is 0, Sum2 is Sum1 + 2.
Both values will thus be available to us -- the previous and the current one.
Another option is maintaining lists of recorded changes where each element in the list is the next version of the previous one.
In this regard Prolog is very much like functional programming(*) in e.g. Haskell etc., forcing us to essentially program in SSA style explicitly, or state-passing.
(*) search for '"How to "think functional"' there.