Character code literals

In the following code I check if a base16 representation of an md5 hash starts with 5 zeros.

From Erlang I’m used to be able to either write "00000" ++ _ = Hash or [$0, $0, $0, $0, $0 | _] = Hash were Hash is a “charlist”, similar to a “code list” in prolog.

I consider these variants much better readable and understandable, and even easier to write than having to repeat a “meaningless” 48 5 times.

?- 0'0 = X.
X = 48.

or a sequence of characters book-ended by `

?- write_canonical(`00000`).
[48,48,48,48,48]
true.

?- `00000` = X.
X = [48, 48, 48, 48, 48].

Also see: The string type and its double quoted syntax and in particular the section Representing text: strings, atoms and code lists

That 0'0 syntax looks nice. Thank you!

Is it explained somewhere?

It is noted as part of Why has the representation of double quoted text changed? but the use of 0' syntax is not a self standing topic.

1 Like

Sad, I don’t have that ~200 Euro. Is there some free (or at least, less expensive) documentation available?

1 Like

And finally:

?- HashCodes = `00001234`, phrase("0000", HashCodes, X).
HashCodes = [48, 48, 48, 48, 49, 50, 51, 52],
X = [49, 50, 51, 52].

This is portable and efficient when using library(apply_macros):

:- use_module(library(apply_macros)).

t(HashCodes) :-
    phrase("0000", HashCodes, _).
$ swipl h.pl
...
?- listing(t).
t(HashCodes) :-
    HashCodes=[48, 48, 48, 48|_].
3 Likes

Which brings us almost full circle to this little beauty:

https://www.swi-prolog.org/pldoc/doc_for?object=f(('.')/2)

?- A is "0".
A = 48.

… but you need to use is/2 for that.

1 Like

Well, it’s just a two-character escape sequence. Real text editors like vim and emacs deal with it alright. :stuck_out_tongue:

vi with Paulo’s syntax file:

and emacs:

and of course if you actually want an IDE for SWI-Prolog you should be probably using PceEmacs.

1 Like

So does Sergio Castro IDEA IntellJ plug-in:
https://plugins.jetbrains.com/idea/plugin/9425-logtalk

Or most of the syntax highlighters I wrote for popular (and not so popular) text editors, IDEs, … :
https://github.com/LogtalkDotOrg/logtalk3/tree/master/coding