Prolog - Binary addition? -


i need write prolog predicate calculate sum of 2 binary numbers represented in list. lists reversed, example ([0,1] base 2) = (2 base 10).

it should work mode binary_plus(+,+,-), example

?- binary_plus([1,1],[1],x). x = [0,0,1]. 

and mode binary_plus(-,-,+), example

?- binary_plus(x,x,[0,1]). x = [1]. 

im not allowed using cut sign,findall,negation,or if-then-else.

here code:

is_binary([]). is_binary([x]):- x 1. is_binary([x|xs]):-     append(_,[1],xs),     member(x,[0,1]),         is_binary(xs).  binary_plus([],x,x):-     is_binary(x). binary_plus(x,[],x):-      is_binary(x).  binary_plus([0|xs],[y|ys],[y|zs]):-     binary_plus(xs,ys,zs). binary_plus([1|xs],[0|ys],[1|zs]):-     binary_plus(xs,ys,zs). binary_plus([1|xs],[1|ys],[0|zs]):-     binary_plus(xs,[1],ws),     binary_plus(ws,ys,zs). 

i dont know i'm wrong because there strange issues cant solve, if me appreciate it. thanks.

here take on binary-addition-without-anything. understand not use clpfd:

binary_plus(a,b,c) :- binary_plus_0(a,b,c).  binary_plus_0([],    [],    []). binary_plus_0([],    [b|bs],[b|bs]). binary_plus_0([a|as],[],    [a|as]). binary_plus_0([a|as],[b|bs],[c|cs]) :- binary_plus_0(a,b,c,as,bs,cs).  binary_plus_0(0,0,0,as,bs,cs) :- binary_plus_0(as,bs,cs). binary_plus_0(0,1,1,as,bs,cs) :- binary_plus_0(as,bs,cs). binary_plus_0(1,0,1,as,bs,cs) :- binary_plus_0(as,bs,cs). binary_plus_0(1,1,0,as,bs,cs) :- binary_plus_1(as,bs,cs).  binary_plus_1([],    [],    [1]). binary_plus_1([],    [b|bs],cs)     :- binary_plus_0([1],[b|bs],cs). binary_plus_1([a|as],[],    cs)     :- binary_plus_0([a|as],[1],cs). binary_plus_1([a|as],[b|bs],[c|cs]) :- binary_plus_1(a,b,c,as,bs,cs).  binary_plus_1(0,0,1,as,bs,cs) :- binary_plus_0(as,bs,cs). binary_plus_1(0,1,0,as,bs,cs) :- binary_plus_1(as,bs,cs). binary_plus_1(1,0,0,as,bs,cs) :- binary_plus_1(as,bs,cs). binary_plus_1(1,1,1,as,bs,cs) :- binary_plus_1(as,bs,cs). 

Comments

Popular posts from this blog

Payment information shows nothing in one page checkout page magento -

tcpdump - How to check if server received packet (acknowledged) -