Reputation: 87
I would like to know if someone could help me with a problem in prolog. I have to define two predicates but before that, I need to find out a way how to parse a list and form a number. For example [1,2,3] => 123. I tried different ways to do this but nothing works good. My code looks like this, I know it is not good but I can't find another way.
num([H|T],I,RI,RES):-
H2 is H * I,
R1 is RI + H2,
I2 is I/10,
RES2 is RES + R1,
num(T,I2,R1,RES2).
Upvotes: 0
Views: 323
Reputation: 58234
Your hunch is correct that this can be much simpler. Recursively, you want to think of the digits [A, B, C]
representing number as, (((A * 10) + B) * 10) + C
.
To start, you want to think about what kind of predicate you desire. That would simply be, num(Digits, Number).
which yields Number
given Digits
. You'll need an accumulator for intermediate results using the above formula concept, so your num/2
needs to call a num/3
that will include an accumulator argument that you carry along:
num(Digits, Num) :-
num(Digits, 0, Num). % Accumulator initially 0
If the input list is empty, the result is the accumulator:
num([], A, A). % Result is accumulator when there are no digits
Then your recursive case:
num([D|T], A, R) :-
NewA is (D * 10) + A, % New accumulator is (current digit * 10) + old accumlator
... % Need recursive call
I'll leave the ...
for you to fill in as an exercise. :)
Upvotes: 2