Did you know ... | Search Documentation: |
Predicate maplist/3 |
maplist(G, [X_11, ..., X_1n], [X_21, ..., X_2n], ..., [X_m1, ..., X_mn]) :- call(G, X_11, ..., X_m1), call(G, X_12, ..., X_m2), ... call(G, X_1n, ..., X_mn).
This family of predicates is deterministic iff Goal is
deterministic and List1 is a proper list, i.e., a list that
ends in []
.
?- maplist(plus(3), [1, X], [Y, 2]). X = -1, Y = 4.
?- length(L, 3), maplist(between(0, 1), L). L = [0, 0, 0] ; L = [0, 0, 1] ; L = [0, 1, 0] ; L = [0, 1, 1] ; L = [1, 0, 0] ; L = [1, 0, 1] ; L = [1, 1, 0] ; L = [1, 1, 1].
?- length(L, 5), maplist(=(foo), L). L = [foo, foo, foo, foo, foo].
?- maplist(atom, [a, b, c]). true. ?- maplist(atom, [a, 2, c]). false.
?- maplist(between(1, 3), [1, 2, 3]). true. ?- maplist(between(1, 3), [1, 2, 99]). false.
With the help of library(csv) and library(http/json), we read a CSV file and use the column names in the first row to emit JSON.
For this example, we use the file weather.csv
:
city,temp_lo,temp_hi,prcp,date San Francisco,46,50,0.25,1994-11-27 San Francisco,43,57,0,1994-11-29 Hayward,37,54,,1994-11-29
The script csv_to_json.pl
reads the CSV from standard input or from
the file provided as the first argument of the script. It converts
the contents to a list of dicts, then writes this as JSON to standard
output:
:- initialization(main, main). :- use_module(library(csv)). :- use_module(library(http/json)). main :- ( current_prolog_flag(argv, [CSV_file|_]) -> csv_read_file(CSV_file, CSV, []) ; csv_read_stream(current_input, CSV, []) ), CSV = [Colnames|Rows], Colnames =.. [row|Names], maplist(row_dict(Names), Rows, Dicts), json_write_dict(current_output, Dicts, [null('')]). row_dict(Names, Row, Dict) :- Row =.. [row|Fields], pairs_keys_values(Data, Names, Fields), dict_create(Dict, _, Data).
The null('')
option to json_write_dict/3 is necessary to convert the
empty "prcp" field in the last row to a missing value represented as
null
in the JSON output.
This is how we can use it to convert weather.csv
to JSON:
$ swipl csv_to_json.pl weather.csv [ { "city":"San Francisco", "date":"1994-11-27", "prcp":0.25, "temp_hi":50, "temp_lo":46 }, { "city":"San Francisco", "date":"1994-11-29", "prcp":0, "temp_hi":57, "temp_lo":43 }, { "city":"Hayward", "date":"1994-11-29", "prcp":null, "temp_hi":54, "temp_lo":37 } ]
word_frequency_count(Words, Counts) :- maplist(downcase_atom, Words, LwrWords), msort(LwrWords, Sorted), clumped(Sorted, Counts).
?- word_frequency_count([a,b,'A',c,d,'B',b,e], Counts). Counts = [a-2, b-3, c-1, d-1, e-1].