Class: Lispcalc::Context

Inherits:
Object
  • Object
show all
Defined in:
lib/lispcalc/context.rb

Instance Method Summary collapse

Constructor Details

#initialize(variables = nil, constants = nil) ⇒ Context

Returns a new instance of Context.



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# File 'lib/lispcalc/context.rb', line 3

def initialize(variables = nil, constants = nil)
  @variables = variables.dup || default_variables
  @constants = constants.dup || default_constants
  @constants.freeze

  unless @variables.values.all?(BigDecimal) && @constants.values.all?(BigDecimal)
    raise ArgumentError, 'variables and constants must be BigDecimal'
  end

  # constant names override variable names
  common_keys = @variables.keys.to_set & @constants.keys.to_set
  common_keys.each do |key|
    @variables.delete(key)
  end
end

Instance Method Details

#[](key) ⇒ Object



19
20
21
# File 'lib/lispcalc/context.rb', line 19

def [](key)
  @variables[key] || @constants[key]
end

#[]=(key, value) ⇒ Object



23
24
25
26
27
# File 'lib/lispcalc/context.rb', line 23

def []=(key, value)
  return unless @variables.key?(key) && value.instance_of?(BigDecimal)

  @variables[key] = value
end

#const?(name) ⇒ Boolean

Returns:

  • (Boolean)


33
34
35
# File 'lib/lispcalc/context.rb', line 33

def const?(name)
  @constants.key?(name)
end

#var?(name) ⇒ Boolean

Returns:

  • (Boolean)


29
30
31
# File 'lib/lispcalc/context.rb', line 29

def var?(name)
  @variables.key?(name)
end