I'm trying to understand the different behavior of predicate in and outside of a rule. when I write:
test(1,2).
in the console I get "predicate not found". but when I write
S=[test(1,2,3)],member(test(1,A,B),S).
prolog answers although the predicate test is still not defined. why is that ?
In your second example, test(1,2,3)
is just a structure. In a conventional language, something like [test(1,2,3)]
would cause the language to go and evaluate some function . Python for instance:
def test(x, y, z):
return 3
Then [test(1,2,3)]
would reduce to [3]
.
This is not how Prolog works. Prolog does not have functions, it has relations , and relations do not have a pre-defined data flow into and out of them. To give a concrete example, consider nth1/3
: if you call nth1(3, [a,b,c], X)
then Prolog gives you back X = c
, but you can also call nth1(X, [a,b,c], c)
and Prolog gives you back X = 3
. You can also call nth1(X, [a,b,c], Y)
and then Prolog will give you back three solutions: X = 1, Y = a
, X = 2, Y = b
and X = 3, Y = c
.
I like this example a lot because it shows you that nth1/3
is doing all the work of Python's enumerate()
and index()
and __getitem__()
. But it also shows you why Prolog cannot just evaluate predicates and replace them with what they "return."
That still leaves you with some ambiguity about what exactly [test(1,2,3)]
means in Prolog. The answer is that it is a list containing Prolog terms. There's just one term in there, a functor or structure test(1,2,3)
. Your second example shows that you are able to unify that structure with another structure. This is a very powerful thing that Prolog lets you do. It's part of what makes Prolog a homoiconic language, meaning a language that has a built-in understanding of its own constituents. For the time being, you can think of it as analogous to Javascript objects or Python dictionaries or C structures. It just happens to have the same shape as the predicate definitions. I consider this fact both a source of great power and great confusion for beginners, so take some heart! It is not intuitive, especially coming from other languages.
In your first example, test
is a predicate of arity 2 which you try to prove and that does not exist.
In your second example, test
is a functor of arity 3. That does not define any test
predicate. It is just a function whose inputs are the values 1
, 2
, and 3
, and whose value is test(1,2,3)
. So, test(1,2,3)
is the value of the function test/3
. A constant like a
may also be viewed as a function, it has no input, and its value is a
.
Predicates define relations between functions.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.