问题
I am trying to write a predicate that ‘exists’ inside the ‘scope’ of another predicate . The reason I need this is because both predicates make use of the same very large parameters/arrays and the predicate I want to nest is doing self recurssion many times , so I want to avoid copying the same parameters . So , is there any way i can do this in Swi-Prolg ?
Thanks in advance .
回答1:
You don't need to. You have to realize that all the terms "named" by Prolog variable names are already global, although inaccessible when the clause doesn't have a name referencing them (and names are always local to a clause). That "very large array" is on the heap. Just pass the name to it to any other predicate at ~0 cost.
As Paulo Moura says.
Suppose you have:
foo(BigArray) :- do_things(BigArray),do_more_things(BigArray).
Suppose do_things/1
either just prints the element at position 0 if it is an instantiated term, or sets it to bar
if its is a fresh term:
do_things(BigArray) :- nth0(0,BigArray,Elem),nonvar(Elem),!,write(Elem).
do_things(BigArray) :- nth0(0,BigArray,Elem),var(Elem),!,Elem=bar.
If there was a fresh term on position 0, the, on return to foo/1
, the atom bar
on position 0 is visible to the caller and to do_more_things/1
because that list designated by BigArray
is a "global term".
Some precision on your other question on whether to use "global variables":
SWI-Prolog also has "Global Variables", which are apparently similar to the GNU Prolog "Global Variables":
Global Variables
We read:
Global variables are associations between names (atoms) and terms. They differ in various ways from storing information using assert/1 or recorda/3.
...which means that their purpose is similar to the purpose of assert/1
and recorda/3
: Storing state that survives query termination at the Prolog toplevel - similar to how program clauses of a program are stored.
I would say, use those only if absolutely needed.
Also read the intro: Database, where we find:
The recorded database is not part of the ISO standard but fairly widely supported, notably in implementations building on the‘Edinburgh tradition'. There are few reasons to use this database in SWI-Prolog due to the good performance of dynamic predicates.
来源:https://stackoverflow.com/questions/62187928/nested-predicates-in-prolog