_(underscore) is a "don't-care" variable, which will match anything (atom, number, structure, …). For example, the rule
bad(Dog) :- bites(Dog, _).
says that something (
Dog) is bad if
bites anything. The "anything" is represented by
other variables in Prolog, a bare
_ can match different
things in the same rule. So, for example, if
Gift) is a three-place procedure that is true if
giver(X) :- gives(X, _, _).
signifies that someone (
X) is a "giver" if
something to anybody - the two
_ s don't have to match the same
thing. So if
gives(fred, john, black_eye). is stored in the Prolog
database, then the rule above allows us to infer that
fred is a
To be more explicit about the meaning of your rule, you could instead write:
bad(Dog) :- bites(Dog, _Anybody).This indicates what the
_variable is actually representing, but has the feature that the binding of
_Anybodytypically doesn't get reported when Prolog finds a solution. In Prolog interpreters that report singleton variables (variables that are only used once in a rule - often these are caused by typographical errors in the code, which is why Prolog warns you about them) do not report singleton variables that begin with
_. This is useful is you are trying to get rid of warning messages in your Prolog code.
bad(Dog) :- bites(Dog, _Anybody).in fact has a bug, in the sense that the _Anybody will match things (like dogfood) that a dog might bite without being "bad". Maybe the rule should say instead:
bad(Dog) :- bites(Dog, Something), is_person(Something). % add your own list of prohibitions - shoes, cats, …
Prolog systems make internal use of variable names beginning with
an underscore, e.g.
_G157. These are not "don't-care"
variables, but are chosen to not clash with any variable name a Prolog
programmer is likely to use.
Underscores may also be used in the middle of variable or atom names, as in
- again, these are not "don't-care" variables.
The idea is to make the variable or atom name more readable.