[Squeak] been dazed by SortedCollection
Bob Arning
arning at charm.net
Sun Aug 30 05:15:24 UTC 1998
On Sun, 30 Aug 1998 13:28:27 +0900 Satoshi NISHIHARA <nishis at urban.ne.jp> wrote:
>I've been dazed and confused ((C)Led Zeppelin) by SortedCollection.
>
> | collection |
> collection := SortedCollection new.
> collection sortBlock: [:element1 :element2 | element1 > element2].
> 1 to: 10 do: [:i | collection add: i].
> Transcript cr; show: (collection copyFrom: 1 to: 5) printString
>
>Got SortedCollection (6 7 8 9 10 ), although expected SortedCollection
>(10 9 8 7 6 ).
>I think that SortedCollection (6 7 8 9 10 ) has sortBlock: [:x :y | x <=
>y] (default) *not* [:x :y | x > y] (required). Is it right?
You are right about the new SortedCollection having the default sortBlock.
OrderedCollection>>copyFrom:to: creates the new collection with
self species new: endIndex + 1 - startIndex
This just gives you the same kind (with 2 exceptions) of collection you had before. It does NOT recognize what sortBlock the original had.
To get your code to work, you can:
1. Explicitly give the new collection a sortBlock as in
Transcript cr; show: ((collection copyFrom: 1 to: 5)
sortBlock: [:element1 :element2 | element1 > element2]) printString
2. Or, if you are not interested in the result actually being a SortedCollection,
Transcript cr; show: (collection asArray copyFrom: 1 to: 5) printString
3. Or you could reimplement #copyFrom:to: in SortedCollection to give the new collection the same sortBlock as the old one had:
copyFrom: startIndex to: endIndex
"Answer a copy of the receiver that contains elements from position
startIndex to endIndex, keeping the sortBlock from the receiver"
| targetCollection |
(targetCollection _ self species new: (endIndex + 1 - startIndex max: 0)) sortBlock: self sortBlock.
endIndex < startIndex ifTrue: [^targetCollection].
startIndex to: endIndex do: [:index | targetCollection add: (self at: index)].
^ targetCollection
Cheers,
Bob
More information about the Squeak-dev
mailing list
|