When I run a query after creating my Prolog listing, how does Prolog use scoping to solve it? I understand that the cut operator ! can affect the results. Does it do this by affecting the scope?
When I run a query after creating my Prolog listing, how does Prolog use
Share
First things first: does prolog uses dynamic scoping? No, it does not, and the reason why it doesn’t is because prolog needs to keep track of the variables defined, so that any new assignment would refer to the initial variable — and not to last value assigned to that variable name.
Bash, on the other hand, uses dynamic scoping, and so, using a variable
iin aforloop, and using a variableiin another function, which happens to be called during — or not — the loop execution, will affect each other’sivalue.This may go not very straightforward, so, an example:
Output:
The trick here is that a variable is messing up with a thought-to-be different one.
Now, as you may be aware of, you’re not able to this in prolog:
Output:
This example does simply point out that, in prolog, the variable is defined in its own local scope, with no leakage into another function’s definition.
Now, the second part: how does the
!work? The logic programming solutions generated by Prolog are derived after the application of an unification algorithm. During the process, a tree-like structure is built in a DFS fashion, performing evaluations on the statements according to the values variables may assume. After each leaf-level expansion, Prolog backtracks up to the next available expansion.If an
!is found, the breadth expansion is stopped, cutting off other possible values for the local solution, and only perfoming the deeper expansions in the tree. Here is a quite simple usage of the!operator.