Search code examples
collectionssmalltalkpharosqueak

unique or distinct for collections in squeak(Smalltalk)


there is a method like uniq in bash for collections in squeak?

to remove all duplications in the collection and get a collection with one of each distinct obj.

For example:

before: #('cat', 'cat', 'dog', 'cat')

after: (uniq) #('cat', 'dog')


Solution

  • There exist quite a few ways of doing the same in subtly different ways, depending on your needs. The more popular ones I can think of are:

    • aCollection asSet creates a new Set with all the elements of the collection, and sets by definition have only one instance of each element.

    • aCollection removeDuplicates removes the duplicates from the original collection itself. This only works if the collection is not of a fixed size (i.e. it doesn't work on arrays).