> On Nov 15, 2017, at 4:36 PM, Greg Parker via swift-evolution 
> <[email protected]> wrote:
> 
> "compactMap" is okay if "compact" is added. Is "compact" a common enough 
> operation in practice to pull its own weight?

Lines containing code like `flatMap { $0 }`—which could be compacting optionals 
or flattening nested sequences—appear 89 times in the source compatibility 
suite. (I happen to have it on my hard drive right now.)

My main concern about adding a compacting method is…well, am I missing a better 
implementation than the slightly gross one I cooked up in a playground just now?

        protocol _OptionalProtocol {
            associatedtype _Wrapped
            var _optional: _Wrapped? { get }
        }
        
        extension Optional: _OptionalProtocol {
            var _optional: Wrapped? {
                return self
            }
        }
        
        extension Sequence where Element: _OptionalProtocol {
            func compacted() -> [Element._Wrapped] {
                return flatMap { $0._optional }
            }
        }
        
        let a = [1, nil, 2]
        a.compacted()           // [1, 2]


-- 
Brent Royal-Gordon
Architechies

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

Reply via email to