Parsing numbers with multiple digits in Prolog

被刻印的时光 ゝ 提交于 2019-12-19 05:29:45

问题


I have the following simple expression parser:

expr(+(T,E))-->term(T),"+",expr(E).
expr(T)-->term(T).

term(*(F,T))-->factor(F),"*",term(T).
term(F)-->factor(F).

factor(N)-->nat(N).
factor(E)-->"(",expr(E),")".

nat(0)-->"0".
nat(1)-->"1".
nat(2)-->"2".
nat(3)-->"3".
nat(4)-->"4".
nat(5)-->"5".
nat(6)-->"6".
nat(7)-->"7".
nat(8)-->"8".
nat(9)-->"9".

However this only supports 1-digit numbers. How can I parse numbers with multiple digits in this case?


回答1:


Use accumulator variables, and pass those in recursive calls. In the following, A and A1 are the accumulator.

digit(0) --> "0".
digit(1) --> "1".
% ...
digit(9) --> "9".

nat(N)   --> digit(D), nat(D,N).
nat(N,N) --> [].
nat(A,N) --> digit(D), { A1 is A*10 + D }, nat(A1,N).

Note that the first nat clause initializes the accumulator by consuming a digit, because you don't want to match the empty string.




回答2:


nat(0). 
nat(N):-nat(N-1).

But you use a syntax that I don't know (see my comment above).




回答3:


Can you provide a sample input?

I think this might work:

nat(N)-->number(N).

If that fails try:

nat(N)-->number(N),!.

The ! is a cut it stops the unification. You can read about it in books/tutorials.



来源:https://stackoverflow.com/questions/3279822/parsing-numbers-with-multiple-digits-in-prolog

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!