【问题标题】:How can i count atoms Prolog?我如何计算原子 Prolog?
【发布时间】:2012-12-13 17:02:34
【问题描述】:

我该如何解决这个问题??

输入: count_atoms(T,Count)

输出 计数原子(a(b,c(d,e),f),计数)。 计数 = 4 ;

我真的不知道...请你帮帮我吗??

【问题讨论】:

    标签: prolog logic


    【解决方案1】:

    通过 SWI-Prolog 和递归使用库(aggregate):

    count_atoms(T, Count) :-
           atom(T)
        -> Count = 1
        ;  compound(T)
        -> aggregate_all(sum(C), (arg(_, T, A), count_atoms(A, C)), Count)
        ;  Count = 0
        .
    

    测试:

    ?- count_atoms(a(b,c(1,e),f),Count).
    Count = 3.
    

    但我担心这不是您分配的解决方案。对于更基本的东西,您可以使用 =.. 分解任何 compound 术语并在参数列表上递归。

    【讨论】:

      【解决方案2】:

      也许基于堆栈的方法会有所帮助。您可以编写至少四个辅助谓词,如下所示:

      % Increases accumulator if T is atomic + call to count_atoms/6
      count_atoms(T, Stack, StackSize, Accumulator, Count) :- ...
      
      % Gets the arity of T if T is compound + call to count_atoms/6
      count_atoms(T, Stack, StackSize, Accumulator, Count) :- ...
      
      % Gets Nth subterm of T and puts it on the stack + call to count_atoms/6
      count_atoms(T, N, Stack, StackSize, Accumulator, Count) :- ...
      
      % Pops element from stack + call to count_atoms/5
      count_atoms(T, _, Stack, StackSize, Accumulator, Count) :- ...
      

      但是您仍然需要一个 count_atoms/2 谓词和一个来停止算法并产生结果。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-01-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多