You can declare a method (to_a
) which will build your array:
class Cons
def initialize(car, cdr)
@car = car
@cdr = cdr
end
attr_reader :car, :cdr
def to_a
list = cdr.respond_to?(:to_a) ? cdr.to_a : cdr
[car, *list]
end
end
myCons = Cons.new(1, Cons.new(2, Cons.new(3, Cons.new(4,5))))
myCons.to_a
# => [1, 2, 3, 4, 5]
This method checks if cdr
supports to_a
itself, and calls it if possible, then it adds car
to the beginning of the list, and returns the created list.
If you want to have a syntax similar to cons(1, cons(2,...)
you can do it using []
:
class Cons
def self.[](car, cdr)
Cons.new(car, cdr)
end
end
Now you can write:
myCons = Cons[1, Cons[2, Cons[3, Cons[4,5]]]]
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…