Download Developing Applications with ECLiPSe

Transcript
CHAPTER 6. INPUT/OUTPUT
70
how this is done. For each item in a list we extract the relevant arguments,
and write them to the output file separated by white space.
:-mode output_data(++,+).
output_data(File,L):open(File,’write’,S),
(foreach(X,L),
param(S) do
output_item(S,X)
),
close(S).
output_item(S,data_item with [attr1:A1,attr2:A2]):write(S,A1),
write(S,’ ’),
write(S,A2),
nl(S).
We use the predicate write to print out the individual fields. As this predicate
handles arbitrary argument types, this is quite simple, but it does not give
us much control over the format of the fields.
6.3.3
Using printf
Instead, we can use the predicate printf which behaves much like the Clibrary routine. For each argument we must specify the argument type and
an optional format. If we make a mistake in the format specification, a
run-time error will result.
:-mode output_data(++,+).
output_data(File,L):open(File,’write’,S),
(foreach(X,L),
param(S) do
output_item(S,X)
),
close(S).
output_item(S,data_item with [attr1:A1,attr2:A2]):printf(S,"%s %d\n",[A1,A2]).
We can use the same schema for creating tab or comma separated files, which
provides a simple interface to spreadsheets and data base readers.