2
votes

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?

2
If phrase(programm(R), [1,+,2], []) is what works when you run it on its own, why not use, phrase(programm(E), R, []) in your main predicate?lurker

2 Answers

3
votes

The fundamental problem is the way you have defined characters and numbers in your grammar. I assume you defined something along:

program(sum(L,R)) -->
    [L],
    [+],
    [R].

You need first

:- set_prolog_flag(double_quotes, chars).

program(sum(L,R)) -->
   number(L),
   "+",
   number(R).

number(1) --> "1".

Note that 1 is an integer and "1" is ['1']!

2
votes

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).