[swift-evolution] [Review] SE-0187: Introduce Sequence.filterMap(_:)
Gwendal Roué
gwendal.roue at gmail.com
Mon Nov 13 02:12:49 CST 2017
> Le 13 nov. 2017 à 04:35, Brent Royal-Gordon via swift-evolution <swift-evolution at swift.org> a écrit :
>
>> On Nov 8, 2017, at 9:29 PM, Paul Cantrell via swift-evolution <swift-evolution at swift.org <mailto:swift-evolution at swift.org>> wrote:
>>
>> The problem in the Doodads example is that the name flatMap is used to identify two distinct intents: concatenating arrays and filtering nils. One can argue that those two operations are, in some lofty abstract sense, if you squint, two instances of some more general pattern — but I don’t think it’s fair to say that they represent the same intent. These separate intents deserve separate names.
>
> I think that's the crux of it.
>
> I think we might be better off renaming the maps on `Optional` and then naming the `Sequence` operation analogously. For instance:
>
> Optional.map(transform) => Optional.pass(to: transform)
> Optional.flatMap(transform) => Optional.chain(to: transform)
>
> Then this would be a natural choice:
>
> Sequence.flatMap(transform) => Sequence.chainMap(transform)
>
> Alternatively, we could think of a name for "removing optionality from a sequence" and then use that name. For example, borrowing a name from Ruby:
>
> (Sequence where Element == T?).compact()
> Sequence.compactMap(transform)
>
> Actually, "unwrapped" might be a better name than "compact", since we use that term.
`unwrap` is in the air, I agree. Before I suggested compactMap as well, above, I had a look at the RxSwift method name for filtering out nils from observable sequences. It is defined in RxSwiftExt, and named `unwrap`: https://github.com/RxSwiftCommunity/RxSwiftExt#unwrap <https://github.com/RxSwiftCommunity/RxSwiftExt#unwrap>
Yet I wouldn't follow that precedent. As Erica Sadun has told us, there is something interesting in "unwappable" types. It's a clear concept. Yet it applies to *values*, not *collections*: Optional.unwrapped, Result.unwrapped, but not Array.unwrapped. Optional<Array<Result>>.unwrapped().unwrapped() is a conceptual mess.
The functional vocabulary does not help us much, here. What about calling a spade a spade? "Filtering out nils" is not general enough to fit in the functional landscape, but it happens to be a concept that has is clear, useful, and stand-alone. "Compact" fits this precise niche very well.
Gwendal Roué
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20171113/d1cb211b/attachment.html>
More information about the swift-evolution
mailing list