【问题标题】:Problems with Tail Recursion and reversing list?尾递归和反转列表的问题?
【发布时间】:2012-12-14 08:32:55
【问题描述】:

您好,我有一个电话号码列表(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.

【问题讨论】:

  • @Boris 我想将数字 436 转换为一个列表,在我的示例中,我的列表顺序错误,而不是尾递归,你能解释一下,我怎样才能让它尾递归??
  • 恕我直言,它已经是尾递归了
  • @CapelliC 哦,我只试过。完美,我怎样才能扭转我的名单??
  • @Boris 对不起,我的错,在我的示例中,我得到 [6,3,4] 而不是 [4,3,6],我知道如何反转列表,但我无法合并它。有什么建议吗??我编辑了它。
  • 我已经解决了,谢谢。

标签: recursion prolog logic tail


【解决方案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).

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2021-04-24
      • 2011-12-10
      • 1970-01-01
      • 1970-01-01
      • 2023-04-08
      • 2014-04-13
      • 2011-05-28
      • 2017-09-23
      • 2015-08-10
      相关资源
      最近更新 更多