使用 DCG 进行解析(= 将列表转换为抽象语法树)很容易:
list_ast(Ls, AST) :- phrase(expression(AST), Ls).
expression(E) --> term(T), expression_r(T, E).
expression_r(E0, E) --> [+], term(T), expression_r(E0+T, E).
expression_r(E0, E) --> [-], term(T), expression_r(E0-T, E).
expression_r(E, E) --> [].
term(T) --> power(P), term_r(P, T).
term_r(T0, T) --> [*], power(P), term_r(T0*P, T).
term_r(T0, T) --> [/], power(P), term_r(T0/P, T).
term_r(T, T) --> [].
power(P) --> factor(F), power_r(F, P).
power_r(P0, P0^P) --> [^], factor(P1), power_r(P1, P).
power_r(P, P) --> [].
factor(N) --> [N], { number(N) }.
factor(E) --> ['('], expression(E), [')'].
要实际计算表达式,您可以使用内置谓词 is/2。示例查询:
?- list_ast([2,+,4,+,5,+,1,+,2,*,3], Ast), V is Ast.
Ast = 2+4+5+1+2*3,
V = 18 ;
false.