I want to merge list of digits to number.
[1,2,3] -> 123
My predicate:
merge([X], X).
merge([H|T], X) :-
merge(T, X1),
X is X1 + H * 10.
But now I get: [1,2,3] -> 33
I want to merge list of digits to number.
[1,2,3] -> 123
My predicate:
merge([X], X).
merge([H|T], X) :-
merge(T, X1),
X is X1 + H * 10.
But now I get: [1,2,3] -> 33
Another way to do it would be to multiply what you've handled so far by ten, but you need an accumulator value.
The math is off. You're rule says you have to multiply
H
by10
. But reallyH
needs to be multiplied by a power of 10 equivalent to its position in the list. That would be* 100
for the 1, and* 10
for the 2. What you get now is:10*1 + 10*2 + 3
which is 33. The problem is that your recursive clause doesn't know what numeric "place" the digit is in.If you structure the code differently, and use an accumulator, you can simplify the problem. Also, by using CLP(FD) and applying some constraints on the digits, you can have a more general solution.