Parsing numbers with multiple digits in Prolog

后端 未结 3 908
北荒
北荒 2021-01-11 14:41

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).
ter         


        
3条回答
  •  没有蜡笔的小新
    2021-01-11 15:36

    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.

提交回复
热议问题