smalltalkpharopharo-5

How do we check in pharo if an element already exist in a set


Say I have a function that continually add a random number to a collection after each refresh.

Myfunction
|list length data |

z := Set new.
x := 8.
data:= received data after each refresh.
length := data size.
1 to: length do:[:k | list := data at: k.
    list < x
    "How to check if this data already exist and not add"
        ifTrue:[z add: list]

How can I check in Pharo if a number already exists and if so it should not add it again?


Solution

  • Sets and other basic collections are part of common Smalltalk. You should have a look at the Smalltalk documentation (e.g., the Smalltalk bluebook), particularly the references for each of the data types you are attempting to use as well as other related ones.

    If you read the documentation for Set you'll find a message #includes: which will return true if the argument is in the set, and return false if it isn't. That would look like:

    (z includes: list) ifTrue: [ z add: list ]
    

    But, a Set by definition contains unique elements. Therefore, if you attempt to add an element that's already in the set, Smalltalk will not add it again and not give you an error if you attempt to do so. So you don't need to check to see if the set already includes list. You can just add it.

    Then you are doing your data traversal the long, hard way. You don't need to get the length then loop on an index from 1 to that length. I assume your data is some kind of Smalltalk Collection, so you can just use the #do: message. The #do: message allows you to iterate a block over each element of the collection:

    data do: [ :each | each < x ifTrue: [ z add: each ] ]
    

    This replaces everything you have shown starting at length := ....