user3422517
user3422517

Reputation: 93

can anyone tell me what is wrong with my prolog code?

Basically, I want to convert two lists each into a number then add the resulting numbers and output a list representing the digits. Like add([2,2,2,2],[3,3,3],X) would be X =[2,5,5,5]. Internally, [2,2,2,2] and [3,3,3] are converted to 2222 and 333, added to get 2555. Here is my code and its not working.

addlistnum([],[],X).
addlistnum([B|C],[D|E],X) :-
   X is Y + F,
   digits([B|C],Y),
   digits([D|E],F).

digits(Num1,List) :-
   digits(0, List,Num1).

digits(Num1, [], Num1).
digits(N, [B|As],Num1) :-
   N1 is N * 10 + B,
   digits(N1, As,Num1).

I'm getting the following error: ERROR: is/2: Arguments are not sufficiently instantiated when I called the addlistnum() passing two lists and a variable. How may fix my code to achieve the desired result?

Upvotes: 0

Views: 62

Answers (1)

pasaba por aqui
pasaba por aqui

Reputation: 3539

I didn't recommend this approach, because you loss the possibility of handle any length numbers. You can try instead:

add(A,B,R) :-
  reverse(A,AR),
  reverse(B,BR),
  addl( AR, BR, 0, RR ),
  reverse( R, RR ).

addl( [], [], 0, [] ).
addl( [], [], 1, [1] ).

addl( [H|Q], [], C, R ) :- addl( [H|Q], [0], C, R ).
addl( [], [H|Q], C, R ) :- addl( [H|Q], [0], C, R ).

addl( [AH|AQ], [BH|BQ], C, [RH|RQ] ) :-
  RH is (AH+BH+C) rem 10,
  C2 is (AH+BH+C) div 10,
  addl( AQ, BQ, C2, RQ ).

Upvotes: 1

Related Questions