Module: Pikuri::Tool::Calculator

Defined in:
lib/pikuri/tool/calculator.rb

Overview

Evaluates a basic arithmetic expression with Python operator syntax and semantics, via the hand-rolled recursive-descent Parser below.

Hand-rolled rather than a gem: the previous backend (dentaku) pulled in concurrent-ruby (~16k lines — pikuri's single heaviest audit item) plus bigdecimal and tsort just for four-function arithmetic. The ~100 lines here implement Python's grammar directly, which also retires the old +**+→+^+ preprocessing (the model's native syntax is now the grammar).

Scope is intentionally narrow: operators (+, -, *, /, //, %, **), unary minus, parentheses, and integer/decimal/e-notation literals. No variables, functions, or booleans — those would teach the model a dialect.

Defined Under Namespace

Classes: Error, Parser

Class Method Summary collapse

Class Method Details

.calculate(expression) ⇒ String

Evaluate expression and return the result as a String. Parse and arithmetic failures (division by zero, overflow to infinity, complex results) come back as "Error: ..." so the model self-corrects.

Parameters:

  • expression (String)

    Python-syntax arithmetic expression

Returns:

  • (String)

    numeric result, or "Error: ..." on failure



30
31
32
33
34
35
36
37
38
39
# File 'lib/pikuri/tool/calculator.rb', line 30

def self.calculate(expression)
  result = Parser.new(expression).parse
  if result.is_a?(Float) && !result.finite?
    raise Error, "result of #{expression.inspect} is not a finite number"
  end

  format_result(result)
rescue Error => e
  "Error: #{e.message}"
end