Skip to content

[stdlib] Adding RangeReplaceable.filter returning Self #9741

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 18, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions stdlib/public/core/Arrays.swift.gyb
Original file line number Diff line number Diff line change
Expand Up @@ -1574,6 +1574,16 @@ extension ${Self} : RangeReplaceableCollection, _ArrayProtocol {
}
}

// Since RangeReplaceableCollection now has a version of filter that is less
// efficient, we should make the default implementation coming from Sequence
// preferred.
@_inlineable
public func filter(
_ isIncluded: (Element) throws -> Bool
) rethrows -> [Element] {
return try _filter(isIncluded)
}

//===--- algorithms -----------------------------------------------------===//

@_inlineable
Expand Down
25 changes: 25 additions & 0 deletions stdlib/public/core/RangeReplaceableCollection.swift.gyb
Original file line number Diff line number Diff line change
Expand Up @@ -1212,6 +1212,31 @@ public func += <
lhs.append(contentsOf: rhs)
}

extension RangeReplaceableCollection {
/// Returns a new collection of the same type containing, in order, the
/// elements of the original collection that satisfy the given predicate.
///
/// In this example, `filter(_:)` is used to include only names shorter than
/// five characters.
///
/// let cast = ["Vivien", "Marlon", "Kim", "Karl"]
/// let shortNames = cast.filter { $0.count < 5 }
/// print(shortNames)
/// // Prints "["Kim", "Karl"]"
///
/// - Parameter isIncluded: A closure that takes an element of the
/// sequence as its argument and returns a Boolean value indicating
/// whether the element should be included in the returned array.
/// - Returns: An array of the elements that `isIncluded` allowed.
@_inlineable
@available(swift, introduced: 4.0)
public func filter(
_ isIncluded: (Element) throws -> Bool
) rethrows -> Self {
return try Self(self.lazy.filter(isIncluded))
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Probably worth checking that this is just as fast as a hand-rolled loop with append. It ought to be, and this is definitely the right way to code it, but worth checking. I'll add a benchmark – doesn't need to hold this up though.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One cannot regress something that does not exist. 🤷‍♂️

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here is the snippet I played with:

@inline(never)
public func iteration<
  C : RangeReplaceableCollection
>(_ xs: C, _ f: (C.Element) -> Bool) -> C {
    var result = C()
    var iterator = xs.makeIterator()
    while let element = iterator.next() {
      if f(element) {
        result.append(element)
      }
    }
    return result
}

@inline(never)
public func lazyFilter<
  C : RangeReplaceableCollection
>(_ xs: C, _ f: (C.Element) -> Bool) -> C {
  return C(xs.lazy.filter(f))
}


for _ in 0..<1_000 {
  /*_ = iteration(Array(0..<10000)) { $0 % 2 == 0 }*/
  _ = lazyFilter(Array(0..<10000)) { $0 % 2 == 0 }
}

Commenting one and uncommenting the other gives these results on my machine:

# lazyFilter                                                                                                                        
swiftc -swift-version 3 -O ../filter.swift -o ../filter && time ../filter
../filter  0.59s user 0.00s system 99% cpu 0.604 total

# iteration
swiftc -swift-version 3 -O ../filter.swift -o ../filter && time ../filter
../filter  1.45s user 0.00s system 99% cpu 1.462 total

#lazyFilter                                                                                                    
swiftc -swift-version 4 -O ../filter.swift -o ../filter && time ../filter
../filter  0.60s user 0.00s system 99% cpu 0.604 total

# iteration                                                                                                                        
swiftc -swift-version 4 -O ../filter.swift -o ../filter && time ../filter
../filter  1.46s user 0.00s system 99% cpu 1.469 total

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also both IR and SIL look better in case of lazyFilter.

}
}

@available(*, unavailable, renamed: "RangeReplaceableCollection")
public typealias RangeReplaceableCollectionType = RangeReplaceableCollection

Expand Down
7 changes: 7 additions & 0 deletions stdlib/public/core/Sequence.swift
Original file line number Diff line number Diff line change
Expand Up @@ -877,6 +877,13 @@ extension Sequence {
public func filter(
_ isIncluded: (Element) throws -> Bool
) rethrows -> [Element] {
return try _filter(isIncluded)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This will mean ContiguousArray and ArraySlice will also return an Array from filter, not Self? Which is... probably the right thing? Worth checking my thinking though.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's what they have been doing all along. filter is not redefined anywhere near array types. They all inherit the default Sequence implementation.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh, I see what you mean here... The line you commented on is misleading, but yeah, even with the addition of a new overload, they will still return [T].

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right. I was just questioning whether this is the right thing. I think it is for those two types specifically.

}

@_transparent
public func _filter(
_ isIncluded: (Element) throws -> Bool
) rethrows -> [Element] {

var result = ContiguousArray<Element>()

Expand Down
29 changes: 29 additions & 0 deletions test/stdlib/RangeReplaceableFilterCompatibility.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
// RUN: rm -rf %t ; mkdir -p %t
// RUN: %target-build-swift %s -o %t/a.out3 -swift-version 3 && %target-run %t/a.out3
// RUN: %target-build-swift %s -o %t/a.out4 -swift-version 4 && %target-run %t/a.out4

import StdlibUnittest

var tests = TestSuite("RangeReplaceableFilterCompatibility")

tests.test("String.filter return type") {
var filtered = "Hello, World".filter { $0 < "A" }
#if swift(>=4)
expectType(String.self, &filtered)
#else
expectType([Character].self, &filtered)
#endif
}

tests.test("Array.filter return type") {
var filtered = Array(0..<10).filter { $0 % 2 == 0 }
expectType([Int].self, &filtered)
}

tests.test("String.filter can return [Character]") {
let filtered = "Hello, World".filter { "A" <= $0 && $0 <= "Z"} as [Character]
expectEqualSequence("HW", filtered)
}


runAllTests()