Display a list in its 'raw' ./2 format

2020-04-07 05:08发布

问题:

Is it possible to display a Prolog list in its ./2 format, e.g.

for the list:

| ?- L=[a,b,c].
L = [a,b,c] ? 
yes

Is there a means to display:

L = .(a, .(b, .(c, []))).

回答1:

Normally, write_canonical(List) or ?- write_term(List, [quoted(true), ignore_ops(true)]), as pointed out in the comments. Since SWI-Prolog decided to do things differently, this is not good enough:

?- write_canonical([a]).
[a]
true.

?- write_term([a], [quoted(true), ignore_ops(true)]).
[a]
true.

?- write_term([a], [dotlists(true)]).
.(a,[])
true.

See the documentation on write_term/2, pay attention to the options brace_terms(Bool) and dotlists(Bool). But beware: if you start SWI-Prolog 7 normally, the ./2 is not the list functor any more!

?- L = .(a, []).
ERROR: Type error: `dict' expected, found `a' (an atom) % WHAT?

?- L = '[|]'(a, []).
L = [a].

If you start it with swipl --traditional, things are back to normal, sort of:

$ swipl --traditional
Welcome to SWI-Prolog (Multi-threaded, 64 bits, Version 7.3.4-32-g9311e51)
Copyright (c) 1990-2015 University of Amsterdam, VU Amsterdam
SWI-Prolog comes with ABSOLUTELY NO WARRANTY. This is free software,
and you are welcome to redistribute it under certain conditions.
Please visit http://www.swi-prolog.org for details.

For help, use ?- help(Topic). or ?- apropos(Word).

?- L = .(a, []).
L = [a].

You still cannot use write_canonical(List) or write_term(List, [quoted(true), ignore_ops(true)]).

Read the linked section of the SWI-Prolog documentation for details and rationale. As an advice, if you decide to use SWI-Prolog stick to SWI-Prolog 7 with the defaults and only use write_term(List, [dotlists(true)]) if you need to communicate with another Prolog implementation. The usual list notation, [a, b, ...] should be good enough in most conventional situations.



标签: list prolog