Class: MIPPeR::LinExpr
- Inherits:
-
Object
- Object
- MIPPeR::LinExpr
- Defined in:
- lib/mipper/expression.rb
Instance Attribute Summary collapse
-
#terms ⇒ Object
readonly
Returns the value of attribute terms.
Instance Method Summary collapse
-
#+(other) ⇒ Object
Add two LinExprs.
-
#add(other) ⇒ Object
Add terms from the other expression to this one.
-
#initialize(terms = {}) ⇒ LinExpr
constructor
A new instance of LinExpr.
-
#inspect ⇒ Object
Produce a string representing the expression.
Constructor Details
#initialize(terms = {}) ⇒ LinExpr
Returns a new instance of LinExpr.
5 6 7 |
# File 'lib/mipper/expression.rb', line 5 def initialize(terms = {}) @terms = terms end |
Instance Attribute Details
#terms ⇒ Object (readonly)
Returns the value of attribute terms.
3 4 5 |
# File 'lib/mipper/expression.rb', line 3 def terms @terms end |
Instance Method Details
#+(other) ⇒ Object
Add two MIPPeR::LinExprs
10 11 12 13 14 15 16 17 18 19 20 21 22 |
# File 'lib/mipper/expression.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 end end |
#add(other) ⇒ Object
Add terms from the other expression to this one
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
# File 'lib/mipper/expression.rb', line 25 def add(other) case other when LinExpr @terms.merge!(other.terms) { |_, c1, c2| c1 + c2 } when Variable if @terms.key? other @terms[other] += 1.0 else @terms[other] = 1.0 end else fail TypeError end self end |
#inspect ⇒ Object
Produce a string representing the expression
43 44 45 46 47 48 49 50 51 |
# File 'lib/mipper/expression.rb', line 43 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 |