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:
- How do I skip the first header row? I tried to look at documentation and couldn't figure out an easy way. ChatGPT says I might need to use
csv_read_streaminstead? Can you please show an example? - What do I do with
Rows? What I would like to do is to interactively make queries in swipl just as with raw prolog terms/predicates loaded as a.plfile. E.g. I wish to issue queries like this:?- row(Name,Value), Value > 150.to find all names withValueabove a certain value.
Thanks!
Remark:
- Import csv file data to populate a Prolog knowledge base Partly answers my question but it says "see it at documentation" which I tried and couldn't comprehend - I need specific code examples on how to ignore the first header row and how to make use of the returned list as queryable knowledge.
To get the tail part of the list, you can pattern match in the query itself.
Now with the
Rowsyou have, you need to check formembers of the list.so full query would be something like: