Question

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

Was it helpful?

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.

OTHER TIPS

Interesting; I don't get that result from the code you show; I just get a failure to parse the input.

First, think about what your string rule recognizes. Does it recognize any string of characters? Or only strings of characters that don't have a comma?

Then think about how the list_w terminates. What code handles the case of the final "table" in your input? It can't be upto_comma, because that requires that "table" be followed by a comma. And list_w doesn't have any right hand side that doesn't include upto_comma.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top