为什么在这里使用 lambda 而不是两个预定义的方法?
def divideset(rows, column, value)
split_function = nil
if value.is_a?(Fixnum) || value.is_a?(Float)
split_function = lambda{|row| row[column] >= value}
else
split_function = lambda{|row| row[column] == value}
end
set1 = rows.select{|row| split_function.call(row)}
set2 = rows.reject{|row| split_function.call(row)}
[set1, set2]
end
在 treepredict 的这段代码中,为什么要使用 lambda?
看来,作者可以不调用 split_function.call(row),而是预定义两种不同的方法来处理 if/else 语句的两个条件 - 一种用于处理 row 的情况[column] >= value 和另一个用于 row[column] == value
的情况
使用 lambda 是否还有其他优势?
def divideset(rows, column, value)
split_function = nil
if value.is_a?(Fixnum) || value.is_a?(Float)
split_function = lambda{|row| row[column] >= value}
else
split_function = lambda{|row| row[column] == value}
end
set1 = rows.select{|row| split_function.call(row)}
set2 = rows.reject{|row| split_function.call(row)}
[set1, set2]
end
In this code from treepredict, why use lambdas?
It seems that instead of calling split_function.call(row)
, the author could have predefined two different methods to handle the two conditions of the if/else statement -- one for the case where row[column] >= value
and the other for the case where row[column] == value
Is there any additional advantage here from using the lambda?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在这种情况下,使用 lambda 没有额外的技术优势。
考虑一下你的建议:
哪个更清楚?就我个人而言,我更喜欢 lambda 版本,因为它更简洁。
There is no additional technical advantage to using the lambdas in this case.
Consider your suggestion:
Which is more clear? Personally, I prefer the lambda version as it's more succinct.
您可以预定义这两个函数然后使用它们。
但在这种情况下使用 lambda 就很清楚了,因为这些函数确实很简单,而且它们的范围仅限于
divideset
内。如果其他一些函数也需要使用某些功能,那么最好使用预定义函数来遵循 DRY 原则。You could predefine these 2 function and then use them.
But using lambda in this case is much clear as these are really trival functions and their scope is only limited within
divideset
. If some other functions would also use the some functionality , it is better to use predefined function to follow the DRY principle.只是插话,以备记录。
Just chiming in, for the record.
从某种意义上说,它只是风格,但一点点帮助
虽然在一种观点中这只是风格,但在另一种观点中,它确实显示了函数式语言以更少的人力完成相同数量的工作的能力。如果我们不关心冗长和笨拙,我们可以用 Java 编写所有内容...
以下是一些浮现在脑海中的相当小的“风格”变化:
也许我一直在玩 太多的代码高尔夫。
In a sense it's just style, but every little bit helps
Although in one view it's just style, in another it does show the capability of a functional language to get the same amount of work done with less peon labor. If we didn't care about verbosity and clunkiness we could just write everything in Java...
Here are some rather minor "style" variations that come to mind:
Perhaps I've been playing too much code-golf.