0
votes

I'm new to prolog and I'm doing some exercises for practice. I am adding two list in successor notation. The question and answer should be displayed in successor notation, but for convenience, I write it in numerical.

  1. List([1,1,1,1],[2,2,2,2],[3,3,3,3])
  2. List([9,9,9,9],[1,1,1,1],[1,1,1,1,0])

I get the answer of the question two [10,10,10,10] in successor notation easily, but the answer needs us to handle the digits, which means the expect ans is [s(0),s(0),s(0),s(0),0].

1
Show your partial solution. - rajashekar
List([],[],[]). List([H1|L1],[H2|L2],[H3|L3]) :- lsum(L1,L2,L3), sum(H1,H2,0,H3). - jay
sum(a,b,c,d) is a equation a+b = c+d. The question ask us refer to the previous question. - jay
Shouldn't the sum of [9, 9, 9, 9] and [1, 1, 1, 1] be [1, 1, 1, 1, 0] ? - rajashekar
yes, sorry. Let me edit the question. Really sorry of my mistake - jay

1 Answers

0
votes

I am using the simple carry over method of addition.

add(0, X, X).
add(s(X), Y, s(Z)) :-
    add(X, Y, Z).

% Helper to convert b/w decimal and succ notation.
sform(0, 0).
sform(N, s(S)) :-
    N > 0, N1 is N - 1,
    sform(N1, S).

sumdigits([], [], [], 0).
sumdigits([X|Xs], [Y|Ys], [Z|Zs], C) :-
    sumdigits(Xs, Ys, Zs, C1),
    (C1 = 0 -> add(X, Y, Z1); add(X, s(Y), Z1)),
    (  Z1 = s(s(s(s(s(s(s(s(s(s(Z))))))))))
    -> C = s(0)
    ;  Z1 = Z, C = 0
    ).

sumdigits(Xs, Ys, Zs) :-
    sumdigits(Xs, Ys, Zs1, C),
    (C = 0 -> Zs = Zs1; Zs = [C|Zs1]).
?- maplist(sform, [9, 9, 9, 9], X), maplist(sform, [1, 1, 1, 1], Y), sumdigits(X, Y, Z).
X = [s(s(s(s(s(s(s(s(s(0))))))))), s(s(s(s(s(s(s(s(s(0))))))))), s(s(s(s(s(s(s(s(s(0))))))))), s(s(s(s(s(s(s(s(s(0)))))))))],
Y = [s(0), s(0), s(0), s(0)],
Z = [s(0), s(0), s(0), s(0), 0]