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

_______________________________________________
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution

Reply via email to