在序言中将列表的整数元素转换为十进制 [英] Converting integer elements of list to a decimal in prolog

查看:35
本文介绍了在序言中将列表的整数元素转换为十进制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将一个整数列表转换为一个十进制数,但遇到一个我无法修复的实例化错误.下面是我尝试执行此操作的代码.

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).

我不太确定如何解决这个问题.len 是一个返回给定列表长度的函数.任何帮助表示赞赏

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

推荐答案

假设您有一个十进制数字的整数列表(例如,域为 0–9).你应该能够做这样的事情:

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)
  .

尾递归的好处是你可以边走边构建结果.在每次调用时,您只需按 10 倍进行缩放并相加.你不在乎 10 的幂.

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.

要按照您尝试的方式进行操作,您可以尝试颠倒列表,以免对 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
  .

这篇关于在序言中将列表的整数元素转换为十进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆