是否有红宝石等同于汽车,CDR和缺点?(Are there ruby equivalents to

2019-08-17 07:28发布

是否有红宝石等同于LISP车,CDR和缺点的功能呢? 对于那些不熟悉口齿不清,这是我从红宝石想:

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

(在LISP):

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

Answer 1:

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]


Answer 2:

这就是你的红宝石实现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))


Answer 3:

半严重的是,如果你想缺点,CAR和CDR在Ruby中,你可以做有过之而无不及

def cons(x,y)
   return lambda {|m| m.call(x,y)}
end

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

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

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

def interval(low, high)
  if (low > high)
    return nil
  else
    return cons(low, interval(low + 1, high))
  end
end

def map(f, l)
  if (l == nil)
    return nil
  else
    cons(f.call(car(l)), map(f, cdr(l)))
  end
end

def filter(p, l)
  if (l == nil)
    return nil
  elsif (p.call(car(l)))
    return cons(car(l), filter(p, cdr(l)))
  else
    return filter(p, cdr(l))
  end
end

def reduce(f, f0, l)
  if (l == nil)
    return f0
  else
    return f.call(car(l), reduce(f, f0, cdr(l)))
  end
end

然后你可能会得到范围为1奇广场到10的总和:

reduce(lambda {|x, y| x + y},
       0,
       filter(lambda {|x| x % 2 == 1},
              map(lambda {|x| x * x},
                  interval(1, 10))))
=> 165


Answer 4:

>> [1,2,3].drop 1
=> [2, 3]
>> [1,2,3].first
=> 1

当然,如你所知,这些都不是太接近Lisp的。 真正的红宝石等效会是这样的[1, [2, [3, nil]]] 你总是可以写一个List类...或找一个地方。

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



Answer 5:

我建议你阅读为Ruby API Array 。 有许多方法和运营商,有可以做的正是你所需要的。

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



文章来源: Are there ruby equivalents to car, cdr, and cons?
标签: ruby lisp