Variables and how they are set and used in prolog

2019-07-27 09:30发布

http://www.csupomona.edu/~jrfisher/www/prolog_tutorial/2_1.html

So on that tutorial where it has:

conflict(Coloring) :- 
   adjacent(X,Y), 
   color(X,Color,Coloring), 
   color(Y,Color,Coloring). 

Am I understanding this correctly, that Color is a variable and is set to a value after the first call to color and then that value is used in the second call to color?

标签: prolog
2条回答
Ridiculous、
2楼-- · 2019-07-27 10:06

Color it's a variable, but we can't say if it will get a value (in Prolog this is called binding) from the first or the second call to color/3. All depends on the color/3 definition. But given this code it's probable that your assumption it's ok.

查看更多
戒情不戒烟
3楼-- · 2019-07-27 10:10

Variables in Prolog:

  1. All variables and arguments are local in scope to the predicate in which they are declared (aka first used). Excepting of course that variables may be passed as arguments (essentially "by reference") to another predicate.

  2. Prolog variables are only "variable" until bound (unified) with something else. At that point they cease to be variable and become one with that with which they were unified. Hence the use of the term "unification": to unify is to become one.

  3. Backtracking, of course, undoes any unification that might have occurred, returning things to the status quo ante as it were.

  4. The special variable _ is the "anonymous variable". Each use, even within the same clause of a predicate is independent. For instance, given the facts

    letter(a).
    letter(b).
    letter(c).
    
    digit(1).
    digit(2).
    digit(3).
    

the predicate:

foo :- letter(A),number(A).

fails, whilst

foo :- letter(_),number(_).

will succeed (9 times, with backtracking).

查看更多
登录 后发表回答