I was solving a problem: A list is representing an integer say 12345 by L=[12,34,5] each element should be from 0 to 99.The exercise is to write a function (sum) that sums two lists and gives the equivalent list of their sum which is representing the sum of two integers.

```
?-sum([11,11],[11,11],L,0).
L=[22,22].
?-sum([12,81],[11,44],L,0).
L=[24,25].
//digit fxn for making sure that we insert an elemnt of two or single integer
//and saving the overflow digit in S1.
```

my code that gives me error:

```
digit(X,D,S1):- S is X/100,S1 is integer(S),0 is S1,D is X.
digit(X,D,S1):-D is mod(X/100).
sum([],[],[],0).
sum(H1|T1,H|T,H3|T3,S):-Z is H1+H+S ,digit(Z,H3,S1),sum(T1,T,T3,S1).
```

# Best How To :

Your list is for all intents and purposes a base-100 number. The easy way to solve it is to do the arithmetic in the same way in which you would evaluate it long hand: start with the least significant digit, working to the most significant digit, sum each pair of digits, with a carry to the left if the overflows.

We reverse the list so as to let us easily work from right to left. You'll note that the worker predicate `sum_list_mod_100/4`

builds is result in the correct order.

```
sum_list_mod_100( Xs , Ys , Zs ) :- % to compute the sum of a list representing a base-100 integer.
reverse( Xs , X1 ) , % - reverse the digits of the left hand side (so we're working from least- to most-significant digit)
reverse( Ys , Y1 ) , % - reverse the digits of the right hand side (so we're working from least- to most-significant digit)
sum_list_mod_100( X1 , Y1 , 0 , Zs ) . % - invoke the worker with the carry initialized as zero.
.
sum_list_mod_100( [] , [] , C , [] ) . % both lists are empty w/o carry: terminate.
C = 0 %
. %
sum_list_mod_100( [] , [] , C , [C] ) :- % both lists are empty with a carry: prepend the carry to the result.
C > 0 %
. %
sum_list_mod_100( [X|Xs] , [] , C , [Z|Zs] ) :- % right-hand side exhausted?
sum_digits(X,0,C,Z,C1) , % - sum the digits, returning the new digit and the new carry
sum_list_mod_100( Xs , [] , C1 , Zs ) % - recurse down, passing the new carry
. %
sum_list_mod_100( [] , [Y|Ys] , C , [Z|Zs] ) :- % left-hand side exhausted?
sum_digits(0,Y,C,Z,C1) , % - sum the digits, returning the new digit and the new carry
sum_list_mod_100( [] , Ys , C1 , Zs ) % - recurse down, passing the new carry
. %
sum_list_mod_100( [X|Xs] , [Y|Ys] , C , [Z|Zs] ) :- % not yet exhausted?
sum_digits(X,Y,C,Z,C1) , % - sum the digits, returning the new digit and the new carry
sum_list_mod_100( Xs , Ys , C1 , Zs ) % - recurse down passing the new carry
. % Easy!
sum_digit(X,Y,C,Z,C1) :- % to sum two digits (and the carry)
S is X+Y+C , % - sum the LHS, RHS and the carry
Z is X mod 100 , % - compute the digit modulo 100
C1 is X div 100 % - compute the carry
.
```