Write list element into csv in prolog

Viewed 233

i have to write into csv file with csv_write_file.
My actual code is:

insert(T, File, Data) :-
    Data = [X | Xs],
    X =.. [_, _, A, B, C],
    csv_write_file(File, [row(A, B, C)], [separator(0'\t)]),
    insert(T, File, Xs).

Data is a list like this :

[test(name, a, b, c), test(name, d, e, f), test(name, g, h, i)].

At the end, the file contain only last element of list --> g h i

but i want a file like this:

a b c
d e f
g h i

Whats wrong with my implementation ? thanks.

1 Answers

The reason this happens is because csv_write_file/3 each time will restart writing to the File. So at the end, it will take g, h, i and write these to the file.

You can process the data in bulk to a list of row/3s and then write these to the file:

map_item(P, row(A, B, C)) :-
    P =.. [_, _, A, B, C].

insert(T, File, Data) :-
    maplist(map_item, Data, Rows),
    csv_write_file(File, Rows, [separator(0'\t)]).
Related