[squeak-dev] Re: Letting Set contain nils?

Igor Stasenko siguctua at gmail.com
Sat Aug 9 01:38:03 UTC 2008


2008/8/9 Eliot Miranda <eliot.miranda at gmail.com>:
>
>
> On Fri, Aug 8, 2008 at 5:37 PM, tim Rowledge <tim at rowledge.org> wrote:
>>
>> On 8-Aug-08, at 5:20 PM, Igor Stasenko wrote:
>>
>>> 2008/8/9 Craig Latta <craig at netjam.org>:
>>>>
>>>>   I'll ask the inevitable question... given that ability, what do you
>>>> really want to do? :)
>>>>
>>>
>>> Some practicle usage: pick an arbitrary array and tell the number of
>>> _unique_ objects it contains, including nils, of course.
>>
>>
>> For Sets that is trivial without any need whatsoever to alter anything. It
>> is theSet size + 1 since all Sets will have at least one nil. Unless of
>> course some evil person messes up the growing protocol for Sets.
>
> But it doesn't deal with the case where the array includes nil.  So one has
> to come up with something clumsy such as
>     (theArray select: [:obj| obj notNil]) asSet size + ((theArray includes:
> nil) ifTrue: [1] ifFalse: [0])
> which creates an extra collection for the select, requires an extra pass to
> find nil (n the case where it doesn't contain it) and is plain ugly
> or
>     [| forNil | forNil := 0. (theArray inject: Set new into: [:set :item|
> item == nil ifTrue: [hasNil := 1] ifFalse: [set add: item]. set]) + forNil]
> which is faster but even more verbose and confusing.

My, maybe more verbose sample, but most efficient one, i guess :) :

daSet := Set new.
daObject := Object new.
daArray do: [:item | item ifNil: [ daSet add: daObject ] ifNotNil: [
daSet add: item] ].
^ daSet size

A use case example from the parrallel domain - databases:

SELECT DISTINCT field FROM someTable WHERE blabla
- returns a set of disctinct field values (including NULL values).

But while we can deal more or less painless with calculating a number
of distinct values,
operating with distinct values causing a lot more problem:
suggest you want to pass a set of distinct values somewhere else:
Now since you want to keep notion that nil present or not as distinct
value - you have to use additional argument, or convert a set to
OrderedCollection and add nil.
Nedless to say, its very inconvenient.

> Compare this to
>
>     theArray asSet size
> I'm with Igor.  This would indeed be an improvement.
> Just because "its always been this way" doesn't mean its right.
>>
>> tim
>> --
>> tim Rowledge; tim at rowledge.org; http://www.rowledge.org/tim
>> Variables won't; constants aren't.
>>



-- 
Best regards,
Igor Stasenko AKA sig.



More information about the Squeak-dev mailing list