Converting integer elements of list to a decimal i

2019-08-20 06:48发布

I would like to convert an integer list into a decimal number but am getting an instantiation error I cannot fix.Below is my code to try to this.

number([X|[]],X).
number([X|XS],Y) :-
   len([X|XS],B),
   BB is B-1,
   YY is X*10^(BB),
   L is Y+YY,
   number(XS,L).

I am not too sure how to go over this problem. len is a function to return the length of the given list. Any help is appreciated

标签: prolog
1条回答
女痞
2楼-- · 2019-08-20 07:33

Assuming you have a list of integers that are decimal digits (e.g, having the domain of 0–9). You should be able to do something like this:

digits_value( Ds , V ) :-
  digits_value(Ds,0,V)
  .

digits_value( []     , V , V ) .
digits_value( [D|Ds] , T , V ) :-
  T1 is 10*T + D ,
  digits_value(Ds,T1,V)
  .

The nice thing about the tail recursion is that you build the result as you go. On each call, you just scale by a factor of 10 and add. You don't care about powers of 10.

To do it the way you're trying to do it, you might try reversing the list so as not to fuss with powers of 10:

digits_value(Ds,V) :-
  reverse(Ds,X) ,
  digits_value_x(X,V)
  .

digits_value_x([D],D).
digits_value_x([D|Ds],V) :-
  digits_value_x(Ds,T) ,
  V is 10*T + D
  .

Alternatively you could do something like this:

digits_value(Ds,V) :-
  length(Ds,L) ,
  S is 10**(L-1) ,
  digits_value_x(X,S,V)
  .

digits_value_x([D],1,D).
digits_value_x([D|Ds],S,V) :-
  S1 is S / 10 ,
  digits_value_x(Ds,S1,T) ,
  V is D*S + T
  .
查看更多
登录 后发表回答