Search code examples
prologdcg

handling input in prolog with read()


I am using read() to take in user input. I planned that my program would accept input in the form of

a,b,c,d,e

and then I would convert that into a list of the elements. But doing a test in prolog i got this

26 ?- read(X).
|: abc,def,ghi,jkl.
X = (abc, def, ghi, jkl).

I am not sure, but is this returning a structure? What can I do to convert this into a list?


Solution

  • (abc, def, ghi, jkl) is a term with functor ',' and arity 2. You can use term inspection predicates like (=..)/2, functor/3, arg/3 etc. to decompose it, or try write_canonical/1:

    ?- T = (abc, def, ghi, jkl), write_canonical(T).
    ','(abc,','(def,','(ghi,jkl)))
    T = (abc, def, ghi, jkl).
    

    To convert such tuples to lists, you can use a DCG:

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

    Example:

    ?- T = (abc, def, ghi, jkl), phrase(tuple_list(T), Ls).
    T = (abc, def, ghi, jkl),
    Ls = [abc, def, ghi, jkl].