Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>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.</p> <p>Bash, on the other hand, uses dynamic scoping, and so, using a variable <code>i</code> in a <code>for</code> loop, and using a variable <code>i</code> in another function, which happens to be called during -- or not -- the loop execution, will affect each other's <code>i</code> value.</p> <p>This may go not very straightforward, so, an example:</p> <pre><code>#!/bin/bash function my_first_I() { I=10; } function my_second_I() { I=100; } I=1; echo $I; my_first_I; echo $I; my_second_I; echo $I; </code></pre> <p>Output:</p> <pre><code>$ ./script.sh 1 10 100 </code></pre> <p>The trick here is that a variable is messing up with a thought-to-be different one.</p> <p>Now, as you may be aware of, you're not able to this in prolog:</p> <pre><code>#!/usr/bin/swipl my_first_I(I) :- I is 10. my_second_I(I) :- I is 100. test(I) :- I is 1, write(I), nl, my_first_I(_), write(I), nl, my_second_I(_), write(I), nl. </code></pre> <p>Output:</p> <pre><code>?- test(I). 1 1 1 I = 1. </code></pre> <p>This example does simply point out that, in prolog, the variable is defined in its own local scope, with no <em>leakage</em> into another function's definition.</p> <p>Now, the second part: how does the <code>!</code> work? The logic programming solutions generated by Prolog are derived after the application of an <a href="http://en.wikipedia.org/wiki/Unification_%28computer_science%29" rel="nofollow">unification algorithm</a>. 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.</p> <p>If an <code>!</code> is found, the breadth expansion is stopped, <em>cutting off</em> other possible values for the local solution, and only perfoming the deeper expansions in the tree. <a href="http://en.wikibooks.org/wiki/Prolog/Cuts_and_Negation" rel="nofollow">Here</a> is a quite simple usage of the <code>!</code> operator.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload