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



72
73
74
75
76
77
78
79
80
# File 'lib/opt/expression.rb', line 72

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((parts || [self]) + [self.class.to_expression(other)])
end

#-(other) ⇒ Object



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

def -(other)
  Expression.new((parts || [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

#valueObject



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

def value
  values = parts.map(&:value)
  return nil if values.any?(&:nil?)

  values.sum
end

#varsObject



67
68
69
# File 'lib/opt/expression.rb', line 67

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