Can someone explain how the logic of the composition of substitutions works with the following block of code?
plus2(0, X, X). % 0+X = X
plus2(s(X), Y, s(Z)) :-
plus2(Y, X, Z). % (X+1) + Y = Z+1 therefore Y+X=Z
Can someone explain how the logic of the composition of substitutions works with the following block of code?
plus2(0, X, X). % 0+X = X
plus2(s(X), Y, s(Z)) :-
plus2(Y, X, Z). % (X+1) + Y = Z+1 therefore Y+X=Z
Composition of substitutions means that if under substitution θ1
we have
A = s(B)
and under substitution θ2
we have
B = s(C)
then under the composed substitution
θ1 U θ2
we have
A = s( s(C))
This can be seen e.g. in the call
%% the code, for reference:
plus2(0, X, X).
plus2(s(X), Y, s(Z)) :- plus2(Y, X, Z).
%% the call:
plus2( s(1), 0, SUM )
=plus2( s(X), Y, s(Z)) under θ1 = {1=X, 0=Y, SUM=s(Z)}
:- plus2( Y, X, Z) under θ1
=plus2( 0, 1, Z)
:-plus2(0,X2,X2) under θ2 = {1=X2, Z=X2}
Thus the composed substitution is
θ = θ1 U θ2 = {1=X, 0=Y, SUM=s(Z), 1=X2, Z=X2}
and the original query holds under θ
as
plus2( s(1), 0, SUM ) % under θ1, SUM=s(Z )
=plus2( s(1), 0, s(Z) ) % under θ2, Z=X2
=plus2( s(1), 0, s(X2)) % under θ2, X2=1
=plus2( s(1), 0, s(1) ). % under θ, SUM=s( 1)
Thus, as the proof progresses, the answer term SUM
is progressively instantiated in the top-down manner.
Here is better naming:
This is using Peano arithmetic, which represents natural numbers (i.e. integers starting from zero) in a relative way, as compound terms, as successors ultimately of 0. For example,
s(s(0))
represents 2. Such relativity is convenient and elegant for Prolog, because it can be used ("reasoned with") in an uninstantiated (var) variable.In swi-prolog, this produces:
... and if we ask it how we can add two natural numbers to sum to 2:
Whereas if we don't swap the arguments:
... we get:
... which is still correct, but doesn't "involve"
M
as much as it could.Both methods are counting from 0 upwards to infinity.
Swapping the parameters brings the advantage of checking the 2nd argument, to fail both fast and when appropriate:
Sadly, there is a common practice in Prolog example code of using meaningless variable names (such as A, B, X, Y), which adds confusion and should be generally avoided.
Addendum: Here is a version which has better determinism, when 2 of the 3 arguments are ground: