Class: Opt::Expression

Inherits:
Object
  • Object
show all
Defined in:
lib/opt/expression.rb

Direct Known Subclasses

Constant, Product, Variable

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(parts = []) ⇒ Expression

Returns a new instance of Expression.



5
6
7
# File 'lib/opt/expression.rb', line 5

def initialize(parts = [])
  @parts = parts
end

Instance Attribute Details

#partsObject (readonly)

Returns the value of attribute parts.



3
4
5
# File 'lib/opt/expression.rb', line 3

def parts
  @parts
end

Class Method Details

.to_expression(other) ⇒ Object

private



65
66
67
68
69
70
71
72
73
# File 'lib/opt/expression.rb', line 65

def self.to_expression(other)
  if other.is_a?(Numeric)
    Constant.new(other)
  elsif other.is_a?(Expression)
    other
  else
    raise TypeError, "can't cast #{other.class.name} to Expression"
  end
end

Instance Method Details

#*(other) ⇒ Object



21
22
23
# File 'lib/opt/expression.rb', line 21

def *(other)
  Expression.new([Product.new(self, self.class.to_expression(other))])
end

#+(other) ⇒ Object



9
10
11
# File 'lib/opt/expression.rb', line 9

def +(other)
  Expression.new([self, self.class.to_expression(other)])
end

#-(other) ⇒ Object



13
14
15
# File 'lib/opt/expression.rb', line 13

def -(other)
  Expression.new([self, -self.class.to_expression(other)])
end

#-@Object



17
18
19
# File 'lib/opt/expression.rb', line 17

def -@
  -1 * self
end

#<(other) ⇒ Object

TODO allow for integer expressions

Raises:



31
32
33
# File 'lib/opt/expression.rb', line 31

def <(other)
  raise Error, "Strict inequality not allowed"
end

#<=(other) ⇒ Object



39
40
41
# File 'lib/opt/expression.rb', line 39

def <=(other)
  Comparison.new(self, :<=, other)
end

#==(other) ⇒ Object



43
44
45
# File 'lib/opt/expression.rb', line 43

def ==(other)
  Comparison.new(self, :==, other)
end

#>(other) ⇒ Object

TODO allow for integer expressions

Raises:



26
27
28
# File 'lib/opt/expression.rb', line 26

def >(other)
  raise Error, "Strict inequality not allowed"
end

#>=(other) ⇒ Object



35
36
37
# File 'lib/opt/expression.rb', line 35

def >=(other)
  Comparison.new(self, :>=, other)
end

#coerce(other) ⇒ Object

keep order



52
53
54
55
56
57
58
# File 'lib/opt/expression.rb', line 52

def coerce(other)
  if other.is_a?(Numeric)
    [Constant.new(other), self]
  else
    raise TypeError, "#{self.class} can't be coerced into #{other.class}"
  end
end

#inspectObject



47
48
49
# File 'lib/opt/expression.rb', line 47

def inspect
  @parts.map(&:inspect).join(" + ").gsub(" + -", " - ")
end

#varsObject



60
61
62
# File 'lib/opt/expression.rb', line 60

def vars
  @vars ||= @parts.flat_map(&:vars)
end