Search code examples
prologdcg

Prolog DCG read from file with separotr


I'm making my first steps in Prolog, but I have encountered a problem.

I'm trying to read from a file records separated by comma

upto_comma(Codes) --> string(Codes), ",", !.
list_w([W|Ws]) --> upto_comma(W), [W] ,list_w(Ws).
string([]) -->  [].
string([H|T]) -->[H],string(T).

but all I got is a list with the single characters, while what I wanted is a list of element. For example from

cat,dog,table

I want [cat,dog,table] and I got [c,a,t,d,o,g,t,a,b,l,e].

I have tried to change upto_comma in

upto_comma(Atom) --> string(Codes), ",", !,{ atom_codes(Atom, Codes) }.

but nothing changed.

I think there's some basic concept I misunderstood, anybody can help? I'm using SWIProlog


Solution

  • Your grammar misses the base case of list_w//1, and I can't understand why after upto_comma(W) you require the same thing just read.

    I would write this way

    list_w([W|Ws]) --> string(W), ",", !, list_w(Ws).
    list_w([W]) --> string(W).
    
    string([]) -->  [].
    string([H|T]) -->[H],string(T).
    

    test:

    ?- phrase(list_w(S),"cat,dog").
    S = [[99, 97, 116], [100, 111, 103]] ;
    false.