Search code examples
prologdcg

convert prolog input `(a,z,b)` to `[a,z,b]`


I am new to prolog.

I need to convert the prolog input which is a given variable in the format of coma separated values inside open and close brace (a,z,b) to a prolog list of the form [a,z,b] .

Can some one please help?


Solution

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

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

    I assume that 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].