class Regaxp::Eiruc

Parses and execute Reverse Polish notation expressions.

Attributes

functions[RW]

Public Class Methods

new() click to toggle source
# File lib/regaxp/eiruc.rb, line 10
def initialize
  @functions = {}
end

Public Instance Methods

evaluate(expression) click to toggle source
# File lib/regaxp/eiruc.rb, line 14
def evaluate(expression)
  expression.reduce([]) { |stack, token| process_token token, stack }[0]
end
fun(name, fun_object = nil, &fun_body) click to toggle source
# File lib/regaxp/eiruc.rb, line 18
def fun(name, fun_object = nil, &fun_body)
  # TODO: validates fun_object is a callable
  # TODO: validates arity?
  functions[name.to_sym] = fun_body || fun_object
end

Private Instance Methods

execute(operation, stack) click to toggle source
# File lib/regaxp/eiruc.rb, line 32
def execute(operation, stack)
  right = stack.pop
  left = stack.pop

  functions[operation].call left, right
end
fun?(operation) click to toggle source
# File lib/regaxp/eiruc.rb, line 28
def fun?(operation)
  !functions[operation].nil?
end
process_token(token, stack) click to toggle source
# File lib/regaxp/eiruc.rb, line 39
def process_token(token, stack)
  result =
    if token.is_a?(Symbol)
      raise UndefinedFun.new(token) if !fun?(token)
      execute(token, stack)
    else
      token
    end

  stack.push result
end