Language: Swi Prolog. It is necessary to make the amount so that 1 is added.

Sketched a little

add(A, B, F) :- F = F+1, not(A+B = F) -> add(A, B, F). 

But it does not work

? - X = 0, add (20, 5, X).

false

What am I doing wrong?

  • and what should the line do: not(A+B = F) -> add(A, B, F) ? - Grundy
  • Well, if the sum of the left and right numbers are not equal to the output value, then we run the same function, where we add it - Di3go

2 answers 2

What am I doing wrong?

 add(A, B, F) :- F = F+1, not(A+B = F) -> add(A, B, F). 
  1. You confuse unification with assignment in imperative languages;
  2. In Prolog, nested expressions (functions) are not calculated in the general case;
  3. Functions are computed by predicates that can do this;
  4. -> / 2 "if that" is a predicate.
 add( A, B, C ) :- add0( A0, B0, C0 ), A is A0, B is B0, C is C0. add0( A, 0, A). add0( 0, A, A). add0( A+1, B, C+1 ) :- add0( A, B, C). add0( A, B+1, C+1 ) :- add0( A, B, C). 
  • one
    Something I did not understand the last line. there is no recursion in it, C is A + B immediately calculated? And A1 is calculated, but it is not used anywhere anymore - Grundy
  • one
    all the same is wrong: if A and B are not 0, then there will be infinite recursion, because A increases, and B does not change - Grundy

In the prologue to the query ?- X = 1 + 2. system will answer X = 1 + 2 . To call arithmetic operations, use the is operation:

 ?- X is 1 + 2. X = 3 

Operation = is a matching operation, it does not cause the calculation of arithmetic expressions, but it can reconcile variables. To compare the equality of arithmetic expressions, use the operation =:=

Well, the recursive sum can be written as the following set of sentences:

 sum(Augend, 0, Augend) :- !. sum(Augend, Addend, Result):- Addend >= 0, !, NewAddend is Addend - 1, sum(Augend, NewAddend, NewResult), Result is NewResult + 1. sum(Augend, Addend, Result):- Addend < 0, NewAddend is Addend + 1, sum(Augend, NewAddend, NewResult), Result is NewResult - 1. 

Here the first sentence is responsible for the end of the recursion, the second and the third for the sum calculation itself, depending on the sign of the second term. True for the predicate to work correctly, the variables Augend and Addend must be specified.