Debugging with difference list of character codes

Difference list of character codes are not friendly to writing for output because they are still a list of characters codes.

An easy way to convert a difference list to a closed list is to unify the tail of the list with [] which converts it to a difference list. This however means that the difference list is now bound and not open for further use as a difference list.

The use of double negation (/+ /+) which will undo binds when done allows one to convert a difference list to a closed list and still allow the difference list to be a difference list at the end of the double negation.

debug/3 is useful for debugging but typically the values are bound before use.

Converting a value for use with debug/3 only to be thrown away if debug/3 is not activated is a waste.

So how can one use debug/3 but only do the conversion from a difference list to a closed list when the debug/3 statement is active?

format/2 has @

Interpret the next argument as a goal and execute it. Output written to the current_output stream is inserted at this place. Goal is called in the module calling format/3. This option is not present in the original definition by Quintus, but supported by some other Prolog systems.

Example code

rule(T0,T) -->
    { debug(parse,'~@',[write_dl('rule',T0,T)]) }.

write_dl(Name,T0,T) :-
    \+ \+ (
        T = [],
        format('~w: `~s~n''',[Name,T0])