Did you know ... | Search Documentation: |
Predicate with_output_to/2 |
For capturing other streams, see with_output_to/3.
Applications should generally avoid creating atoms by breaking and concatenating other atoms, as the creation of large numbers of intermediate atoms generally leads to poor performance, even more so in multithreaded applications. This predicate supports creating difference lists from character data efficiently. The example below defines the DCG rule term//1 to insert a term in the output:
term(Term, In, Tail) :- with_output_to(codes(In, Tail), write(Term)). ?- phrase(term(hello), X). X = [104, 101, 108, 108, 111]
Output takes one of the shapes below. Except for the
first, the system creates a temporary stream using the wchar_t
internal encoding that points at a memory buffer. The encoding cannot be
changed and an attempt to call set_stream/2
using encoding(Encoding)
results in a permission_error
exception.
Evidently, if the goal fails, and you output to a variable, you will have nothing:
?- with_output_to( string(T), (format("Hello",[]), format(",World",[]))). T = "Hello,World".
but
?- with_output_to( string(T), (format("Hello",[]), format(",World",[]), false)). false.
Btw, the above is easier written and read using format/3:
?- format(string(T1),"Hello",[]), format(string(T2),",World",[]), string_concat(T1,T2,T). T1 = "Hello", T2 = ",World", T = "Hello,World".