toggle : a -> Set a -> Set a
toggle x xs =
if Set.member x xs then
Set.remove x xs
else
Set.insert x xs
It is frequently useful to me and I’d expect it to be a part of the stdlib, not just *-extra packages. Is everybody else modelling stuff (eg. multi-select checkboxes/dropdowns) differently so that you don’t need that kind of function?
I have similar functions but always with a boolean to indicate if you should add or remove. E.g.
toggle : a -> Bool -> Set a -> Set a
For me the boolean is important to make the function idempotent. I always have my messages carry the desired state e.g. Toggle True, (never just Toggle). Unsure about the tradeoffs of these two approaches.
ah, interesting. In such cases I just use SetFoo and UnsetFoo messages (or AddFoo and RemoveFoo), which I guess is isomorphic to your ToggleFoo Bool message, but is two messages instead of one and the two update handlers use Set.insert and Set.remove respectively.
With multi-select I just make the message reflect the desired state, so if a checkbox should be set the message includes True and if it should not be set it includes False. This also makes the intent of the messages independent of the current state, which is a good thing in my opinion.
Yeah, I agree. I think it’s very rare for someone to actually want to toggle a value like that.
ie. “I don’t know/care what the current value of this is just make it the opposite of that”
It’s more common for toggle to be used when someone thinks they knows the state of the value and wants to implicitly set it to the other state.
This leads to all kinds of races and other bugs resulting from the assumption of the state being wrong and thus the toggle having the opposite of the desired effect.
multi-select checkboxes/dropdowns is a great example of the kind of thing where the event from the user has a specific intention that isn’t to toggle but to explicitly add/remove a selection, or enabled/disabled a checkbox.
I think actually wanting to toggle is rare enough that having it included in core would just encourage people to create these kinds of bugs.