[swift-evolution] [draft] Introduce Sequence.filteredMap(_:)

Xiaodi Wu xiaodi.wu at gmail.com
Mon Oct 23 18:17:27 CDT 2017


On Mon, Oct 23, 2017 at 6:11 PM, Braden Scothern <bradenscothern at gmail.com>
wrote:

> The reason `flatMap(_:)` has its name is for code like this:
>
> ```
>     let nestedArray = [[1, 2, 3], [4, 5, 6]]
>     let flatArray = nestedArray.flatMap {
>         $0
>     }
>
>     print(flatArray) // prints [1, 2, 3, 4, 5, 6]
>
>     let anotherNestedArrays = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
>     let anotherFlatArray = anotherNestedArray.flatMap {
>         $0
>     }
>
>     print(anotherFlatArray) // prints [[1, 2], [3, 4], [5, 6], [7, 8]]
> ```
>
> Do your examples from other languages have this behavior of flattening
> nested sequences by 1 layer? Do you think it makes sense to have this
> effect as part of your proposed rename?
>
> I feel like the name `filteredMap(_:)` implies that the result should keep
> the same structure as the original Sequence type which doesn't allow for
> the flattening.
>
> If these 2 pieces of functionality weren't already a part of one function
> or if you proposal had a good solution to address this other part
> functionality, I would be accepting of a name change. I haven't ever been a
> fan of flatMap(_:) having 2 jobs, but it has been this way since Swift 1 or
> 2.
>

`flatMap` is not going away or being renamed. One particular overload is
being renamed so that the other overloads work as expected.


> Also, I don't think the name `filterMap` makes sense with Swift naming
> conventions. To me it implies that you are going to map in place vs the
> filtered makes it clear you are creating a new Array to return. I really
> like the sort() vs sorted() naming convention that is already the standard
> for Swift code and would rather any name changes stick to that.
>

`map`, `filter` and `flatMap` are settled exceptions to the Swift naming
conventions because they are terms of art, and that's not changing going
forward.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20171023/05445499/attachment.html>


More information about the swift-evolution mailing list