用MoonScript实现算术表达式解析



“算术表达式”有两种形式:

  1. 一个数
  2. 一个 '(op e1 e2) 这样的结构(其中 e1 和 e2 是两个“算术表达式”
代码如下
其实就是一个解释器,用递归下降的方式实现

--chekck token is number
isnumber = (exp) -> tonumber(exp) ~= nil

isspace = (c) -> c == ' ' or c == '\t'

len = (exp) -> string.len(exp)

--trim space
trim = (exp ,pos) ->
	while pos <= len(exp) and isspace string.sub(exp,pos,pos)
		pos += 1
	pos

--get token from pos and return next valid pos
token = (exp,pos) ->
	pos = trim(exp,pos)
	if pos > len(exp)
		return nil,pos
	lpos = pos
	while pos <= len(exp) and not isspace string.sub(exp,pos,pos)
		pos += 1
	t = string.sub(exp,lpos,pos-1)
	return t,pos

calc = (exp,pos)->
	t ,pos = token(exp,pos)
	if t == nil 
		return nil,pos
	
	if isnumber t
		return tonumber(t),pos
	if t == '('
		op,pos = token(exp,pos)
		v1 ,pos = calc(exp,pos)
		v2,pos = calc(exp,pos)
		t ,pos = token(exp,pos)
		if( t ~= ')')
			return nil,pos
		v = nil
		switch op
			when '+'
				v = v1 + v2
			when '-'
				v = v1 - v2
			when '/'
				v = v1 / v2
			when '*'
				v = v1 / v2 
			else
				v = nil
		return v,pos
	else
		return nil,pos	

run = (exp) -> 
	r,pos = calc(exp,1)
	if r == nil 
		print('error exp ',exp,'at pos ',pos)
	return r


print run '( / ( + 100 2 ) 3 )'
print run '( -          ( + ( * 10.25 333 ) 999 ) 100 )'
print rum '(+ 1 2)'	--failed
print run ' + 1 '
print run '( / ( + 1 2  3 )'
print run '( ^ 1 2 )'


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值