implement interpreter and demo + bug fixes
- implement interpreter and demo - replace StandardError with appropriate subclasses - implement division - rewrite Polynomial.simplify()
This commit is contained in:
70
lib/ruby_algebra/interpreter.rb
Normal file
70
lib/ruby_algebra/interpreter.rb
Normal file
@@ -0,0 +1,70 @@
|
||||
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
|
||||
Reference in New Issue
Block a user