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

Vladimir.S svabox at gmail.com
Thu Nov 9 13:42:48 CST 2017


On 09.11.2017 19:41, BJ Homer via swift-evolution wrote:
> 
> 
>> On Nov 9, 2017, at 9:37 AM, Sam Warner via swift-evolution <swift-evolution at swift.org> wrote:
>>
>> I accept the motivation for this change, although I would mention that:
>> - in 2.5 years on a ~200k lines of Swift project
>> - we've seen a plenty of instances of `flatMap` used where `map` would have been sufficient, but
>> - we've never burned time on tracking down the sort of compiler issue described by the author in the Motivation. As I say, the argument is fair, but I am questioning how frequently this problem occurs.
>>
>> I can't speak to the previous attempts to solve this problem, but I'd add my voice to anyone advocating solving this by having a compiler warning when `flatMap` is used redundantly(?).
>>
>> If this proposal were to be accepted, I'd also question the choice of `filterMap` as a name. This name is presumably shorthand for `filterNonesAndMap`, which conveniently ignores the following:
>> - `flatMap` may be used on a sequence-of-sequences to flatten our to a single-dimensional sequence.
>> - `flatMap` may be used on other 'box' types, e.g. on an optional: `Optional<String>("foo").flatMap { .some($0 + "bar") }` or on the common `Result` type.
>>
>> Any re-naming of one `flatMap` should take these other uses into account, as they share conceptual details.
>>
>> Thanks,
>>
>> Sam
> 
> This proposal only proposes renaming the “filterNonesAndMap” variant (though that name is misleading, it would be “filterNonesAfterMapping” if anything); the other uses of flatMap will remain unchanged.

I wonder, if it's also about unwrapping optionals (not just about filtering nils out; so correct name seems like 
mapOptionalsThenSkipNilsAndUnwrap), why not unwrapMap, optionalMap or maybe flatOptionalMap or even flatUnwrapMap, or 
mapUnwrapped? Such name IMO will be more clear about what is the purpose, because personally for me 'filterMap' is very 
general name, something about filtering and map, nothing about optional/unwrapping/nils. I even think 'flatMap' has a 
better mental model(we have optionals .some and nils in array, and will have an array of unwrapped(flat) values without 
nils).

For comparision:

let a : [Int?] = [1,2,3,nil,4,nil,5]

let b = a.flatMap { $0.flatMap{$0*10} }  // current

let b = a.filterMap { $0.filterMap {$0*10} }  // suggested

let b = a.unwrapMap { $0.unwrapMap {$0*10} }  // alternative

let b = a.optionalMap { $0.optionalMap {$0*10} }  // alternative

print(b) // [10, 20, 30, 40, 50]



Vladimir.

> 
> -BJ
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
> 


More information about the swift-evolution mailing list