Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prolog Binary Addition Issue?

Tags:

binary

prolog

I have this piece of homework that I have to write in Prolog.The requirement is to write a piece of code that does binary addition such as:

?- add([1,0,1],[1,1],X).
X = [0,0,0,1]

And so, this is the code that I came up with:

add([],[], _).
add([],Y, Z) :- append([], Y, Z).
add(X,[], Z) :- append(X,[],Z).
add([HX|TX],[HY|TY], Z) :-
    HX = 1,
    HY = 1,
    add(TX,TY, Z1),
    add([1],Z1, Z2),
    append([0],Z2,Z),!.
add([HX|TX],[HY,TY], Z) :-
    HX = 0,
    HY = 1,
    add(TX,TY,Z1),
    append([1],Z1, Z),!.
add([HX|TX],[HY|TY], Z) :-
    HX = 1,
    HY = 0,
    add(TX,TY,Z1),
    append([1],Z1, Z),!.
add([HX|TX],[HY,TY], Z) :-
    HX = 0,
    HY = 0,
    add(TX,TY,Z1),
    append([0],Z1, Z),!.

It seems to do what I needed, however, there are strange issues with it that I can not understand, so if someone could guide me to what I have done wrong, I would be glad.

Results:

?- add([1,1,1,1], [1,1],Z).
Z = [0, 1, 0, 0, 1]. % this is correct

?- add([1], [1],Z).
Z = [0, 1]. % this is correct

?- add([1,1,0,1], [1,1],Z).
Z = [0, 1, 1, 1]. % this is correct

?- add([1],[0],Y).
Y = [1|_G7100]. % there is an error here, but its not the big issue.

?- add([1,0,1], [1,1],Z).   
false. % no results are returned.

    104 ?- add([0], [1],Z).
    false. % no results returned either

Problem: Whenever there seems to be a 0 in the first binary list, under some conditions(still trying to figure them out), no results seems to be returned.but I can't seem to locate my error.Would be glad if someone can tell me what I did wrong.

like image 906
user1691809 Avatar asked Sep 23 '12 04:09

user1691809


1 Answers

There are 3 mistakes:

  • Rule #1: Should be add([],[],[]). instead of add([],[], _).. This fails for equal-length lists.
  • Rule #5 and #7: Should be add([HX|TX],[HY|TY], Z) instead of add([HX|TX],[HY,TY], Z). This fails when the second list (Y) contains less than two elements.

Fix these and your code should run well: see here.

like image 178
Sufian Latif Avatar answered Oct 13 '22 20:10

Sufian Latif