4

How do I pretty print a list of terms in SWI-Prolog.

I have tried:

portray_clause([term1, term2]).

but that just writes out in a long stream and a string even comes out as a list of ascii character codes - where I'd like "abc" to be printed.

false
  • 10,264
  • 13
  • 101
  • 209
codeshot
  • 1,183
  • 1
  • 9
  • 20

2 Answers2

2

This is a frequent problem in SWI. By default "abc" is a list of character codes, thus it is printed as:

?- Xs = "abc".
   Xs = [97,98,99].

Can this be converted back easily? Imagine you had a list of distances which happen to be 97, 98, and 99. In that case a string would be very misleading as an answer. Therefore, there is no clean solution to your problem, as long as the string-notation means list-of-character codes!

You can switch the meaning of "abc" to a list of chars which are atoms of length 1:

?- set_prolog_flag(double_quotes,chars).
   true.
?- Xs = "abc".
   Xs = [a,b,c].

If you are happy with it you can use library(double_quotes).

?- use_module(library(double_quotes)).
true.
?- Xs = "abc".
   Xs = "abc".

For more, see this thread.

false
  • 10,264
  • 13
  • 101
  • 209
  • 1
    This is a great answer for printing the strings, but I haven't marked it as an answer because portray clause still doesn't pretty print terms even if the strings in them are much better. – codeshot May 12 '12 at 16:59
0

Here's a hint.. look up the difference between strings and atoms.. you probably only need to hold things as strings if you want to pull them apart an analyse individual characters of the string eg. using nth0 or nth1. Otherwise, atoms work fine for most things / can be manipulated easily.

?- write(["a", "b", "c"]).
[[97],[98],[99]]
true.

?- write(['a','b','c']).
[a,b,c]
true.
magus
  • 1,347
  • 7
  • 13