Files
RubyAlgebra/lib/ruby_algebra/interpreter.rb
Slavasil 1fff529e83 implement interpreter and demo + bug fixes
- implement interpreter and demo
- replace StandardError with appropriate subclasses
- implement division
- rewrite Polynomial.simplify()
2026-04-13 19:33:50 +03:00

71 lines
2.2 KiB
Ruby

module RubyAlgebra
class Interpreter
def initialize
@locals = {}
end
def execute(command)
case command.type
when :assignment
unless command.operand1.is_a?(Polynomial)
operand1 = @locals[command.operand1]
return "Undeclared polynomial: #{command.operand1}" if operand1.nil?
else
operand1 = command.operand1
end
unless [:assign, :scale, :diff, :subs].include?(command.operation)
operand2 = @locals[command.operand2]
return "Undeclared polynomial: #{command.operand2}" if operand2.nil?
else
operand2 = command.operand2
end
case command.operation
when :assign
@locals[command.lhs] = operand1
return "#{command.lhs} = #{operand1}"
when :add
result = operand1 + operand2
@locals[command.lhs] = result
return "#{command.lhs} = #{result}"
when :sub
result = operand1 - operand2
@locals[command.lhs] = result
return "#{command.lhs} = #{result}"
when :mult, :scale
result = operand1 * operand2
@locals[command.lhs] = result
return "#{command.lhs} = #{result}"
when :div
result = operand1 / operand2
@locals[command.lhs[0]] = result[0]
@locals[command.lhs[1]] = result[1]
return "Quotient: #{command.lhs[0]} = #{result[0]}, remainder: #{command.lhs[1]} = #{result[1]}"
when :diff
result = operand1
operand2.each do |variable|
result = result.diff(variable)
end
@locals[command.lhs] = result
return "#{command.lhs} = #{result}"
when :subs
result = operand1.evaluate(operand2)
@locals[command.lhs] = result
return "#{command.lhs} = #{result}"
end
when :display
unless command.item.is_a? Polynomial
unless @locals[command.item].nil?
return @locals[command.item].to_s
else
return "Undeclared polynomial: #{command.item}"
end
else
return command.item.to_s
end
end
end
end
end