A beautiful idiom.

Previous Topic Next Topic
 
classic Classic list List threaded Threaded
3 messages Options
Reply | Threaded
Open this post in threaded view
|

A beautiful idiom.

Squeak - Dev mailing list
Hi all,

Just a programmer shout out for a truly remarkable bit of code in
Collection.

As a middling smalltalker, when confronted with a tough problem I
regrettably tend toward the Algol/Procedural mode of thought of "iterating
and comparing"*.

The specific problem was to remove Identity duplicates from an
OrderedCollection.
I asked for help on Squeak-Begginers and thanks to Christoph,

Behold!

*withoutDuplicates
        "Answer a copy of the receiver that preserves order but eliminates
any
duplicates."
        | seen |
        seen := Set new: self size.
        ^self select: [:each| seen ifAbsentAdd: each]*

For an Algol-head, this is truly a remarkable bit of code!

The tentative  way to think about this, is "Use the essence of a thing as a
method"; or in this particular example, use the essence of what a Set is as
a mask on a Collection.

This is a beautiful idiom.

In the theatrical sense, if duplicate entries in the Collection are Balrogs,
the Set is Gandalf; none! shall pass!

Thanks all for your work, it is truly an remarkable language.



*"Collection reject collect detect  reject aspect  suspect deject
bleeaaahect wtfect dude-ect  "
vs.
Collection withoutDuplicates.













--
Sent from: http://forum.world.st/Squeak-Dev-f45488.html

Reply | Threaded
Open this post in threaded view
|

Re: A beautiful idiom.

Stéphane Rollandin
This one is faster though (it uses the fact that the elements are
already ordered):

        | nc |
        nc := self species new: self size.
        self ifEmpty: [^ nc].
        nc add: self first.
        self do: [:ea | nc last = ea ifFalse: [nc add: ea]].
        ^ nc

Stef


Reply | Threaded
Open this post in threaded view
|

Re: A beautiful idiom.

Stéphane Rollandin
> This one is faster though (it uses the fact that the elements are
> already ordered):
>
> | nc |
> nc := self species new: self size.
> self ifEmpty: [^ nc].
> nc add: self first.
> self do: [:ea | nc last = ea ifFalse: [nc add: ea]].
> ^ nc
>
> Stef

Hmm... sorry for the noise. I confused "ordered" and "sorted"...

Stef