Prolog作业:如何将表示数值的'bits'列表解析为十进制表示?

时间:2010-03-04 19:31:49

标签: list binary prolog

好的,所以我对我正在努力解决的prolog作业问题有另一个问题。问题如下:

编写一个Prolog程序,它将获取一个表示二进制数字位的列表,并返回该列表所代表的整数的十进制值。

示例:valueof([1,1,0,1],X)。 X = 13

所以这就是我到目前为止所拥有的:

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

再一次,我感谢任何帮助,我似乎真的在努力解决这个问题。感谢。

2 个答案:

答案 0 :(得分:2)

你的算法看起来太复杂了;尝试这些方面:

  • 基本情况:一位数字列表,返回数字
  • 递归案例:返回最后一位数字加上列表结果的2倍,删除最后一位数字。

由于它是家庭作业,我会将实施细节留给您。

答案 1 :(得分:1)

我想说我不同意卡尔对基本案例的选择。我们必须处理空列表的情况,最好不要有多种类型的“基本情况”。 “基础”案例的类比就是递归“底部”的情况,我们都知道事物只有一个底部或底部。

所以我建议:

  • 基本情况:
    • 空列表,其值为“零”(0)
    • 这种情况结束了递归,因此必须将任何累积的值复制到输出参数中。
  • 初始情况:尚未累积任何数字,累加器变量将为零(0)。
  • 递归情况:每次递归中检查的数字累积到累加器

prolog代码如下所示:

% Initial value of accumulator is zero (0).
valueOf( L, X) :- value_of_accumulation( L, 0, X).

% Base case:
% When there are no more digits to process, the output value (3rd param)
% is unified with the accumulator (2nd param)
value_of_accumulation( [], A, A).

% The recursive step.  There is a digit (B) to process here.  T is a temporary
% which holds the value of the accumulator "passed down" to the next case
% and, ultimately, to the base case after possible more accumulations.  A holds
% the previously-accumulated value derived from more-significant bits, already
% processed in previous recursions.  This clause is invoked once for each bit.
% Implicitly, the invocations of this clause generate a "count" but there is no
% actual use of the count when accumulating the bits.  Each bit is accumulated
% without knowledge of whether subsequent bits follow.
value_of_accumulation( [B | L], A, X) :-
    B >= 0,
    B =< 1,
    T is % fill this in with math, a function of bit B and previously-accumulated bits A,
    value_of_accumulation( L, %fill this in with prolog understanding.