2012-12-13 31 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謂詞和一個停止算法和產生的結果。