[swift-evolution] [Accepted and Focused Re-review] SE-0187: Introduce Sequence.filterMap(_:)
BJ Homer
bjhomer at gmail.com
Wed Nov 15 16:31:11 CST 2017
> On Nov 15, 2017, at 3:05 PM, Tino Heth via swift-evolution <swift-evolution at swift.org> wrote:
>
> Odd… exactly that is the reason why I think filterMap is the worst choice:
>
> Both are established terms of art, but one has a meaning that doesn’t fit to the operation.
> Applying filter can remove elements, but it can never change types (I feel kind of silly to repeat this over and over, but so far, nobody took the time to falsify this).
The concern about filter changing types is only relevant if you think of the filter applying to the result of the map, instead of being a part of the filterMap operation itself (an operation that is distinct from map).
Let’s imagine that we had this instead:
enum SelectiveMapResult<T> {
case use(T)
case ignore
}
extension Sequence {
func selectiveMap<T>(_ selectiveTransform: (Element)->SelectiveMapResult<T>) -> [T]
}
let actualNumbers =
["1", "2", "apple", "banana", "5"].selectiveMap({ (x)->SelectiveMapResult<Int> in
if let value = Int(x) { return .use(value) }
else { return .ignore }
})
actualNumbers == [1, 2, 5]
The “selective” part of this operation doesn’t feel like it’s changing the type of the result, because SelectiveMapResult is easily understood to not be part of the mapping transformation; it just exists to tell us whether we should use the result of that particular transformation. Likewise, I don’t feel like the optional in filterMap is part of the mapping operation; it’s just serving the same role as SelectiveMapResult. (It should be obvious that SelectiveMapResult is just Optional with another name here.)
The name filterMap focuses on removing the ignored values, as does compactMap. The name selectiveMap focuses on retaining the non-ignored values. I’m not sure whether focusing on the positive or negative aspects is clearer here. I don’t particularly like the name compactMap, simply because I don’t have a lot of experience with languages that use “compact” to mean “drop the nil values”, and without that experience it doesn’t seem intuitive. I think filterMap is better. But if we introduced Sequence.compact() alongside .compactMap(), I’d probably get used to it.
-BJ
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20171115/182e9c66/attachment.html>
More information about the swift-evolution
mailing list