> On Nov 10, 2017, at 4:07 AM, Tino Heth <[email protected]> wrote:
> 
> 
>> The “think of optionals as collections” explanation is a good way to help 
>> people who are confused by the overload. But an even better way would be to 
>> not have a confusing overload in the first place.
> With the renaming, confusion might strike less often, but with bigger impact 
> (free translation of a real discussion):
> A: Cool, filterMap makes much more sense than flatMap!
> Me: Why do you thing so?
> A: Well, it does a mapping, and then applies a filter to get rid of nils, and 
> that's super useful!
> Me: I see. So you can be sure that when you apply the filterMap method, the 
> result doesn’t contain any nil values?
> A: Don’t you understand the concept of a filter? Of course, that’s what I 
> just said, you never have to worry about nil!
> 
> [me shows a very simple proof that this is completely wrong]
> 
> Even here on the mailing lists, people seem to have a wrong understanding of 
> what flatMap actually does, and this is reinforced with the renaming.
> It might have no considerable effect on real-world code, because even with 
> false assumptions, correct results are possible — but I really would prefer 
> to leave the name filterMap free for something like this:
> 
> extension Collection {
>       func filterMap<T>(transform: (Element) -> T, include: (T) -> Bool) -> 
> [T] {
>               return self.map(transform).filter(include)
>       }
> }
> 

If you insist upon a literal translation of the name into code, then here:

extension Sequence {
    func filterMap<T>(_ transform: (Element)->T?) -> [T] {
        return self.filter { transform($0) != nil }.map { transform($0)! }
    }
}

The implementor is then able to optimize that implementation however they 
prefer.


_______________________________________________
swift-evolution mailing list
[email protected]
https://lists.swift.org/mailman/listinfo/swift-evolution

Reply via email to