2
votes

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

1
Where did I ever endorse codes? I said: This is frequently the default, but it leads to very unreadable answers. By what collusion can this be seen as a preference/recommendation let alone endorsement? - false
@false I changed it. As I often note, this is all CC so feel free to change it. - Guy Coder
Of interest: SWI-Prolog 5.6 Remaining issues - Codes can be used in arithmetic expressions, while chars are more readable. - Guy Coder

1 Answers

3
votes

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'