I have a predicate that receives a binary number in the form of an atom, and returns a list of hexadecimal codes.
?- binaryHex('11111111',X).
X = [f, f].
When I try to go from hexadecimal to binary, I get this error:
?- binaryHex(X,[f,f]).
ERROR: atom_codes/2: Arguments are not sufficiently instantiated
I want both variables to produce the correct output. Here is the code.
hex('0000',0). hex('0001',1). hex('0010',2). hex('0011',3).
hex('0100',4). hex('0101',5). hex('0110',6). hex('0111',7).
hex('1000',8). hex('1001',9). hex('1010',a). hex('1011',b).
hex('1100',c). hex('1101',d). hex('1110',e). hex('1111',f).
binaryHex(X,Y) :-
atom_codes(X,A),
binaryList(A,B),
binaryHex_(B,Y).
binaryList([],[]).
binaryList([A,B,C,D|Ds],[Y|Ys]) :-
atom_codes(Y,[A,B,C,D]),
binaryList(Ds,Ys).
binaryHex_([],[]).
binaryHex_([B|Bs],[H|Hs]) :-
hex(B,H),
binaryHex_(Bs,Hs).
The variables in the predicates binaryHex_/2
and binaryList/2
work both ways. The program breaks down because of the order of instantiation in the original binaryHex/2
: binaryList/2
must come before binaryHex_/2
in order for the original task of binary to hex to work.
I imagine that this problem will be compounded if I convert the hexadecimal list to an atom. What are some strategies to cope with this situation so that as I continue to program I do not run into instantiation errors? Any comments/answers as to when this is not achievable are also encouraged.