解析Prolog中具有多个数字的数字 [英] Parsing numbers with multiple digits in Prolog

查看:82
本文介绍了解析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".

但是,它仅支持1位数字.在这种情况下,如何解析具有多个数字的数字?

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

推荐答案

使用累加器变量,并将其传递给递归调用.在下面,A和A1是累加器.

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

请注意,第一个nat子句通过使用数字来初始化累加器,因为您不想匹配空字符串.

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

这篇关于解析Prolog中具有多个数字的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆