Skip to content

Dict.update is confusing #1095

Open
Open
@gampleman

Description

@gampleman

Recently there was a discussion on Slack, where it turned out that even well seasoned Elm developers where confused about the semantics of Dict.update. Specifically, it is unclear what is supposed to happen when the provided function returns Nothing (i.e. should "nothing" happen - the value remains the same or does it cause the value to be removed?)

A secondary issue is that the code needed for one of the most common use cases - aggregation - is quite unwieldy:

-- for example to count by key is:
Dict.update
    key
    (Maybe.withDefault 0 >> (+) 1 >> Just)
    dict

I can see 2 possible solutions here:

  1. Improve the docs with a) specifying what happens when b) adding some practical examples to illustrate this.
  2. Change the API for a more Elixir like update : comparable -> v -> (v -> v) -> Dict comparable v -> Dict comparable v. This is less general, but arguably addresses one of the most common usecases much more explicitly:
Dict.update key 1 ((+) 1) dict

For situations where delete semantics are useful, it is not too hard to write explicit remove logic and it is probably easier to parse anyway:

toggle : comparable -> v -> Dict comparable v ->  Dict comparable v
toggle key val =
    Dict.update key (Maybe.andThen (always Nothing) >> Maybe.withDefault (Just val))

-- vs: --

toggle key val dict =
     case Dict.get key dict of
          Just v ->
                Dict.remove key dict
          Nothing ->
                Dict.insert key val

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions