Reputation: 7476
What is the meaning of curly brackets in Prolog:
{a,b,c}
I see I can use them, but do they describe tuples or what?
Upvotes: 5
Views: 2889
Reputation: 126
Curly brackets ({
and }
) can be used to isolate normal Prolog goals from the Definite Clause Grammar preprocessor. So the stuff between the curly brackets can be arbitrary Prolog code that is simply not preprocessed with the DCG rules.
As an example, let's say you have the following rules to define a very simple grammar:
sentence -->
nounPhrase, verbPhrase.
nounPhrase -->
det, noun,
{ write ('noun was found'), nl }.
verbPhrase -->
verb, nounPhrase,
{ write ('verb was found'), nl }.
The goal of writing "noun was found"
or "verb was found"
has nothing to do with the consumption of the input sequence. So Prolog lets you add any non-preprocessed goal between curly brackets. Omitting the curly brackets for a non-preprocessed goal will give you an error.
The write
goal added above at the end of the DCG rule was just an example of what curly brackets do (there is no practical use in having a write
goal in DCGs). But here is an example that might be useful in improving the dictionary of the parser: suppose you want your grammar to distinguish between singular and plural nouns. One option would be to have an additional feature argument, like:
noun(n(boy), singular) --> [boy].
noun(n(boy), plural) --> [boys].
But as you add more and more nouns to the vocabulary you're adding unnecessary complexity. You can instead write a Prolog rule between curly brackets to check whether your noun is either singular or plural, something like this:
n(n(NounSingular), Sgn_or_Pl) -->
[Noun],
{ isNoun(Noun, NounSingular, Sgn_or_Pl) }.
For a full description of the usefulness of curly brackets, I recommend reading the paragraph "Adding Extra Tests" in Chapter 8 from "Programming in Prolog" by W. F. Clocksin, C. S. Mellish available here Curly Brackets in Prolog.
Upvotes: 5
Reputation: 60014
Prolog is almost old as C... from the very beginning, it took a peculiar approach to syntax. Since it's a so called homoiconic language, everything is a term. Therefore, we are sure that {a,b,c}
is also a term. In my old Prolog interpreter, I handled '{' and '}' as a separate pair of operators, so being able to process DCG rules, as explained in Clocksin/Mellish Programming in Prolog appendix D (beware, I googled for authors and title, the book is an unofficial copy, and the book I used was much older, maybe 1985...)
Let's explore some syntax on SWI-Prolog REPL:
?- functor({a,b,c},F,N).
F = {},
N = 1.
so, {a,b,c}
it's just a compound, and a,b,c
its argument:
?- {a,b,c} =.. Syntax.
Syntax = [{}, (a, b, c)].
also write_canonical helps when exploring syntax details, but in this case it doesn't make so apparent what the functor is:
?- write_canonical({a,b,c}).
{','(a,','(b,c))}
A noteworthy SWI-Prolog extension, dicts, uses {}
to build a clean object representation...
Upvotes: 10