#into的代码:与#Indject的代码相关:INTO:,但必须解决另一个问题。解释区别?
这有什么作用,并且有一种更简单的写作方法?
Collection>>into: a2block
| all pair |
all := ([:allIn :each| allIn key key: allIn value. each])
-> (pair := nil -> a2block).
pair key: all.
self inject: all
into: [:allIn :each| allIn value: (allIn key value: allIn value value: each). allIn].
^all value
What does this do, and is there a simpler way to write it?
Collection>>into: a2block
| all pair |
all := ([:allIn :each| allIn key key: allIn value. each])
-> (pair := nil -> a2block).
pair key: all.
self inject: all
into: [:allIn :each| allIn value: (allIn key value: allIn value value: each). allIn].
^all value
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您想找出答案,最好的方法是尝试一下,可能会逐步通过调试器。
例如,尝试:
您会看到一种减少形式。
因此,它就像
注入:in:
,但没有注入任何东西。a2block
将消耗前两个元素,然后将其结果和第三元素等。因此,我们必须将选择器名称为
注入:INTO:不注入:
:就像实现一样,它已经是命名事物的弯曲方法。这是在Squeak中作为
redy:
进行的,除了减少外,它将很明显作为选择器,除了将其发送到空的集合中,它会引起错误,相反,它会回答奇怪的递归人工制品。所有
工件包含一个要减少作为关键的块,而当前价值作为值。在第一步,它安排用a2block
和第一个元素替换要执行的块。但是用于实现替换的递归结构是……不必要的复杂。编写同一内容的方式少一些:
这或多或少是相同的原理:首先,块被还原块(A2Block)代替,并累积了第一个元素。
还原仅在第二次迭代开始。
替代方法是检查循环内的第一次迭代...一种做到这一点的方法:
还有许多其他方法可以清楚地使用布尔来测试第一次迭代...
If you want to find out, the best way is to try it, possibly step by step thru debugger.
For example, try:
You'll see a form of reduction.
So it's like
inject:into:
but without injecting anything.The
a2block
will consume first two elements, then result of this and 3rd element, etc...So we must understand the selector name as
inject:into: without inject:
: like the implementation, it's already a crooked way to name things.This is implemented in Squeak as
reduce:
, except that reduce: would be well too obvious as a selector, and except that it would raise an Error if sent to an empty collection, contrarily to this which will answer the strange recursive artifact.The
all
artifact contains a block to be executed for reduction as key, and current value of reduction as value. At first step, it arranges to replace the block to be executed witha2block
, and the first value by first element. But the recursive structure used to achieve the replacement is... un-necessarily complex.A bit less obfuscated way to write the same thing would be:
That's more or less the same principle: at first iteration, the block is replaced by the reduction block (a2block), and first element is accumulated.
The reduction only begins at 2nd iteration.
The alternative is to check for first iteration inside the loop... One way to do it:
There are many other ways to write it, more explicitely using a boolean to test for first iteration...