Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
262 views
in Technique[技术] by (71.8m points)

ruby - Cons box implementation

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

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...