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

Recursion 用于计算最大递归深度的元解释器,recursion,prolog,metaprogramming,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 Goa

我正试图用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中定义它时有问题。谁能给我指出正确的方向吗


谢谢。

您可以尝试以下方法:

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

我认为您在第一个solve:solve(true,0)中缺少了cut(!):-!。解决方案的Tnx。这实际上比我想象的要简单:)
solve(true,0)
是一个简单的事实。不需要切割。这是纯序言!但是,当回溯时,它将尝试将Head与true匹配,Hdepth与0匹配并成功(第二次求解/2)。这是错误的,当它达到解算(true,0)时,您希望它停止。我不希望剪切。但是,SWI Prolog在回溯时给出了“错误:第/2条:无权访问私有_过程'true/0'”。这可以通过切割来避免。合乎逻辑的理由是肯定只有一个解决方案。好吧,避免这个错误是另一个有效的理由。您仍然可以通过使用catch/3或其他内置谓词来避免剪切,以查看第二个子句中是否可以安全地使用子句/2。关于“仅有一个解决方案”:一个好的声明性解决方案将是,而不是使用内置子句/2来表示将以非默认方式解释的程序,例如像my_子句(Head、[G1、G2、…,G_n])(“true”则对应于空列表)。这样,元解释器就可以写得很好,不需要剪切,而且也可以很容易地解释自己。