L
Lui Kore
Hi dear everyone,
I just made a small parser combinator library for ruby1.9 (sadly it's
1.9 only).
It's simple(buggy) and fast(ha, it beats treetop on arithmetics!).
Please have a look if you are interested in.
install:
gem install rsec -s http://gemcutter.org
source code (about 500 LOCs):
http://github.com/luikore/rsec
the terrible document:
http://wiki.github.com/luikore/rsec/
Yours, sincerely, and many best regards.
Helloworld: a simple arithmetic calculator
#---------------------------------------------------------
require 'rubygems'
require 'rsec'
include Rsec::Helpers
def arithmetic
calculate = proc do |(p, *ps)|
ps.each_slice(2).inject(p) do |left, (op, right)|
left.send op.strip, right
end
end
num = /[+-]?[1-9]\d*(\.\d+)?/.r.map &:to_f
bra = '('.r.skip
ket = ')'.r.skip
paren = (bra << lazy{@expr} << ket).map &:first
factor = paren | num
term = factor.join(/\s*[\*\/]\s*/).map &calculate
@expr = term.join(/\s*[\+\-]\s*/).map &calculate
end
puts arithmetic.parse '1 + 2.3 / 4 - 5 + 6 * 7.8 / (9 +10)'
I just made a small parser combinator library for ruby1.9 (sadly it's
1.9 only).
It's simple(buggy) and fast(ha, it beats treetop on arithmetics!).
Please have a look if you are interested in.
install:
gem install rsec -s http://gemcutter.org
source code (about 500 LOCs):
http://github.com/luikore/rsec
the terrible document:
http://wiki.github.com/luikore/rsec/
Yours, sincerely, and many best regards.
Helloworld: a simple arithmetic calculator
#---------------------------------------------------------
require 'rubygems'
require 'rsec'
include Rsec::Helpers
def arithmetic
calculate = proc do |(p, *ps)|
ps.each_slice(2).inject(p) do |left, (op, right)|
left.send op.strip, right
end
end
num = /[+-]?[1-9]\d*(\.\d+)?/.r.map &:to_f
bra = '('.r.skip
ket = ')'.r.skip
paren = (bra << lazy{@expr} << ket).map &:first
factor = paren | num
term = factor.join(/\s*[\*\/]\s*/).map &calculate
@expr = term.join(/\s*[\+\-]\s*/).map &calculate
end
puts arithmetic.parse '1 + 2.3 / 4 - 5 + 6 * 7.8 / (9 +10)'