cryptarithmetic prolog test fails recursion idea

Tag: prolog , artificial-intelligence , swi-prolog , first-order-logic Author: dvzhou Date: 2014-04-23

I need to test this code for crypt arithmetic for two + two = four but it is giving me false which is wrong. I need to know why is this happening. It works for donald+robert= gerald or it+is=me. I got the idea of how recursion works but since i cannot debug it I have no idea what is wrong.

sum(N1,N2,N) :-
    sum1(N1,N2,N,0,0,[0,1,2,3,4,5,6,7,8,9], _).

sum1([], [], [], C,C,D,D).
sum1([D1|N1], [D2|N2], [D|N], CR, C, Digs1, Digs) :-
    sum1(N1,N2,N, CR, CLN, Digs1, Digs2),
    digsum(D1,D2, CLN, D, C, Digs2, Digs).

digsum(D1,D2, C1, D, C, Digs1, Digs) :-
    del_var(D1, Digs1, Digs2),   
    del_var(D2, Digs2, Digs3),   
    del_var(D,  Digs3, Digs),

    S is D1+D2+C1,
    D is S mod 10,               
    C is S // 10. 

del_var(A,L,L) :-
    nonvar(A), !.                
del_var(A, [A|L], L).
del_var(A, [B|L], [B|L1]) :-
   del_var(A,L,L1).
I'm not sure exactly what your issue is but you can use trace. to turn on tracing at the prompt, if you need to debug something.
Some debug thoughts: (1) use trace as @qu4ntumcpa suggests, (2) use debug(predicate_name) to debug/trace a specific predicate, (3) query a specific predicate from the Prolog prompt to test that predicate (e.g., enter del_var(...) to test that del_var does what you think it should) and/or, (4) use some write/1 statements for custom tracing. If you need more help, you might want to indicate exactly what query you enter for expressions like donald+robert=gerald.

Other Answer1

There is nothing wrong with your code except that it works only for lists of same lenghts. That's why it works for IT + IS = ME (lists of length 2) and for DONALD + ROBERT = GERALD (lists of length 6). Actually, it is quite easy to find a workaround: for example you can fill shorter lists with leading zeros. So instead of sum([T,W,O], [T,W,O], [F,O,U,R]) you have to do something like sum([0,T,W,O], [0,T,W,O], [F,O,U,R]) and it will work.

comments:

Instead can you tell me how do i compare the length of list and append zero in the code rather than giving input with zero
@user3342812, look here: