I am trying to learn to use Prolog and was very pleasantly surprised to find SWI Prolog provides a CSV library out of the box: https://www.swi-prolog.org/pldoc/man?section=csv
However I have no idea how to use it, specifically, with below data (saved inside Data.csv
file):
Name,Value
A,150
B,300
C,50
And below snippet:
:- use_module(library(csv)).
get_data(Rows) :-
csv_read_file("Data.csv", Rows).
I could in swipl easily get the following:
> swipl .\Code.pl
1 ?- get_data(Rows).
Rows = [row('Name', 'Value'), row('A', 150), row('B', 300), row('C', 50)].
However, the return result looks like a list of terms, and there are two issues:
csv_read_stream
instead? Can you please show an example?Rows
? What I would like to do is to interactively make queries in swipl just as with raw prolog terms/predicates loaded as a .pl
file. E.g. I wish to issue queries like this: ?- row(Name,Value), Value > 150.
to find all names with Value
above a certain value.Thanks!
Remark:
To get the tail part of the list, you can pattern match in the query itself.
get_data([Header|Rows]).
Now with the Rows
you have, you need to check for member
s of the list.
?- member(X, [1, 2, 3, 4]), X >= 3.
X = 3 ;
X = 4.
so full query would be something like:
get_data([Header|Rows]), member(row(Name, Value), Rows), Value > 50.