尾递归和反转列表的问题?

时间:2012-12-14 08:32:55

标签: recursion prolog logic tail

您好我有一个这样的数字列表(436,L)。

如何反转列表,并使其尾递归?

list_of_digits(0,[]).
list_of_digits(M, [Z|Zx]) :- M > 0 , 
                  MM is floor(M / 10), 
                  Z is M mod 10,        
                  list_of_digits(MM,Zx).

任何人都可以帮助我吗?

我想改变我的号码,在这种情况下是436 列表如[4,3,6]。

I call  ?-  list_of_digits(436,L)
and get 
    L = [6,3,4] ;
    false.
back.

2 个答案:

答案 0 :(得分:1)

使用累加器:

list_of_digits(X,L) :- lod_acc(X, [], L).
lod_acc(0,R,R).
lod_acc(M,Acc,R) :-
    M > 0, 
    MM is floor(M / 10), 
    Z is M mod 10,        
    lod_acc(MM,[Z|Acc],R).

答案 1 :(得分:0)

我这样做,处理负数和零本身(特殊情况):

%
% the external/public API predicate.
%
% this handles the special case of zero, which has 1 digit.
% all other cases are handled by the internal worker predicate.
%
digits_in( X , Ds  ) :- int(X) , X > 0 ,               digits_in(X,[],Ds).
digits_in( X , Ds  ) :- int(X) , X < 0 , Y is abs(X) , digits_in(Y,[],Ds).
digits_in( 0 , [0] ) .

%
% the internal/private guts-of-the-operation predicate
%
digits_in( 0 , Ds , Ds ).        % when we hit zero, we're done.
digits_in( X , Ts , Ds ) :-      % otherwise...
  T  is X mod 10 ,               % get the lower order digit via modulus arithmetic
  X1 is X //  10 ,               % get the high order digits via integer division
  digits_in( X1 , [T|Ts] , Ds )  % [tail-]recurse down.
  .