One of the most common uses of DCG is to parse unstructured text into a compound term/structure, e.g.
the number 1
into number(1)
.
However in the real world some of those generated structures get rather large and would look nicer if put through a pretty-printer when viewing e.g.
structure(id(23,0),dictionary([key_value(name(Length),number(1992)),key_value(name(Filter),name(FlateDecode))]))
would look nicer as
structure(
id(23,0),
dictionary([
key_value(name(Length),number(1992)),
key_value(name(Filter),name(FlateDecode))
])
)
Here is some basic code that works as the start of a pretty-printer, but it is begging to be turned into a DCG and have the use of append/3 removed.
format(number(Number),S0,S) :-
string_codes("Number: ",Prompt_codes),
append(S0,Prompt_codes,S1),
atom_codes(Number,Number_codes),
append(S1,Number_codes,S).
Yes I know format/3 is not format//1 as is customary but would like it to be.
And some test cases to understand how it should work.
:- begin_tests(format).
test(001) :-
Structure = number(1),
format(Structure,[],Codes),
string_codes(String,Codes),
assertion( String == "Number: 1" ).
test(002) :-
Structure = number(1),
DCG = format(Structure),
phrase(DCG,[],Codes),
string_codes(String,Codes),
assertion( String == "Number: 1" ).
:- end_tests(format).
For those not familiar with SWI-Prolog test cases, running is simple.
?- run_tests(format).
% PL-Unit: format .. done
% All 2 tests passed
true.
As I have never done DCGs in this manner (compound terms/structure to string) and this seems like it would have been done before without using append/3. Any comments, suggestions, feedback, example code, a rewrite of my code, etc., are sought.