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

Parsing multiple-digit numbers in Prolog

I have the following simple 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 a 1-digit number. How can I parse numbers with multiple digits in this case?

+10
prolog dcg grammar
Jul 19 '10 at 9:27
source share
3 answers

Use battery variables and pass them in recursive calls. Further, A and A1 are the battery.

 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 battery by consuming a number, because you do not want to match an empty string.

+9
Jul 19 '10 at 11:54
source share
 nat(0). nat(N):-nat(N-1). 

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

-one
Jul 19 '10 at 11:52
source share

Can you provide sample input?

I think this might work:

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

If this fails, follow these steps:

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

The! it is a contraction that stops unification. You can read about it in books / textbooks.

-3
Jul 19 '10 at 10:39
source share



All Articles