[swift-users] Why can I not filter or map a dictionary to another dictionary?

Rick Mann rmann at latencyzero.com
Mon Oct 31 03:55:55 CDT 2016


> On Oct 27, 2016, at 10:29 , Dave Abrahams <dabrahams at apple.com> wrote:
> 
> 
> on Thu Oct 27 2016, Rick Mann <rmann-AT-latencyzero.com> wrote:
> 
>>> On Oct 26, 2016, at 22:23 , Dave Abrahams via swift-users <swift-users at swift.org> wrote:
>>> 
>>> 
>>> on Wed Oct 26 2016, Rick Mann <swift-users-AT-swift.org> wrote:
>>> 
>> 
>>>> It seems fairly natural to want to do this:
>>>> 
>>>> let bigDictionary = ...
>>>> let smallerDictionary = bigDictionary.filter { key, value in <some test returning Bool> }
>>> 
>>>> Similarly, it seems natural to want to map this way.
>>> 
>>> It's reasonable for filter, but maybe not for map.  Map follows certain
>>> laws, and one of them is that you get the same number of elements out as
>>> you put in.  But you can easily map all keys to the same key, and the
>>> law would be violated.
>> 
>> Sure map would produce a dictionary of the same number of entries. I
>> didn't mean to imply map would also filter. 
> 
> I think you're missing my point.  What result do you expect from
> 
>  {1:2, 3:4}.map { _ in (1, 1) }

Fair point. I suppose I'd be okay with unpredictable results, or an exception, if possible.

> 
> ? How many elements does it have?  Note that you can't have the same key
> twice in a Dictionary.
> 
>> But I'm basically transforming a JSON dictionary into a new version of
>> that dictionary with fewer elements. I'd like to first filter it, then
>> map it, and have the result be a dictionary.
> 
> What we need are Dictionary initializers that operate on Sequences, per
> https://github.com/apple/swift-evolution/blob/master/proposals/0100-add-sequence-based-init-and-merge-to-dictionary.md
> 
>    Dictionary(merging: d.lazy.filter {... }.map {...})
> 
> That would get you the result you're looking for in a principled way,
> without creating an intermediate Array.

I guess for now I write it in a clunky way.


-- 
Rick Mann
rmann at latencyzero.com




More information about the swift-users mailing list