Class: Heist::Runtime::Vector

Inherits:
Array
  • Object
show all
Defined in:
lib/heist/runtime/data/vector.rb

Overview

Vector is Scheme’s equivalent of Ruby’s Array class, and Heist implements it by subclassing Array. In Scheme code a vector is denoted as a proper list preceeded by a # symbol, for example #(1 2 3). Vectors are flat, non-recursive data structures, meaning they are faster for accessing slots by numeric index since we do not have to walk a tree to find the correct node.

As an example, you can think of the list (1 2 3) and the vector #(1 2 3 4) as having the following structure:

Proper list: (1 2 3)      Vector: #(1 2 3 4)

      .                           .
     / \                          |
    1   .                   -------------
       / \                  |   |   |   |
      2   .                 1   2   3   4
         / \ 
        3  ()

Accessing a member of a vector takes time independent of the member’s index, whereas access time scales as O(n) for lists.

Instance Method Summary collapse

Constructor Details

#initialize(*args, &block) ⇒ Vector

A Vector is initialized using a sequence of values, just like a Ruby Array. Optionally, it can be initialized using an array and a block, which will be used to map the array to new values before inserting into the Vector.

Vector.new([1,2,3,4]) { |x| x*x }
#=> #(1 2 3 4)


36
37
38
39
# File 'lib/heist/runtime/data/vector.rb', line 36

def initialize(*args, &block)
  return super(*args) unless block_given?
  args.first.each_with_index { |cell, i| self[i] = block.call(cell) }
end

Instance Method Details

#[]=(index, value) ⇒ Object

Sets the value at the given index. Will throw an exception if the Vector is frozen. The Scheme function (vector-set!) also performs out-of-bounds checks to keep vectors a fixed size, but this is not enforced at this level.

Raises:



51
52
53
54
# File 'lib/heist/runtime/data/vector.rb', line 51

def []=(index, value)
  raise ImmutableError.new("Cannot modify vector constant") if frozen?
  super
end

#freeze!Object

Performs a recursive freeze of the Vector and all its members.



42
43
44
45
# File 'lib/heist/runtime/data/vector.rb', line 42

def freeze!
  freeze
  each { |slot| slot.freeze! if slot.respond_to?(:freeze!) }
end

#to_sObject Also known as: inspect

Returns a Scheme-style string representation of the Vector.



57
58
59
# File 'lib/heist/runtime/data/vector.rb', line 57

def to_s
  '#(' + map { |cell| Heist.stringify(cell) }.join(' ') + ')'
end