Created
December 3, 2020 10:18
-
-
Save esad/6cccf4a37c3b8a8f413897d4f3a66620 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
:- 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