[swift-evolution] [Proposal] mapValues

Ross O'Brien narrativium+swift at gmail.com
Wed Apr 13 05:38:15 CDT 2016


+1 on mapValues.

DictionaryLiteral already throws an exception if it includes duplicate
keys, so I'd expect mapKeys to throw an error if multiple source keys
mapped to the same destination key.

On Wed, Apr 13, 2016 at 11:28 AM, Miguel Angel Quinones via swift-evolution
<swift-evolution at swift.org> wrote:

> I'm +1 for adding mapValues. Very useful functionality and trivial to
> implement.
>
> > > I.e. I suggest to implement and mapKeys() also. It could be also
> useful in some situations.
> > `mapKeys` is much more dangerous, because you could end up mapping many
> values into a single key. You kind of need to combine the values somehow.
> Perhaps:
> >
> > extension Dictionary {
> > func mapValues(_ valueTransform: @noescape Value throws ->OutValue)
> rethrows ->[Key: OutValue] { … }
> >
> > func mapKeys(_ keyTransform: @noescape Key throws ->OutKey) rethrows
> ->[OutKey: [Value]] { … }
> >
> > // Possibly flatMap variants, too?
> > }
> >
> > extension Dictionary where Value: Sequence {
> > func reduceValues(_ initial: OutValue, combine: @noescape (OutValue,
> Value.Iterator.Element) throws ->OutValue) rethrows ->[Key: OutValue] {
> > return mapValues { $0.reduce(initial, combine: combine) }
> > }
> > }
> >
> > Which you would end up using like this:
> >
> > let wordFrequencies: [String: Int] = …
> > let firstLetterFrequencies: [Character: Int] = wordFrequencies.mapKeys {
> $0.characters.first! }.reduceValues(0, combine: +)
> >
> > --
> > Brent Royal-Gordon
> > Architechies
> >
> >
> >
> >
>
> --
> Miguel Angel Quinones
>
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160413/3c51d3c0/attachment.html>


More information about the swift-evolution mailing list