[swift-evolution] [draft] Introduce Sequence.filteredMap(_:)
retired.hunter.djura at gmail.com
Tue Oct 24 07:24:34 CDT 2017
"Flattening" in the context of functional programming (and that's where map and flatMap come from) means something like this:
F<F<T>> -> F<T>
So for example:
Array<Array<T>> -> Array<T>
Optional<Optional<T>> -> Optional<T>
Array<Optional<T>> -> Array<T>
It's simply the wrong word for the operation.
If "Map" is something like this:
(F<T> + (T -> U)) -> F<U>
then "FlatMap" means "map to the same functor, then flatten", thus:
(F<A> + (A -> F<B>)) -> F<F<B>>
(F<F<B>> -> F<B>)
In this case "U == F<B>"
In fact, there's (rightfully) a FlatMap method on Optional in cases in which the mapping function produces another Optional (notice that the chained unwrapping with "?." is a FlatMap operation).
Calling FlatMap something that is not (in the literature and community at large) was not a good idea, in my opinion.
> Il giorno 24 ott 2017, alle ore 14:10, Tino <2th at gmx.de> ha scritto:
>> Calling "flatMap" a map + filtering out the nil values was a TERRIBLE idea.
> maybe I’m the one who’s getting this all wrong, but afaik the purpose of flatMap isn’t filtering out nil at all, but just a combination of map & flatten…
> Optional<T> is like Array<T> with a maximal capacity of one (so it can either contain a single object, or it’s empty), and in this interpretation, there’s nothing wrong with the behavior.
> Instead, I think Nobuo Saito is right, and that a renaming to filteredMap is only fighting symptoms, and not the cause (but I’m not that sure if there’s a good way to tackle the cause).
> Besides that, all those alternative names also have potential for confusion:
> Imho it isn’t intuitive what is filtered out — and don’t forget that the result of flatMap can contain nil elements…
> If the biggest problem of flatMap is that people who don’t understand it write code that isn’t optimal (but still does the right thing!), I don’t think there is any change needed. I’m not even sure that that wrapping/unwrapping is actually done, because it should be discoverable by the compiler.
> It would be nice if there was an way to warn in places where flatMap could be replaced with map, though (but imho this special warning shouldn’t be checked by the compiler).
> - Tino
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the swift-evolution