Class: MathEngine

Inherits:
Object
  • Object
show all
Defined in:
lib/lexer.rb,
lib/nodes.rb,
lib/errors.rb,
lib/parser.rb,
lib/context.rb,
lib/math_engine.rb,
lib/evaluators/finders.rb,
lib/evaluators/calculate.rb

Defined Under Namespace

Modules: Evaluators Classes: AdditionNode, AssignmentNode, Context, DivisionNode, ExponentNode, ExpressionNode, FunctionCallNode, IdentifierNode, LiteralNumberNode, ModulusNode, MultiplicationNode, Node, ParametersNode, ParenthesisedExpressionNode, ParseError, Parser, SubtractionNode, UnableToModifyConstantError, UnknownEvaluatorError, UnknownFunctionError, UnknownVariableError

Constant Summary collapse

Lexer =
Lexr.that {
  ignores /\s/ => :whitespace

  legal_place_for_binary_operator = lambda { |prev| [:addition,
                                                     :subtraction,
                                                     :multiplication,
                                                     :division,
                                                     :open_parenthesis,
                                                     :start].include? prev.type }

  matches ',' => :comma
  matches '=' => :assignment
  matches '+' => :addition, unless: legal_place_for_binary_operator
  matches '-' => :subtraction, unless: legal_place_for_binary_operator
  matches '*' => :multiplication, unless: legal_place_for_binary_operator
  matches '/' => :division, unless: legal_place_for_binary_operator
  matches '^' => :exponent, unless: legal_place_for_binary_operator
  matches '%' => :modulus, unless: legal_place_for_binary_operator
  matches '(' => :open_parenthesis
  matches ')' => :close_parenthesis

  matches /[a-z][a-z0-9_]*/i => :identifier, convert_with: lambda { |v| v.to_sym }
  matches /([-+]?(\d+\.?\d*|\d*\.?\d+)([Ee][-+]?[0-2]?\d{1,2})?[r]?|[-+]?((\d+\.?\d*|\d*\.?\d+)([Ee][-+]?[0-2]?\d{1,2})?)?[i]|[-+]?(\d+\.?\d*|\d*\.?\d+)([Ee][-+]?[0-2]?\d{1,2})?[r]?[-+]((\d+\.?\d*|\d*\.?\d+)([Ee][-+]?[0-2]?\d{1,2})?)?[i])/ => :number, convert_with: lambda { |v| BigDecimal(v) }
}
DEFAULT_OPTIONS =
{evaluator: :calculate,
case_sensitive: true}

Instance Method Summary collapse

Constructor Details

#initialize(opts = {}) ⇒ MathEngine

Returns a new instance of MathEngine.



16
17
18
19
# File 'lib/math_engine.rb', line 16

def initialize(opts = {})
  @opts = DEFAULT_OPTIONS.merge(opts)
  @opts[:context] = Context.new(@opts) unless @opts[:context]
end

Instance Method Details

#contextObject



26
27
28
# File 'lib/math_engine.rb', line 26

def context
  @opts[:context]
end

#evaluate(expression) ⇒ Object



21
22
23
24
# File 'lib/math_engine.rb', line 21

def evaluate(expression)
  evaluator = MathEngine::Evaluators.find_by_name(@opts[:evaluator]).new(context)
  Parser.new(Lexer.new(expression)).parse.evaluate(evaluator)
end