问题
What does the -->
operator do in Prolog and what is the difference between it and :-
?
I'm using SWI Prolog.
回答1:
It is used to define a DCG (Definite Clause Grammar) rule as opposed to a normal predicate. See this tutorial for a very nice explanation of DCG rules.
There are many examples here on Stack Overflow. See the DCG tag.
Here is one very simple solution, showing both the DCG and the normal predicate.
Note that you have to use phrase/2
or phrase/3
to evaluate a DCG. Make sure to read the section of the SWI-Prolog manual on DCGs. The two phrase
predicates are documented there.
回答2:
The -->
operator reads in Definite Clause Grammar rules. It's syntactic sugar to transform rules of the form:
parenthesized_expression(Inner) -->
[ open ],
expression(Inner),
[ close ],
{ nl }.
Into something more like this:
parenthesized_expression(Inner, [open | T1], T2) :-
expression(Inner, T1, [close | T2]),
nl.
This makes writing grammars very convenient. There are helper predicates available to consume them, though you're allowed to do so by hand if you prefer.
来源:https://stackoverflow.com/questions/32579266/what-does-the-operator-in-prolog-do