Our textbook gave us this example of a structurer for a math equation in Prolog:
math(Result) --> number(Number1), operator(Operator), number(Number2), { Result = [Number1, Operator, Number2] }.
operator('+') --> ['+'].
number('number') --> ['NUMBER'].
I'm quite new to Prolog, however, and I have no idea how to use this example to get the output. I'm under the impression it restructures the input using Result
and outputs it for use.
The only input I've tried that doesn't cause an error is math('number', '+', 'number').
but it always outputs false
and I don't know why. Furthermore shouldn't it restructure it and give me the result in Result
as well?
What should I be inputting here?
This example is a DCG. You should use the phrase/2
interface predicate to access DCGs.
To find out what the DCG describes, start with the most general query, relating the nonterminal math(R)
to a list Ls
that is described by the first argument:
?- phrase(math(R), Ls).
From the answer you get (very easy exercise!), you will notice that R
is probably not what you meant it to be. Hint: Look up (=..)/2
.
Notice in particular that you need not be "inputting" anything here: A DCG describes a list. The list can be specified, but need not be given: A variable will do too! Think in terms of relations between arbitrary terms.