Convert input prologue `(a, z, b)` to `[a, z, b]`

I am new to the prologue.

I need to convert the input of the prologue, which is a given variable, in the format of coma-separated values ​​inside the open and closing brackets (a,z,b)into a prolog list of the form [a,z,b].

Can anyone help?

+3
source share
2 answers

The main functor of the sequence is, / 2, the list. / 2. Hence,

% call: convert(+Sequence,-List)
convert(','(A,B), [A|B1]) :- !, convert(B,B1).
convert(A,[A]).

I assume that the elements of the sequence should not be converted:

?- convert((1,2,3),L).
L = [1, 2, 3].

?- convert((1,(2,3),4),L).
L = [1, (2, 3), 4].
+4
source

In addition to what Alexander wrote above: how often DCGs are great for describing lists in this case, especially if you also want to smooth tuples in a tuple:

tuple_list((A,B)) --> !, tuple_list(A), tuple_list(B).
tuple_list(A)     --> [A].

, , ( , ):

?- phrase(tuple_list((1,(2,3),4)), Ls).
Ls = [1, 2, 3, 4].

, , , DCG. , "defaulty", " " ( ), , . . , (a, b, c) , triple (a, b, c), , .., .

+2
source

All Articles