Class: Cons

Inherits:
Object show all
Includes:
Enumerable
Defined in:
lib/funtools/cons.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(left, right) ⇒ Cons

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.



37
38
39
40
# File 'lib/funtools/cons.rb', line 37

def initialize(left, right)
  @car = left
  @cdr = right
end

Instance Attribute Details

#carObject (readonly) Also known as: head

Returns the value of attribute car.



28
29
30
# File 'lib/funtools/cons.rb', line 28

def car
  @car
end

#cdrObject (readonly) Also known as: tail

Returns the value of attribute cdr.



28
29
30
# File 'lib/funtools/cons.rb', line 28

def cdr
  @cdr
end

Instance Method Details

#==(other) ⇒ Object

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

other - Object to be compared against.

Returns true or false.



72
73
74
75
# File 'lib/funtools/cons.rb', line 72

def ==(other)
  return false unless other.is_a?(Cons)
  to_a == other.to_a
end

#each(&block) ⇒ Object

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.



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# 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

#inspectObject Also known as: to_s

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

Returns a String.



80
81
82
83
84
85
86
87
88
89
# 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