Okay, so I have another question on a prolog homework problem I am struggling with. The problem goes as follows:
Write a Prolog program that will take a list representing the bits of a binary number, and return the decimal value of the integer that the list represents.
Example: valueof([1,1,0,1],X).
X = 13
So here’s what I have so far:
valueOf(List, X) :- setup(List, [], X).
setup([H|T], [Y|H], X) :- setup(T,Y,X).
setup([], Y, X) :- count(Y, X, 0).
count([], _, _).
count([H|T], X, Count) :- NewCount is Count + 1, NewX is X + (H*2^Count),
count(T,NewX,NewCount).
Once again, I appreciate any help at all, I really seem to be struggling with this prolog stuff. Thanks.
I would say that I disagree with Carl’s choice of base case. We must handle the case of empty list, and it is better not to have multiple types of “base cases.” The analogy of “base” case is the case at the “bottom” of the recursion and we all know things have only one bottom, or base.
So I would suggest:
The prolog code will look like this: