Prolog中的嵌套谓词

问题描述 投票:1回答:1

我正在尝试写一个在另一个谓词的“范围”内“存在”的谓词。我需要这个的原因是因为两个谓词都使用相同的非常大的参数/数组,而我要嵌套的谓词多次进行自递归,所以我想避免复制相同的参数。所以,有什么办法可以在Swi-Prolg中做到吗?

谢谢。

nested prolog swi-prolog
1个回答
0
投票

您不需要。您必须认识到所有由Prolog变量名称“命名”的术语都是已经全局,尽管在​​子句中没有引用它们的名称时无法访问(并且names总是local to a条款)。那个“非常大的数组”正在堆积。只需将名称传递给任何其他谓词即可,费用为〜0。

正如Paulo Moura所说:

假设您有:

foo(BigArray) :- do_things(BigArray),do_more_things(BigArray).

然后成立:

% Consulting an element of the array:

do_things(BigArray) :- nth0(0,BigArray,Elem),nonvar(Elem),!,write(Elem).

% "Refining" the array by binding an Element that is a fresh variable ("freshvar"):

do_things(BigArray) :- nth0(0,BigArray,Elem),var(Elem),!,Elem=bar.

% on return to foo/1, "bar" on position 0 is visible to the caller 
context and to do_more_things/1 because that array is a "global term".
© www.soinside.com 2019 - 2024. All rights reserved.