What does the -->
operator do in Prolog and what is the difference between it and :-
?
I'm using SWI Prolog.
What does the -->
operator do in Prolog and what is the difference between it and :-
?
I'm using SWI Prolog.
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.
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.
phrase/2
interface to DCGs ensures that your code will work without changes if the DCG implementation changes behind the scenes in the future. –
Neoclassicism :-
and -->
" question. (link answers frowned upon no matter what). I'll sleep over it in any case. And likely add some disclaimer to clear up the "explanation" vs "this is not 100% accurate" situation in the morning. If you're up to it, I would like to know how not using phrase/2
could actually blow up. I don't use DCGs every day, but FBOW that's how they were taught to me. –
Crawfish © 2022 - 2024 — McMap. All rights reserved.