Search code examples
prologswi-prologdcg

Process user input to "phrase/3" method in Prolog


I have build a DCG with Prolog. The code works, when I do the following call:

phrase(programm(R), [1,+,2], []).

I want the user to write the input, so I did this:

main :- read(Input), atom_chars(Input, R), write(R), phrase(programm(E), R).

Calling main and input e.g. '1+2' doesn't work. How can I process the user input to the phrase method for calling my DCG?


Solution

  • SWI-Prolog offers an handy way, by means of tokenize_atom.

    program(sum(L,R)) --> [L, +, R].
    
    ?- tokenize_atom('1 + 2', L), phrase(program(P), L).
    L = [1, +, 2],
    P = sum(1, 2).