[swift-evolution] Lazy flatMap for Optionals

Dmitri Gribenko gribozavr at gmail.com
Sun Dec 6 19:04:57 CST 2015


On Sun, Dec 6, 2015 at 8:06 AM, Donnacha Oisín Kidney
<oisin.kidney at gmail.com> wrote:
> (forgot to cc the mailing list)
>
> You can define it in terms of a map-filter-map chain, like this:
>
> extension LazySequenceType {
>
>   @warn_unused_result
>   public func flatMap<T>(transform: Elements.Generator.Element -> T?)
>     -> LazyMapSequence<LazyFilterSequence<LazyMapSequence<Elements, T?>>, T>
> {
>       return self
>         .map(transform)
>         .filter { opt in opt != nil }
>         .map { notNil in notNil! }
>   }
> }
>
> The version for LazyCollectionType can be done similarly:
>
> extension LazyCollectionType {
>
>   @warn_unused_result
>   public func flatMap<T>(transform: Elements.Generator.Element -> T?)
>     -> LazyMapCollection<LazyFilterCollection<LazyMapCollection<Elements,
> T?>>, T> {
>       return self
>         .map(transform)
>         .filter { opt in opt != nil }
>         .map { notNil in notNil! }
>   }
> }

I like this.

> The version for a LazyCollectionType with a BidirectionalIndexType would
> rely on a similar LazyFilterCollection, but a BidirectionalFilterCollection
> doesn’t exist (I think). Is that something that might be included in this
> proposal?

Indeed.  I think that would be a separate proposal.

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j<i;j++){if(!(i%j)){j=0;break;}}if
(j){printf("%d\n",i);}}} /*Dmitri Gribenko <gribozavr at gmail.com>*/


More information about the swift-evolution mailing list