Skip to content

Instantly share code, notes, and snippets.

@esad
Created December 3, 2020 10:18
Show Gist options
  • Save esad/6cccf4a37c3b8a8f413897d4f3a66620 to your computer and use it in GitHub Desktop.
Save esad/6cccf4a37c3b8a8f413897d4f3a66620 to your computer and use it in GitHub Desktop.
:- module(csv_writer, [csv_write/3, csv_write_row/1, csv_flush/0]).
:- use_module(util, [rational_string/3, get_keypath_dict/3, rtrim/3]).
:- meta_predicate csv_write(+, +, 0).
csv_write(Path, Fields, Goal) :-
open(Path, write, Out),
maplist(term_to_atom, Fields, AtomFields),
Row =.. [row | AtomFields],
csv_write_stream(Out, [Row], []),
write_loop(Fields, Out, Goal).
csv_write_row(Dict) :- shift(csv_write_row(Dict)).
csv_flush :- shift(csv_flush).
write_loop(Fields, Out, Cont) :-
reset(Cont, Ball, Cont2),
(Cont2 = 0 ->
close(Out)
;
( Ball = csv_write_row(Dict) ->
%format("D = ~w~n", [Dict]),
dict_slice(Fields, Dict, Values),
Row =.. [row | Values],
csv_write_stream(Out, [Row], []),
write_loop(Fields, Out, Cont2)
; Ball = csv_flush ->
flush_output(Out),
write_loop(Fields, Out, Cont2)
; % otherwise
throw(unknown_csv_command)
)
).
dict_slice([], _, []) :- !.
dict_slice([K | Ks], Dict, [V | Vs]) :-
(get_keypath_dict(K, Dict, V0) -> value(V0, V) ; V = ''),
dict_slice(Ks, Dict, Vs).
value(-, '') :- !.
value(date(Y,M,D), Value) :-
!, atomic_list_concat([Y,M,D],'-', Value).
value(Value, Value3) :-
rational(Value), \+ integer(Value), !,
rational_string(Value, Value2, 8),
rtrim("0", Value2, Value3). % Remove padding 0s
value(Value, Value).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment