Dylan Nico
Dylan Nico

Reputation: 79

Extract string from csv file after reading in Prolog

Good evening,

I am trying to read a csv file in Prolog containing all the countries in the world. Executing this code:

read_KB(R) :- csv_read_file("countries.csv",R).

I get a list of Terms of this type:

R = [row('Afghanistan;'), row('Albania;'), row('Algeria;'), row('Andorra;'), row('Angola;'), row('Antigua and Barbuda;'), row('Argentina;'), row('Armenia;'), row(...)|...].

I would like to extract only the names of each country in form of a String and put all of them into a list of Strings. I tried this way with only the first row executing this:

read_KB(L) :- csv_read_file("/Users/dylan/Desktop/country.csv",R),
        give(R,L).

give([X|T],X).

I obtain only a Term of type row('Afghanistan;')

Upvotes: 0

Views: 135

Answers (2)

CapelliC
CapelliC

Reputation: 60014

The answer given by @slago can be simplified, using arg/3 instead of a lambda expression, making it slightly more efficient:

read_KB(Names) :-
    csv_read_file('countries.csv', Rows, [separator(0';)]),
    maplist(arg(1), Rows, Names).

Upvotes: 2

slago
slago

Reputation: 5509

You can use maplist/3:

read_KB(Names) :-
    csv_read_file('countries.csv', Rows, [separator(0';)]),
    maplist([row(Name,_), Name] >> true, Rows, Names).

Upvotes: 2

Related Questions