Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I cannot seem to figure out a way to do Scheme's cons boxes in Ruby (it seems its pretty much all arrays). This is a pretty rough outline:

class cons
    def initialize (car, cdr)
    @car = car
    @cdr = cdr
    end

    #return the car of the pair
    def car
        return @car
    end

    #return the cdr of the pair
    def cdr
        return @cdr
    end
end

I can pass two values and call the car and cdr, but this is not a list of any sort (just two values). How do I make a list on which I can insert something as in Scheme cons:

myCons = (cons(1, cons(2, cons(3, cons(4, 5)))))

The closest I can find is making my own array like myArray = Array[1, 2, 3, 4, 5] and then using puts myArray.join(' '). This only gives me "1 2 3 4 5" and not (1 2 3 4 5) though, and that's not taking into account I still can't actually build the array with cons, I simply made it myself.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
251 views
Welcome To Ask or Share your Answers For Others

1 Answer

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]]]]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...