combinations:atATimeDo:Pharo 5.0 中的奇怪行为

combinations:atATimeDo: weird behavior in Pharo 5.0

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

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

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

 "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))"

可能是什么问题?

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

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