用于计算最大递归深度的元解释器

时间:2011-07-07 12:09:31

标签: recursion prolog metaprogramming

我正在尝试在prolog中为prolog编写一个元解释器,它将在给定的prolog程序中返回最大达到的递归深度。

此代码实际上计算程序中所有递归调用的数量:

rc( true, 0) :- !.
rc( ( Goal1, Goal2), N) :- !, %we have multiple goals
  rc( Goal1, N1), %count recursive calls in Goal1
  rc( Goal2, N2), %count recursive calls in goals Goal2
  N is N1 + N2. %add both counters

rc( Goal, N) :-
  clause( Goal, Body),
  functor( Goal, F, A), %get functor and airity
  rcount( F/A, Body, NF), %count calls of that functor/airity in the body
  rc( Body, NB), %recursively process the body
  N is NF + NB. %add counters

我必须以某种方式跟踪每个单独的递归路径并比较它们的深度,但在prolog中定义它时会遇到问题。有人能指出我正确的方向吗?

感谢。

1 个答案:

答案 0 :(得分:3)

您可以尝试以下几点:

solve(true, 0) :- !.
solve(Head, Hdepth) :- clause(Head, Body), solve(Body, Bdepth),
    Hdepth is Bdepth + 1.
solve((Goal1, Goal2), Depth) :- solve(Goal1, Depth1), solve(Goal2, Depth2),
    Depth is max(Depth1, Depth2).