[swift-evolution] [Proposal] mapValues
Miguel Angel Quinones
miguel at miqu.me
Wed Apr 13 05:28:41 CDT 2016
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
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160413/8d9a461a/attachment.html>
More information about the swift-evolution
mailing list