Prolog: making a 4-argument add function

76 Views Asked by At

I am trying to code a 4-argument function myadd(A, B, C, D) which holds true when A + B + C = D in prolog.

I am completely new to prolog and had no clue what to do, so what I did was some extention from a similar function but with 3 arguments:

add(0, Y, Y).
add(s(X), Y, s(Z)) :- add(X, Y, Z).
myadd(0, B, C, D) :- add(B, C, D).
myadd(s(A), B, C, s(D)) :- myadd(A, B, C, D).

Then when I execute this code, it starts to list what is untrue from some point:

?- myadd(A, B, C, s(s(0))).
A = B, B = 0,
C = s(s(0)) ;
A = 0,
B = C, C = s(0) ;
A = C, C = 0,
B = s(s(0)) ;
A = s(0),
B = 0,
C = s(s(0)) ; <- obviously this should not be true since s(0) + s(s(0)) != s(s(0))
A = B, B = C, C = s(0) ;
A = s(0),
B = s(s(0)),
C = 0 ;
A = C, C = s(s(0)),
B = 0 ;
A = s(s(0)),
B = C, C = s(0) ;
A = B, B = s(s(0)),
C = 0 ;
A = s(s(s(0))),
B = 0,
C = s(s(0)) ;
...

I have no idea why this (1. the code works until some point, 2. and then it doesn't) happens, I highly appreciate it if someone kindly points out the flaw.

Or, I'd be really grateful if you could tell me where to start.

1

There are 1 best solutions below

1
On

I cannot reproduce the answers you are getting.

Using SWI-Prolog 8.4.3:

?- myadd(A, B, C, s(s(0))).         % A + B + C = 2
   A = B, B = 0, C = s(s(0))        % 0 + 0 + 2 = 2
;  A = 0, B = C, C = s(0)           % 0 + 1 + 1 = 2
;  A = C, C = 0, B = s(s(0))        % 0 + 2 + 0 = 2
;  A = C, C = s(0), B = 0           % 1 + 0 + 1 = 2
;  A = B, B = s(0), C = 0           % 1 + 1 + 0 = 2
;  A = s(s(0)), B = C, C = 0        % 2 + 0 + 0 = 2
;  false.

This part of your program seems to work properly!