Question: Why is `toggle` function not a standard part of Set packages API?

What the title says.

I mainly have this in mind:

toggle : a -> Set a -> Set a
toggle x xs =
    if Set.member x xs then
        Set.remove x xs

        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’ve installed set-extra sometimes in order to have this function. I could see it being a part of elm/core.

Agreed - I think every time I have used a Set in Elm I have defined this exact 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.


Hi Sebastian,

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.

1 Like

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.

1 Like

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.


On the other hand, setting the value directly, rather than using something like toggle is susceptible to the stale update bug.

I’ve thought a lot about how to avoid both of these classes of bugs, and have never come up with a good solution.


This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.