2012-12-13 32 views
-2

我怎样才能解决这个问题?我如何计算原子Prolog?

输入: count_atoms(T,计数)

输出 count_atoms(A(B,C(d,e)中,f)中,计数)。 Count = 4;

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

回答

0

使用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长期和递归的参数列表。

1

也许一个基于堆栈的方法可以提供帮助。你可以写至少有四个助手断言这可能是这样的:

% 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谓词和一个停止算法和产生的结果。