json icon indicating copy to clipboard operation
json copied to clipboard

Encode.dict & Decode.dict are asymmetrical

Open ghost opened this issue 4 years ago • 1 comments

Hello!

I'm working with dictionaries of character-based keys. Encoding them is straight-forward, as I simply have to convert keys from characters to strings. No problem!

Writing the decoder for this kind of dictionary was more problematic, as I don't have the option convert keys back into characters.

Encode.dict : (k -> String) -> (v -> Encode.Value) -> Dict k v -> Encode.Value

Decode.dict : Decoder a -> Decoder (Dict String a)

I am working around this, but I'd love for the solution to be incorporated into Decode.dict, to avoid the additional passes through the data.

Proposed solution

I'd really like these functions to be symmetrical, in the sense that the dictionary-decoder takes a function to convert the string-key into a comparable value in the same way the encoder requires me to convert the comparable keys into strings.

Perhaps like this:

Decode.dict : (String -> comparable) -> Decoder a -> Decoder (Dict comparable a)

To spare you the time, I could do this implementation for you, but let me know what you think when you have the time :sunny:

ghost avatar Sep 06 '19 10:09 ghost

I'm working with a dictionary with Int keys, and thus endorse this feature request.

The solution seems to be already implemented in Decode.Extra.dict2 from the elm-community/json-extra package.

Maybe it would make sense to have the Decode.Extra.dict2 implementation under the name Decode.dict, since it is more symmetrical to Encode.dict?

davidpomerenke avatar Jun 21 '20 10:06 davidpomerenke