(no subject)
Bert Freudenberg
bert at impara.de
Sun Apr 9 21:31:03 UTC 2006
Am 07.04.2006 um 22:03 schrieb Andrew P. Black:
> Does anyone else feel that
>
> x ifNotNilDo: [: each | Transcript show: each; space]. (1)
>
> and
>
> x ifNotNil: [ x do: [: each | Transcript show: each; space]]. (2)
>
> ought to do the same thing?
>
> Or perhaps nil should respond to do: (and do nothing?)
>
> The rationale is to be able to use instance variables initialized
> to nil as empty collections, without having to repeatedly test if
> they are nil before telling them to do: something, as in phrase (2)
> above. One might be forgiven for thinking that ifNotNilDo: would
> have the same effect as do: on a non-nil object.
>
> I realize that it is probably infeasible to make a change like
> this, but I couldn't resist thinking about it.
Agreed, it would more aptly named ifNotNilIn:, as it is equivalent to
"x ifNotNil: [x in: aBlock]".
Your problem reminds me of a pattern I've used before, not sure of
its "official" name. It optimizes collections of 0 and 1 elements:
x := nil. "empty list"
x myDo: [:each | ...]. "not evaluated"
x := x myAdd: 42. "x = 42"
x myDo: [:each | ...]. "evaluated once"
x := x myAdd: 'hi'. "x = #(42 'hi')"
x myDo: [:each | ...]. "evaluated twice"
- Bert -
More information about the Squeak-dev
mailing list
|