[英]What's the easiest way to get Lisp-Style addition (+ *args) in Ruby?
So I really like this syntax in Lisp: 所以我真的很喜欢Lisp中的这种语法:
(+ 1 1 2 3 5 8 13)
=> 33
I want to add a list of items in Ruby and would like to approximate this as best as possible. 我想在Ruby中添加项目列表,并希望尽可能地近似。 Right now, my best solution involves an array and the collect/map method.
现在,我最好的解决方案涉及数组和collect / map方法。
So: 所以:
sum = 0; [1,1,2,3,5,8,13].collect { |n| sum += n }
BUT... 但...
I would like to add methods to this which could return nil. 我想向此方法添加可能返回nil的方法。
sum = 0; [1, booking_fee, 8,13].collect { |n| n = 0 if n.nil?; sum += n }
And it would be really nice to do this, where all of the lines in the middle refer to methods that may return nil, but I can't exactly build an array in this manner. 这样做非常好,中间的所有行都引用了可能返回nil的方法,但是我无法以这种方式精确地构建数组。 This is just an idea of what I want my syntax to look like.
这只是我想要我的语法看起来的一个想法。
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
Any suggestions before I try to hack away and effectuate Greenspun's Rule? 在我尝试破解和执行格林斯潘法则之前有什么建议吗? (Programming is indeed a compulsion.
(编程确实是一种强迫。
I really don't understand your question. 我真的不明白你的问题。 If you want a method that works like
+
does in Lisp, ie takes an arbitrary number of arguments and is in prefix position rather than infix, that's trivial: 如果您想要一个像
+
在Lisp中一样工作的方法,即采用任意数量的参数,并且位于前缀位置而不是中缀,那很简单:
def plus(*nums)
nums.inject(:+)
end
plus 1, 1, 2, 3, 5, 8, 13 # => 33
If you want to get really fancy, you could override the unary prefix +
operator for Array
s: 如果您真的想花哨的话,可以覆盖
Array
的一元前缀+
运算符:
class Array
def +@
inject(:+)
end
end
+[1, 1, 2, 3, 5, 8, 13] # => 33
Please don't do that! 请不要那样做!
I don't see how the rest of your question is related in any way to a Lisp-style addition operation. 我看不到您其余的问题与Lisp风格的加法运算有什么关系。
If you want to remove nil
s from an Array
, there's Array#compact
for that. 如果要从
Array
删除nil
,则可以使用Array#compact
。
inject
for doing what you want. inject
可以执行您想要的操作。 nil
to a number without affecting a number is easy: use to_i
(or to_f
if you are dealing with float). nil
而不影响其人数很简单:使用to_i
(或to_f
如果你正在处理的浮动)。 . 。
[
booking_fee,
rental_charges,
internationalization_charges,
discounts,
wild_nights,
].inject(0){|sum, item| sum + item.to_i}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.