Module: VectorSpace::InstanceMethods

Defined in:
lib/vector_space/vector_space.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



40
41
42
43
44
45
46
47
48
# File 'lib/vector_space/vector_space.rb', line 40

def self.included(base)
  base.class_eval do
    extend Forwardable
    def_delegators :'self.class', :components, :dimensions, :order, :reflect_on_component

    include PartialOrder
    include Arithmetic
  end
end

Instance Method Details

#<=>(other) ⇒ Object

Compares the receiver against another object, returning -1, 0, +1 or nil depending on whether the receiver is less than, equal to, greater than, or incomparable with the other object. This works just like the #<=> expected by Comparable, but also returns nil iff the two objects are incomparable.



75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/vector_space/vector_space.rb', line 75

def <=>(other)
  if compatible_with?(other)
    comparisons = map_values(dimensions, other) { |a, b| a <=> b }

    case order
    when :product
      comparisons.inject { |a, b| a + b if a && b && a * b >= 0 }
    when :lexicographic
      comparisons.inject { |a, b| a == 0 ? b : a }
    end
  end
end

#compatible_with?(other) ⇒ Boolean

Decides whether the receiver is compatible with some other object for general operations (e.g. arithmetic and comparison).

Returns:

  • (Boolean)


68
69
70
# File 'lib/vector_space/vector_space.rb', line 68

def compatible_with?(other)
  other.class == self.class
end

#map_components(components, *vectors) ⇒ Object



55
56
57
# File 'lib/vector_space/vector_space.rb', line 55

def map_components(components, *vectors)
  Array(components).map { |component| [component, yield(*([self] + vectors).map { |vector| vector.project(component) })] }
end

#map_values(components, *vectors, &block) ⇒ Object



59
60
61
# File 'lib/vector_space/vector_space.rb', line 59

def map_values(components, *vectors, &block)
  map_components(components, *vectors, &block).map { |component, value| value }
end

#project(component) ⇒ Object



50
51
52
53
# File 'lib/vector_space/vector_space.rb', line 50

def project(component)
  reflection = reflect_on_component(component)
  reflection.value(send(reflection.getter))
end

#zero?Boolean

Returns:

  • (Boolean)


63
64
65
# File 'lib/vector_space/vector_space.rb', line 63

def zero?
  map_values(dimensions) { |value| value.zero? }.all?
end