Class: NaiveCalculator::Environment

Inherits:
Object
  • Object
show all
Defined in:
lib/naive_calculator/environment.rb

Defined Under Namespace

Classes: Function

Instance Method Summary collapse

Constructor Details

#initialize(initial_bindings: {}) ⇒ Environment

Returns a new instance of Environment.



9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/naive_calculator/environment.rb', line 9

def initialize(initial_bindings: {})
  @bindings = initial_bindings.merge(
    pi: BigDecimal(Math::PI, 15),
    e:  BigDecimal(Math::E, 15)
  )

  @functions = {
    sin: Function.new(1, lambda { |x| BigDecimal(Math.sin(x), 10) }),
    cos: Function.new(1, lambda { |x| BigDecimal(Math.cos(x), 10) }),
    log: Function.new(2, lambda { |x,y| BigDecimal(Math.log(x, y), 10) }),
    pow: Function.new(2, lambda { |x,y| x**y }),
  }
end

Instance Method Details

#define_function(name, arity, body) ⇒ Object



36
37
38
# File 'lib/naive_calculator/environment.rb', line 36

def define_function(name, arity, body)
  @functions[name] = Function.new(arity, body)
end

#define_variable(name, value) ⇒ Object



32
33
34
# File 'lib/naive_calculator/environment.rb', line 32

def define_variable(name, value)
  @bindings[name] = value
end

#initialize_copyObject



23
24
25
26
# File 'lib/naive_calculator/environment.rb', line 23

def initialize_copy(*)
  @bindings = @bindings.dup
  @functions = @functions.dup
end

#lookup_function(name, arity) ⇒ Object



40
41
42
43
44
45
46
47
# File 'lib/naive_calculator/environment.rb', line 40

def lookup_function(name, arity)
  function = @functions[name]

  raise "No function `#{name}`" unless function
  raise "Function `#{name}` takes #{function.arity} argument(s) (#{arity} given)" unless function.arity == arity

  function.body
end

#lookup_variable(name) ⇒ Object



28
29
30
# File 'lib/naive_calculator/environment.rb', line 28

def lookup_variable(name)
  @bindings[name] or raise "No variable `#{name}`"
end