The example below calls the rule set integer/3
defined in section 4.13 and available
from library(library(dcg/basics))
, binding Rest
to the remainder of the input after matching the integer.
?- [library(dcg/basics)]. ?- atom_codes('42 times', Codes), phrase(integer(X), Codes, Rest). X = 42 Rest = [32, 116, 105, 109, 101, 115]
The next example exploits a complete body. Given the following definition of digit_weight1, we can pose the query below.
digit_weight(W) --> [D], { code_type(D, digit(W)) }.
?- atom_codes('Version 3.4', Codes), phrase(("Version ", digit_weight(Major),".",digit_weight(Minor)), Codes). Major = 3, Minor = 4.
The SWI-Prolog implementation of phrase/3 verifies that the List and Rest arguments are unbound, bound to the empty list or a list cons cell. Other values raise a type error.70The ISO standard allows for both raising a type error and accepting any term as input and output. Note the tail of the list is not checked for performance reasons. The predicate call_dcg/3 is provided to use grammar rules with terms that are not lists.
Note that the syntax for lists of codes changed in SWI-Prolog version 7
(see section 5.2). If a DCG body
is translated, both "text"
and `text`
is a
valid code-list literal in version 7. A version 7 string ("text"
)
is not acceptable for the second and third arguments of phrase/3.
This is typically not a problem for applications as the input of a DCG
rarely appears in the source code. For testing in the toplevel, one must
use double quoted text in versions prior to 7 and back quoted text
in version 7 or later.
See also portray_text/1,
which can be used to print lists of character codes as a string to the
top level and debugger to facilitate debugging DCGs that process
character codes. The library library(apply_macros)
compiles phrase/3
if the argument is sufficiently instantiated, eliminating the runtime
overhead of translating DCGBody and meta-calling.