Class: BusScheme::Cons
Direct Known Subclasses
Instance Attribute Summary collapse
-
#car ⇒ Object
(also: #first)
Returns the value of attribute car.
-
#cdr ⇒ Object
(also: #rest)
Returns the value of attribute cdr.
Instance Method Summary collapse
- #==(other) ⇒ Object
-
#call(nth) ⇒ Object
allows for (mylist 4) => (nth mylist 4).
- #each {|@car| ... } ⇒ Object
- #empty? ⇒ Boolean
-
#initialize(car, cdr) ⇒ Cons
constructor
TODO: figure out default values.
- #inspect(open = '(', close = ')') ⇒ Object
- #last ⇒ Object
- #length ⇒ Object (also: #size)
- #map(mapper = nil, &block) ⇒ Object
- #to_a ⇒ Object
- #to_list ⇒ Object
Methods included from Callable
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
#car ⇒ Object Also known as: first
Returns the value of attribute car.
3 4 5 |
# File 'lib/cons.rb', line 3 def car @car end |
#cdr ⇒ Object 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
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
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 |
#last ⇒ Object
26 27 28 29 |
# File 'lib/cons.rb', line 26 def last # TODO: do this list-style self.to_a.last end |
#length ⇒ Object 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_a ⇒ Object
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_list ⇒ Object
66 67 68 |
# File 'lib/cons.rb', line 66 def to_list self end |