在Ruby中添加Lisp-Style(+*args)的最简单方法是什么?

ova*_*g25 1 ruby lisp

所以我真的很喜欢Lisp中的这种语法:

 (+ 1 1 2 3 5 8 13)
 => 33
Run Code Online (Sandbox Code Playgroud)

我想在Ruby中添加一个项目列表,并希望尽可能地近似.现在,我最好的解决方案涉及一个数组和collect/map方法.

所以:

sum = 0; [1,1,2,3,5,8,13].collect { |n| sum += n }
Run Code Online (Sandbox Code Playgroud)

但...

我想为此添加可返回nil的方法.

sum = 0; [1, booking_fee, 8,13].collect { |n| n = 0 if n.nil?; sum += n }
Run Code Online (Sandbox Code Playgroud)

这样做真的很好,中间的所有行都引用可能返回nil的方法,但我不能以这种方式完全构建数组.这只是我希望我的语法看起来像什么的想法.

def total
  Array.new do
    booking_fee
    rental_charges
    internationalization_charges
    discounts
    wild_nights
  end.collect { |n| n = 0 if n.nil?; sum += n }
end
Run Code Online (Sandbox Code Playgroud)

在我试图破解并实现格林斯普规则之前的任何建议?(编程确实是一种强制性.

Jör*_*tag 10

我真的不明白你的问题.如果你想要一个像+Lisp中那样工作的方法,即获取任意数量的参数并且位于前缀位置而不是中缀,这是微不足道的:

def plus(*nums)
  nums.inject(:+)
end

plus 1, 1, 2, 3, 5, 8, 13 # => 33
Run Code Online (Sandbox Code Playgroud)

如果你想得到真正的幻想,你可以覆盖s 的一元前缀+运算符Array:

class Array
  def +@
    inject(:+)
  end
end

+[1, 1, 2, 3, 5, 8, 13] # => 33
Run Code Online (Sandbox Code Playgroud)

请不要那样做!

我不知道你的问题的其余部分是如何与Lisp风格的加法操作相关的.

如果你想从中删除nils Array,就Array#compact可以了.