class Cons

Attributes

car[R]
cdr[R]
head[R]
tail[R]

Public Class Methods

new(left, right) click to toggle source

Public: Create a Cons cell.

left - Any Object to be the left element of the cell. right - Any Object to be the right element of the cell.

# File lib/funtools/cons.rb, line 37
def initialize(left, right)
  @car = left
  @cdr = right
end

Public Instance Methods

==(other) click to toggle source

Public: Determine whether two Cons cells/lists are equivalent.

other - Object to be compared against.

Returns true or false.

# File lib/funtools/cons.rb, line 72
def ==(other)
  return false unless other.is_a?(Cons)
  to_a == other.to_a
end
each(&block) click to toggle source

Public: Iterate through each element of a Cons cell/list. Note that Cons cells will be yielded without inspecting their contents if they are in the left position of a parent Cons cell.

Yields each element.

# File lib/funtools/cons.rb, line 47
def each(&block)
  block.(car)
  left, right = car, cdr

  while right
    if right.is_a?(Cons)
      if left.is_a?(Cons)
        block.(right)
        right = nil
      else
        block.(right.car)
        left, right = right.car, right.cdr
      end
    else
      block.(right) unless right.nil?
      right = nil
    end
  end
end
inspect() click to toggle source

Public: Produce a string representation of a Cons cell/list.

Returns a String.

# File lib/funtools/cons.rb, line 80
def inspect
  result = [self]
  while result.grep(Cons).any?
    result = result.map do |e|
      e.is_a?(Cons) ? ['(', e.to_a.zip([' '].cycle).flatten[0..-2], ')'] :
      e.nil? ? 'nil' : e
    end.flatten
  end
  result.map(&:to_s).join
end
Also aliased as: to_s
to_s()
Alias for: inspect