Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing numbers with multiple digits in Prolog

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?

like image 429
ubuntudroid Avatar asked Jul 19 '10 09:07

ubuntudroid


1 Answers

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.

like image 89
Fred Foo Avatar answered Nov 04 '22 17:11

Fred Foo