我正在使用Prolog的內置DCG功能編寫一個Lisp-to-C轉換程序。這是我如何處理算術:DCG in Prolog - 字符串
expr(Z) --> "(", "+", spaces, expr(M), spaces, expr(N), ")", {swritef(Z, "%d + %d", [M, N])}.
expr(Z) --> "(", "-", spaces, expr(M), spaces, expr(N), ")", {swritef(Z, "%d - %d", [M, N])}.
expr(Z) --> "(", "*", spaces, expr(M), spaces, expr(N), ")", {swritef(Z, "%d * %d", [M, N])}.
expr(Z) --> "(", "/", spaces, expr(M), spaces, expr(N), ")", {swritef(Z, "%d/%d", [M, N])}.
expr(E) --> number(E).
number(C) --> "-", digits(X), {C is -X}.
number(C) --> digits(C).
digits(D) --> digit(D);digit(A),digits(B), {number_codes(B,Cs),length(Cs,L), D is A*(10^L)+B}.
digit(D) --> [C], {"0"=<C, C=<"9", D is C - "0"}.
現在,它不處理嵌套的表達式。以下是我認爲會的工作:
expr(Z) --> "(", "+", spaces, expr(M), spaces, expr(N), ")", {swritef(Z, "%s + %s", [M, N])}.
expr(E) --> number(N), {swritef(E, "%d", [N])}.
但我發現了這一點:
?- expr(E, "42", []).
E = "42" %all OK
?- expr(E, "(+ 3 (* 2 2))", []).
E = "%s + %s" %not OK
我如何工作的呢?
你使用什麼Prolog? – 2010-12-08 16:29:43
@Bobby:SWI-Prolog version 5.6.64 – Igor 2010-12-12 15:44:39