Class: Guruby::LinExpr

Inherits:
Object
  • Object
show all
Defined in:
lib/guruby/expr.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(terms = {}) ⇒ LinExpr

Returns a new instance of LinExpr.



5
6
7
# File 'lib/guruby/expr.rb', line 5

def initialize(terms = {})
  @terms = terms
end

Instance Attribute Details

#termsObject (readonly)

Returns the value of attribute terms.



3
4
5
# File 'lib/guruby/expr.rb', line 3

def terms
  @terms
end

Instance Method Details

#+(other) ⇒ Object

Add two Guruby::LinExprs



10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/guruby/expr.rb', line 10

def +(other)
  case other
  when LinExpr
    # Add the terms of two expressions
    # For now, this assumes variables are not duplicated
    LinExpr.new(@terms.merge(other.terms) { |_, c1, c2| c1 + c2 })
  when Variable
    # Add the variable to the expression
    self + other * 1.0
  else
    fail TypeError unless other.is_a? LinExpr
  end
end

#inspectObject

Produce a string representing the expression



25
26
27
28
29
30
31
32
33
# File 'lib/guruby/expr.rb', line 25

def inspect
  @terms.map do |var, coeff|
    # Skip if the coefficient is zero or the value is zero
    value = var.value
    next if coeff == 0 || value == 0 || value == false

    coeff == 1 ? var.name : "#{var.name} * #{coeff}"
  end.compact.join(' + ')
end