nikita-volkov / stm-containers

Containers for STM
http://hackage.haskell.org/package/stm-containers
MIT License
66 stars 13 forks source link

Insert into a set, returning the prior existence #23

Open rehno-lindeque opened 5 years ago

rehno-lindeque commented 5 years ago

Hi, I was taking a stab at a function that inserts an item into a set and returns whether it already existed prior to the operation.

-- The result is False if the item already exists in the set
insertIfMissing :: item -> Set item -> STM Bool

Obviously this can be done as a lookup followed by insert. However, I was wondering if it ought to be possible via focus?

E.g.

do
  let insertIfMissing :: a -> Focus a m Bool
       insertIfMissing element = do
         F.cases (True, F.Set element) (const (False, F.Leave))
  alreadyPresent <- focus insertIfMissing item set

focus expects Focus () STM result, which is explained in the docs:

The strategy is over a unit since we already know, which element we're focusing on and it doesn't make sense to replace it

Would it be fair to say that this use-case contradicts the rationale?

nikita-volkov commented 5 years ago

Seems like a perfectly valid use-case to me :)