是否有汽车,cdr和缺点的ruby?

是否有ruby等效的lisp汽车,cdr和consfunction? 对于那些不熟悉lisp的人来说,这就是我想要的ruby:

[1,2,3].car => 1 [1,2,3].cdr => [2,3] [2,3].cons(1) => [1,2,3] 

(在口齿不清):

 (car '(1 2 3)) => 1 (cdr '(1 2 3)) => (2 3) (cons 1 '(2 3)) => (1 2 3) 

Ruby数组没有实现为单链接列表,因此它不具备汽车和cdr和东西的用处。

如果你真的想要,你可以做到

 [1,2,3][0] => 1 [1,2,3].first => 1 [1,2,3][1..-1] => [2,3] [1] + [2,3] => [1,2,3] 

这就是你如何在ruby中实现类似lisp的单链表:

 class Object def list? false end end class LispNilClass include Enumerable def each end def inspect "lnil" end def cons(car) Cell.new(car, self) end def list? true end end LispNil = LispNilClass.new class LispNilClass private :initialize end class Cell include Enumerable attr_accessor :car, :cdr def initialize(car, cdr) @car = car @cdr = cdr end def self.list(*elements) if elements.empty? LispNil else first, *rest = elements Cell.new(first, list(*rest)) end end def cons(new_car) Cell.new(new_car, self) end def list? cdr.list? end # Do not use this (or any Enumerable methods) on Cells that aren't lists def each yield car cdr.each {|e| yield e} end def inspect if list? "(#{ to_a.join(", ") })" else "(#{car} . #{cdr})" end end end list = Cell.list(1, 2, 3) #=> (1, 2, 3) list.list? #=> true list.car #=> 1 list.cdr #=> (2, 3) list.cdr.cdr.cdr #=> lnil list.cons(4) #=> (4, 1, 2, 3) notlist = Cell.new(1,2) #=> (1 . 2) notlist.list? #=> false notlist.car #=> 1 notlist.cdr #=> 2 notlist.cons(3) #=> (3 . (1 . 2)) 

半严肃的说,如果你想在Ruby中使用CONS,CAR和CDR,你可能会比这更糟糕

 def cons(x,y)
    return lambda {| m |  m.call(X,Y)}
结束

 def car(z)
   z.call(lambda {| p,q | p})
结束

 def cdr(z)
   z.call(lambda {| p,q | q})
结束

然后你可以定义你的列表程序,

 def间隔(低,高)
   if(低>高)
    返回零
  其他
    返回利弊(低,间隔(低+ 1,高))
  结束
结束

 def map(f,l)
   if(l == nil)
    返回零
  其他
    缺点(f.call(car(l)),map(f,cdr(l)))
  结束
结束

 def滤波器(p,l)
   if(l == nil)
    返回零
   elsif(p.call(car(l)))
    返回利弊(car(l),filter(p,cdr(l)))
  其他
    返回filter(p,cdr(l))
  结束
结束

 def reduce(f,f0,l)
   if(l == nil)
    返回f0
  其他
     return f.call(car(l),reduce(f,f0,cdr(l)))
  结束
结束

然后你可以得到1到10范围内奇数平方的总和:

减少(lambda {| x,y | x + y},
        0,
       filter(lambda {| x | x%2 == 1},
               map(lambda {| x | x * x},
                  间隔(1,10))))
 => 165
 >> [1,2,3].drop 1 => [2, 3] >> [1,2,3].first => 1 

当然,如你所知,这些与Lisp并不太接近。 真正的ruby等价物就像[1, [2, [3, nil]]] 。 你总是可以编写一个List类……或者在某处找到一个。

实用Ruby项目的第8章在Ruby中称为实现Lisp

我建议阅读Ruby API for Array 。 那里有许多方法和操作员可以完全满足您的需求。

http://www.ruby-doc.org/core/classes/Array.html

不,没有,但如果需要,很容易编写自己的。

    Interesting Posts