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.
Why hand-rolled rather than a gem: the previous backend, dentaku, pulled in concurrent-ruby (~16k lines of Ruby — the single heaviest audit item in pikuri’s whole dependency closure) plus bigdecimal and tsort, all to evaluate four-function arithmetic. The ~100 lines here implement Python’s expression grammar directly, which also retires the old preprocessing step that rewrote Python’s ** into dentaku’s ^ dialect — the model’s native syntax is now simply the grammar.
Scope is intentionally narrow: operators (+, -, *, /, //, %, **), unary minus, parentheses, and integer / decimal / e-notation literals. No variables, functions, or booleans — those would mean teaching the model a dialect, which we specifically want to avoid for this tool.
Defined Under Namespace
Class Method Summary collapse
-
.calculate(expression) ⇒ String
Evaluate
expressionand return the result formatted as a String.
Class Method Details
.calculate(expression) ⇒ String
Evaluate expression and return the result formatted as a String. Parse and arithmetic failures (division by zero, overflow to infinity, complex results) are caught and returned as “Error: …” strings so the model can read the failure as the next observation and self-correct rather than crashing the agent loop.
40 41 42 43 44 45 46 47 48 49 |
# File 'lib/pikuri/tool/calculator.rb', line 40 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.}" end |