Class: BusScheme::Cons

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

Direct Known Subclasses

Lambda

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Callable

#call_as

Constructor Details

#initialize(car, cdr) ⇒ Cons

TODO: figure out default values


6
7
8
# File 'lib/cons.rb', line 6

def initialize(car, cdr)
  @car, @cdr = [car, cdr]
end

Instance Attribute Details

#carObject Also known as: first

Returns the value of attribute car


3
4
5
# File 'lib/cons.rb', line 3

def car
  @car
end

#cdrObject Also known as: rest

Returns the value of attribute cdr


3
4
5
# File 'lib/cons.rb', line 3

def cdr
  @cdr
end

Instance Method Details

#==(other) ⇒ Object


10
11
12
13
# File 'lib/cons.rb', line 10

def ==(other)
  other.respond_to?(:car) and @car == other.car and
    other.respond_to?(:cdr) and @cdr == other.cdr
end

#call(nth) ⇒ Object

allows for (mylist 4) => (nth mylist 4)


71
72
73
# File 'lib/cons.rb', line 71

def call(nth)
  nth == 0 ? @car : @cdr.call(nth - 1)
end

#each {|@car| ... } ⇒ Object

Yields:


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

def each(&block)
  yield @car
  @cdr.each(&block) if @cdr && @cdr.respond_to?(:each)
end

#empty?Boolean

Returns:

  • (Boolean)

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

def empty?
  @car.nil? && @cdr.nil?
end

#inspect(open = '(', close = ')') ⇒ Object


55
56
57
58
59
60
61
62
63
64
# File 'lib/cons.rb', line 55

def inspect(open = '(', close = ')')
  str = open + @car.inspect
  if @cdr.nil?
    str + close
  elsif @cdr.is_a? Cons
    str + ' ' + @cdr.inspect('', '') + close
  else
    str + ' . ' + @cdr.inspect + close
  end
end

#lastObject


26
27
28
29
# File 'lib/cons.rb', line 26

def last
  # TODO: do this list-style
  self.to_a.last
end

#lengthObject Also known as: size


18
19
20
21
22
23
# File 'lib/cons.rb', line 18

def length
  return 0 if @car.nil? and @cdr.nil?
  return 1 if @cdr.nil?
  return 2 if !@cdr.respond_to? :length
  1 + @cdr.length
end

#map(mapper = nil, &block) ⇒ Object


31
32
33
34
# File 'lib/cons.rb', line 31

def map(mapper = nil, &block)
  mapper ||= block
  Cons.new(mapper.call(@car), @cdr ? @cdr.map(mapper) : @cdr)
end

#to_aObject


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

def to_a
  if @cdr.respond_to? :to_a
    [@car] + @cdr.to_a
  elsif !@cdr.nil?
    [@car, @cdr]
  else
    [@car]
  end
end

#to_listObject


66
67
68
# File 'lib/cons.rb', line 66

def to_list
  self
end