[Proposal] mapValues


(Jon Hull) #1

I am definitely +1 for adding the initializer in any case.

I would like to see it (based on Nate’s suggestion) have a “merge" parameter which takes a closure of (Key, Value, Value)throws->Value, which would be called to choose a value whenever a repeated key is encountered. That parameter should have a default value which just traps. That way the default behavior is to trap when a key is repeated, but it can still be overridden with a more appropriate behavior for the situation (e.g. keeping the first value, keeping the last, averaging them, etc…)

That said, I would still also like to see the functionality of mapValues (whatever it ends up being called) in the standard library. It easily applies to 80-90% of my use cases, and allowing re-mapping of keys adds a lot of complexity which must be carefully considered (there is a lot more which can go wrong). As swift is a practical language, it would be nice to have a quick and foolproof way to do this common task.

Thanks,
Jon

···

on Tue Apr 12 2016, Jonathan Hull <swift-evolution at swift.org <https://lists.swift.org/mailman/listinfo/swift-evolution>> wrote:

> I would really like to see something like the following added to the standard
> library:
>
> extension Dictionary {
>
> func mapValues<U>(transform:(Key,Value)->U)->[Key:U] {
> var output:[Key:U] = [:]
> for (k,v) in self {
> output[k] = transform(k,v)
> }
> return output
> }
>
> }
>
> It comes up enough that I have had to add it to pretty much every one of my
> projects. I also don’t feel comfortable adding it to my frameworks, since I
> figure a lot of people are also adding something like this to their projects,
> and I don’t want to cause a conflict with their version. Prime candidate for the
> standard library.
>
> I like calling it ‘mapValues' as opposed to providing an override for map, since
> it makes the specific behavior more clear. I would expect ‘map' to possibly map
> the keys as well (though there are issues where the new keys overlap). I suppose
> you could just have a bunch of overrides for map if the compiler becomes good
> enough at differentiating return types: (Value)->(Value), (Key,Value)->Value,
> (Key, Value)->(Key,Value)

I agree that we need a way to do this, and was surprised when what I
tried didn't work. This should work:

  Dictionary(d.lazy.map { (k, v) in (k, transform(v)) })

We should have a proposal that makes the constructor work* if we don't
already have one.

I'm inclined against building specialized variants of basic algorithms
into particular collections, though. Could be talked out of it if the
use-case is strong enough.