%% file: g1.pl %% A grammar must specify variables, terminals, and rules. %% Here is the context-free grammar for addition, multiplication %% and exponentiation: %% s -> p + s | p %% p -> e * p | e %% e -> v ^ e | v %% v -> 0 | 1 | 2 | ... | 9 %% Variables are stated as facts. These facts simply state the names of the variables. %% In this example, the facts state that s, p, e, and v are variables. %% These are all in lower case because Prolog thinks of anything beginning %% in uppercase as one of its own unbound variables. variable(s). variable(p). variable(e). variable(v). %% terminal(X) states that X is a terminal. %% In this case, we are defining terminal using some helpers called %% digit and operator. terminal(X) :- digit(X) ; operator(X). digit(0). digit(1). digit(2). digit(3). digit(4). digit(5). digit(6). digit(7). digit(8). digit(9). operator(+). operator(*). operator(^). %% Rules are stated as ordered pairs, where the first element is the left-hand-side %% of a rule and the second argument is the LIST of elements appearing on the right-hand-side %% of that rule. rule(s, [p, +, s]). rule(s, [p]). rule(p, [e, *, p]). rule(p, [e]). rule(e, [v, ^, e]). rule(e, [v]). rule(v, [X]) :- digit(X). member(A, [A | X]). member(A, [_ | X]) :- member(A, X).