[swift-evolution] [Review] SE-0187: Introduce Sequence.filterMap(_:)

Tino Heth 2th at gmx.de
Wed Nov 15 09:39:46 CST 2017


Looks like I finally have to draw on drawings... (hope the pictures aren’t considered inappropriate content ;-)

But after all, it might be the best way to convey my point anyways: I’m not thinking in terms of type names (why should it only be possible to flatten a „Sequence“? Many people associate this operation with lists, which aren’t common in Swift at all) or implementation details (neither Optional nor Sequence actually has a flatten-method).
Instead, I tend to look at the easiest way to explain how to get from input to output, so here is what I have in my mind when I speak about Sequence-Sequence flatmap:


https://imgur.com/hy4rel1

There is a transform, which turns an input value (red circle) into a collection (blue basket) of output values (green squares).
map takes an array of those input values, and stores each result-collection in an array (light blue).
flatten takes that container, unwraps each sub-collection, and stores its contents together with the other elements.
Note that empty collections aren’t skipped or removed — they just have nothing that they could contribute to the final result, so no trace of them is left.
flatMap just is flatten performed on the output of map.

Now, Optionals… I could simply say „think of those as an array with a maximal size of one“ — but because there’s really no fundamental difference, I just copied the sequence-illustration, and changed one tiny bit: The transformation doesn’t return multiple items now, so that the blue basket can act as representation for an Optional.



https://imgur.com/qq95b31

So conceptionally, both overrides are equivalent: The transformation always produces something — an Optional, and that can contain a value, or it can be empty, just like an array.
You also see that the flatten step really does what it says: It removes one layer of objects, and leaves a flush surface without gaps.

So, that should really be my last word in this discussion — I won’t add an animation or start singing about Optionals ;-)

- Tino

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20171115/41bc454a/attachment.html>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: PastedGraphic-2.png
Type: image/png
Size: 19246 bytes
Desc: not available
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20171115/41bc454a/attachment.png>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: PastedGraphic-4.png
Type: image/png
Size: 15916 bytes
Desc: not available
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20171115/41bc454a/attachment-0001.png>


More information about the swift-evolution mailing list