组合:atATimeDo:Pharo 5.0中的怪异行为

use*_*565 4 collections combinations smalltalk pharo

我想使用以下代码段在Pharo中生成组合:

| col |
col := Set new.
(0 to: 7) asArray
    combinations: 5
    atATimeDo: [ : combination | col add: combination  ].
^ col
Run Code Online (Sandbox Code Playgroud)

我不知道我做错了什么,但总是导致重复相同的集合:

 "a Set(#(7 7 7 7 7) #(7 7 7 7 7) #(7 7 7 7 7) #(7 7 7 7 7) #(7 7 7 7 7) #(7 7 7 7 7) #(7 7 7 7 7) #(7 7 7 7 7) #(7 7 7 7 7) #(7 7 7 7 7) #(7 7 7 7 7) #(7 7 7 7 7))"
Run Code Online (Sandbox Code Playgroud)

可能是什么问题呢?

Uko*_*Uko 5

我认为这是因为性能原因,但#combinations:atATimeDo:实现的方式是创建一个组合大小的单个数组,并用不同的元素填充它并将其传递给块.这样更有效,因为每次都不分配新数组.另一方面,在您的情况下发生的情况是,您实际上是一遍又一遍地将同一个对象添加到您的集合中,但同时它会发生变化,因此结果您拥有一个具有相同对象的集合,该集合具有最后的组合.您可以通过简单地存储copy数组来使代码工作:

| col |
col := Set new.
(0 to: 7) asArray
    combinations: 5
    atATimeDo: [ : combination | col add: combination copy  ].
^ col
Run Code Online (Sandbox Code Playgroud)