Skip to content

Instantly share code, notes, and snippets.

@koleksiuk
Last active August 29, 2015 14:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save koleksiuk/11054262 to your computer and use it in GitHub Desktop.
Save koleksiuk/11054262 to your computer and use it in GitHub Desktop.
require 'dentaku'
class ExtendedCalculator < Dentaku::Calculator
def initialize(*args)
super
add_exponent
end
private
def add_exponent
self.add_function(
name: :exp,
type: :numeric,
signature: [:numeric, :numeric],
body: ->(mantissa, exponent) { mantissa ** exponent }
)
end
end
class Guard
def initialize(proc = nil, &block)
@proc = if block_given?
block
else
proc
end
end
def call(args = {})
return true unless @proc
@proc.call(*args.values)
end
end
class Formula
InvalidArgs = Class.new(StandardError)
def initialize(formula, guard = Guard.new)
@formula = formula
@guard = guard
end
def calculate(args = {})
raise InvalidArgs unless @guard.call(args)
calculator.evaluate(@formula, args)
end
protected
def calculator
@calculator ||= ExtendedCalculator.new
end
end
f1 = Formula.new("x/(exp(x,2) - 4)", Guard.new {|x| x > 0 } )
begin
puts "F2(2): #{f1.calculate(x: 2)}"
rescue => e
puts e
end
begin
puts "F1(-1): #{f1.calculate(x: -1)}"
rescue => e
puts "Invalid args"
puts e
end
f2 = Formula.new("x + y")
begin
puts "F2(-1, 2): #{f2.calculate(x: 1, y: 2)}"
rescue => e
puts e
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment