Search code examples
prologflagsdcg

current_prolog_flag double_quotes DCG (codes or chars)?


In using SWI Prolog DCGs I noticed some people note

:- set_prolog_flag(double_quotes, codes).

Jan

while others note

:- set_prolog_flag(double_quotes, chars).

false, Markus, mat

What is the difference if any when using with DCG and phrase?

References

The string type and its double quoted syntax
DCG
DCG Grammar rules
double_quotes
set_prolog_flag


Solution

  • As the name double_quotes implies, this flag affects how double quotes (i.e.: ") are treated.

    This holds whether or not such quotes are used in connection with DCGs. However, it is especially useful in connection with DCGs because you can for example use:

    ?- phrase(nt(NT), "test").
    

    and thus automatically treat the phrase to be parsed as a list of characters (in this case: [t,e,s,t]). That's nice for interactive test cases.

    The answer by false that you linked to explains it nicely. Note also the following quote from the answer:

    This notation [using chars!] gives more readable answers. It can be even more compactly displayed since the double quote notation can be used for printing any list of one-char atoms.

    It is clear that chars yields more readable answers than codes. For example:

    ?- Xs = "hello".
    Xs = [h, e, l, l, o].
    

    vs., with codes:

    ?- Xs = "hello".
    Xs = [104, 101, 108, 108, 111].
    

    (Ahem.)

    Historically, Han shot first chars came first! Only later, this was changed to using codes by default. A quite unfortunate choice, in my view. Other languages like Haskell work like Prolog originally did:

    Hugs> :t last
    last :: [a] -> a
    Hugs> :t "test"
    "test" :: String
    Hugs> last "test"
    't'