Files
swift-mirror/stdlib/public/core/Map.swift.gyb
Joe Groff 0c39db22bc stdlib: Implement strict 'map', 'filter', and 'flatMap' as 'rethrows' operations.
Replace the Lazy-based implementations with open-coded implementations based on the _UnsafePartiallyInitializedContiguousArrayBuffer builder from the previous commit, so that we have control over the early-exit flow when an error interrupts the operation.

Swift SVN r30794
2015-07-30 05:28:34 +00:00

310 lines
10 KiB
Swift

//===--- Map.swift - Lazily map over a SequenceType -----------*- swift -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// The `GeneratorType` used by `MapSequence` and `MapCollection`.
/// Produces each element by passing the output of the `Base`
/// `GeneratorType` through a transform function returning `Element`.
public struct MapGenerator<
Base : GeneratorType, Element
> : GeneratorType, SequenceType {
@available(*, unavailable, renamed="Element")
public typealias T = Element
/// Advance to the next element and return it, or `nil` if no next
/// element exists.
///
/// - Requires: `next()` has not been applied to a copy of `self`
/// since the copy was made, and no preceding call to `self.next()`
/// has returned `nil`.
public mutating func next() -> Element? {
let x = _base.next()
if x != nil {
return _transform(x!)
}
return nil
}
public var _prext_base: Base { return _base }
internal var _base: Base
internal var _transform: (Base.Element)->Element
}
/// A `SequenceType` whose elements consist of those in a `Base`
/// `SequenceType` passed through a transform function returning `Element`.
/// These elements are computed lazily, each time they're read, by
/// calling the transform function on a base element.
public struct _prext_LazyMapSequence<Base : SequenceType, Element>
: _prext_LazySequenceType/*, _SequenceWrapperType*/ {
public typealias Elements = _prext_LazyMapSequence
/// Return a *generator* over the elements of this *sequence*.
///
/// - Complexity: O(1).
public func generate() -> MapGenerator<Base.Generator, Element> {
return MapGenerator(_base: _base.generate(), _transform: _transform)
}
/// Return a value less than or equal to the number of elements in
/// `self`, **nondestructively**.
///
/// - Complexity: O(N).
public func underestimateCount() -> Int {
return _base.underestimateCount()
}
/// Create an instance with elements `transform(x)` for each element
/// `x` of base.
public init(_ base: Base, transform: (Base.Generator.Element)->Element) {
self._base = base
self._transform = transform
}
public var _base: Base
internal var _transform: (Base.Generator.Element)->Element
}
//===--- Collections ------------------------------------------------------===//
/// A `CollectionType` whose elements consist of those in a `Base`
/// `CollectionType` passed through a transform function returning `Element`.
/// These elements are computed lazily, each time they're read, by
/// calling the transform function on a base element.
public struct _prext_LazyMapCollection<Base : CollectionType, Element>
: _prext_LazyCollectionType {
// FIXME: Should be inferrable.
public typealias Index = Base.Index
public var startIndex: Base.Index { return _base.startIndex }
public var endIndex: Base.Index { return _base.endIndex }
/// Access the element at `position`.
///
/// - Requires: `position` is a valid position in `self` and
/// `position != endIndex`.
public subscript(position: Base.Index) -> Element {
return _transform(_base[position])
}
/// Returns `true` iff `self` is empty.
public var isEmpty: Bool { return _base.isEmpty }
public var first: Element? { return _base.first.map(_transform) }
/// Returns a *generator* over the elements of this *sequence*.
///
/// - Complexity: O(1).
public func generate() -> MapGenerator<Base.Generator, Element> {
return MapGenerator(_base: _base.generate(), _transform: _transform)
}
public func underestimateCount() -> Int {
return _base.underestimateCount()
}
/// Returns the number of elements.
///
/// - Complexity: O(1) if `Index` conforms to `RandomAccessIndexType`;
/// O(N) otherwise.
public var count: Index.Distance {
return _base.count
}
/// Create an instance with elements `transform(x)` for each element
/// `x` of base.
public init(_ base: Base, transform: (Base.Generator.Element)->Element) {
self._base = base
self._transform = transform
}
public var _base: Base
var _transform: (Base.Generator.Element)->Element
}
//===--- Support for lazy(s) ----------------------------------------------===//
extension _prext_LazySequenceType {
/// Return a `LazyMapSequence` over this `Sequence`. The elements of
/// the result are computed lazily, each time they are read, by
/// calling `transform` function on a base element.
public func map<U>(
transform: (Elements.Generator.Element) -> U
) -> _prext_LazyMapSequence<Elements, U> {
return _prext_LazyMapSequence(self.elements, transform: transform)
}
}
extension _prext_LazyCollectionType {
/// Return a `LazyMapCollection` over this `Collection`. The elements of
/// the result are computed lazily, each time they are read, by
/// calling `transform` function on a base element.
public func map<U>(
transform: (Elements.Generator.Element) -> U
) -> _prext_LazyMapCollection<Self.Elements, U> {
return _prext_LazyMapCollection(self.elements, transform: transform)
}
}
//===----------------------------------------------------------------------===//
// Implementations we are replacing
//===----------------------------------------------------------------------===//
//===--- Sequences --------------------------------------------------------===//
/// A `SequenceType` whose elements consist of those in a `Base`
/// `SequenceType` passed through a transform function returning `Element`.
/// These elements are computed lazily, each time they're read, by
/// calling the transform function on a base element.
public struct MapSequence<Base : SequenceType, Element> : SequenceType {
@available(*, unavailable, renamed="Element")
public typealias T = Element
/// Return a *generator* over the elements of this *sequence*.
///
/// - Complexity: O(1).
public func generate() -> MapGenerator<Base.Generator, Element> {
return MapGenerator(
_base: _base.generate(), _transform: _transform)
}
public func underestimateCount() -> Int {
return _base.underestimateCount()
}
var _base: Base
var _transform: (Base.Generator.Element)->Element
}
/// Return an `Array` containing the results of mapping `transform`
/// over `source`.
@available(*, unavailable, message="call the 'map()' method on the sequence")
public func map<S : SequenceType, T>(
source: S, _ transform: (S.Generator.Element) -> T
) -> [T] {
fatalError("unavailable function can't be called")
}
/// Return an `Array` containing the results of mapping `transform`
/// over `source` and flattening the result.
@available(*, unavailable, message="call the 'flatMap()' method on the sequence")
public func flatMap<S : SequenceType, T>(
source: S, @noescape _ transform: (S.Generator.Element) -> [T]
) -> [T] {
fatalError("unavailable function can't be called")
}
//===--- Collections ------------------------------------------------------===//
/// A `CollectionType` whose elements consist of those in a `Base`
/// `CollectionType` passed through a transform function returning `Element`.
/// These elements are computed lazily, each time they're read, by
/// calling the transform function on a base element.
public struct MapCollection<Base : CollectionType, Element> : CollectionType {
@available(*, unavailable, renamed="Element")
public typealias T = Element
/// The position of the first element in a non-empty collection.
///
/// In an empty collection, `startIndex == endIndex`.
public var startIndex: Base.Index {
return _base.startIndex
}
/// The collection's "past the end" position.
///
/// `endIndex` is not a valid argument to `subscript`, and is always
/// reachable from `startIndex` by zero or more applications of
/// `successor()`.
public var endIndex: Base.Index {
return _base.endIndex
}
/// Access the element at `position`.
///
/// - Requires: `position` is a valid position in `self` and
/// `position != endIndex`.
public subscript(position: Base.Index) -> Element {
return _transform(_base[position])
}
/// Returns a *generator* over the elements of this *sequence*.
///
/// - Complexity: O(1).
public func generate() -> MapSequence<Base, Element>.Generator {
return MapGenerator(_base: _base.generate(), _transform: _transform)
}
public func underestimateCount() -> Int {
return _base.underestimateCount()
}
var _base: Base
var _transform: (Base.Generator.Element)->Element
}
/// Return an `Array` containing the results of mapping `transform`
/// over `source`.
@available(*, unavailable, message="call the 'map()' method on the sequence")
public func map<C : CollectionType, T>(
source: C, _ transform: (C.Generator.Element) -> T
) -> [T] {
fatalError("unavailable function can't be called")
}
/// Return an `Array` containing the results of mapping `transform`
/// over `source` and flattening the result.
@available(*, unavailable, message="call the 'flatMap()' method on the sequence")
public func flatMap<C : CollectionType, T>(
source: C, _ transform: (C.Generator.Element) -> [T]
) -> [T] {
fatalError("unavailable function can't be called")
}
//===--- Support for lazy(s) ----------------------------------------------===//
% traversals = ('Forward', 'Bidirectional', 'RandomAccess')
% for View, Self in [('MapSequence', 'LazySequence')] + [
% ('MapCollection', 'Lazy%sCollection' % t) for t in traversals
% ]:
extension ${Self} {
/// Return a `${View}` over this `${Self}`. The elements of
/// the result are computed lazily, each time they are read, by
/// calling `transform` function on a base element.
public func map<U>(
transform: (Base.Generator.Element) -> U
) -> ${Self}<${View}<Base, U>> {
return ${Self}<${View}<Base, U>>(
${View}(_base: self._base, _transform: transform)
)
}
}
% end
@available(*, unavailable, renamed="MapGenerator")
public struct MapSequenceGenerator<Base : GeneratorType, T> {}
@available(*, unavailable, renamed="MapSequence")
public struct MapSequenceView<Base : SequenceType, T> {}
@available(*, unavailable, renamed="MapCollection")
public struct MapCollectionView<Base : CollectionType, T> {}
// ${'Local Variables'}:
// eval: (read-only-mode 1)
// End: