Compare commits

...
Author SHA1 Message Date
Nate Cook b333caf0a5 Naive benchmark harness 2021-03-23 14:23:36 -05:00
Charles Maria TorandXiaodi Wu e64cff7e1d Add Sequence.firstNonNil(_:) (#31)
* Add Sequence.firstNonNil(of:) and associated tests

* Rename First.swift to FirstTests.swift

* Address PR comments by adding guide and changing naming

* Address PR comments by changing name

* Update Guides/FirstNonNil.md

Co-authored-by: Xiaodi Wu <13952+xwu@users.noreply.github.com>

* Update Sources/Algorithms/FirstNonNil.swift

Co-authored-by: Xiaodi Wu <13952+xwu@users.noreply.github.com>

Co-authored-by: Xiaodi Wu <13952+xwu@users.noreply.github.com>
2021-03-23 19:55:33 +01:00
Kyle Macomber 98b6e26d8d Remove .xcodesamplecode.plist, which prevents editing markdown from Xcode (#111) 2021-03-23 13:20:39 -05:00
Luciano Almeida ca8af77420 [test] Adding missing BidirectionalCollection::partition(subrange:) and MutableCollection::partition(subrange:) unit tests (#95) 2021-03-23 13:20:21 -05:00
Ahmad Alhashemi e077f67639 Improve XCTAssertEqualSequences to log difference (#105) 2021-03-23 07:52:56 -07:00
8 changed files with 372 additions and 15 deletions

No files matched your search

-5
View File
@@ -1,5 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<array/>
</plist>
+43
View File
@@ -0,0 +1,43 @@
# First Non-Nil
[[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/FirstNonNil.swift) |
[Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/FirstNonNilTests.swift)]
Retrieves the first `.some` encountered while applying the given transform.
This operation is available through the `firstNonNil(_:)` method on any sequence.
```swift
let value = ["A", "B", "10"].firstNonNil { Int($0) }
// value == .some(10)
//
let noValue = ["A", "B", "C"].firstNonNil { Int($0) }
// noValue == .none
```
This method is analogous to `first(where:)` in how it only consumes values until
a `.some` is found, unlike using lazy operators, which will load any sequence into a collection
before evaluating its transforms lazily.
## Detailed Design
The `firstNonNil(_:)` method is added as an extension method on the `Sequence`
protocol:
```swift
public extension Sequence {
func firstNonNil<Result>(_ transform: (Element) throws -> Result?)
rethrows -> Result?
}
```
### Naming
This method’s name was selected for its comprehensibility.
### Comparison with other languages
**Scala**: Scala provides a `collectFirst` function that finds the first element
in a collection for which a partial function is defined.
+3
View File
@@ -28,6 +28,9 @@ let package = Package(
dependencies: [
.product(name: "RealModule", package: "swift-numerics"),
]),
.target(
name: "Benchmark",
dependencies: ["Algorithms"]),
.testTarget(
name: "SwiftAlgorithmsTests",
dependencies: ["Algorithms"]),
+28
View File
@@ -0,0 +1,28 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Algorithms open source project
//
// Copyright (c) 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
// firstNonNil(_:)
//===----------------------------------------------------------------------===//
public extension Sequence {
/// Returns the first element in `self` that `transform` maps to a `.some`.
func firstNonNil<Result>(
_ transform: (Element) throws -> Result?
) rethrows -> Result? {
for value in self {
if let value = try transform(value) {
return value
}
}
return nil
}
}
+140
View File
@@ -0,0 +1,140 @@
import Darwin
import Algorithms
struct Benchmark {
var name: String
var `default`: Int
var body: (Int) -> Int
}
let benchmarks = [
Benchmark(name: "chain", default: 100) { count in
let x = String(repeating: "_", count: 10_000)
.chained(with: String(repeating: "-", count: 10_000))
.chained(with: "0")
var v = 0
for _ in 0..<count {
let i = x.firstIndex(of: "0")!
let d = x.distance(from: x.startIndex, to: i)
v &+= d
}
return v
},
Benchmark(name: "chunked", default: 1000) { count in
let x = (1...1000).shuffled()
var v = 0
for _ in 0..<count {
let y = x.chunked(by: <=)
v &+= y.count
}
return v
},
Benchmark(name: "lazy chunked", default: 1000) { count in
let x = (1...1000).shuffled()
var v = 0
for _ in 0..<count {
let y = x.lazy.chunked(by: <=)
v &+= y.count
}
return v
},
Benchmark(name: "combinations", default: 100) { count in
let x = 1...30
var v = 0
for _ in 0..<count {
let y = x.combinations(ofCount: 4)
let combo = y.first(where: { combo in combo.allSatisfy { $0.isMultiple(of: 2) }})!
v &+= combo.reduce(0, +)
}
return v
},
Benchmark(name: "stable partition", default: 100) { count in
var v = 0
for _ in 0..<count {
var x = Array(1...10000)
let i = x.stablePartition(by: { $0.isMultiple(of: 3) })
v &+= i
}
return v
},
Benchmark(name: "permutations", default: 10) { count in
let x = 1...20
var v = 0
for _ in 0..<count {
let y = x.permutations(ofCount: 4)
let perm = y.first(where: { perm in perm.allSatisfy { $0.isMultiple(of: 2) }})!
v &+= perm.reduce(0, +)
}
return v
},
Benchmark(name: "product", default: 1000) { count in
let x = product(1...100, "abcdefghijklmnopqrstuvwxyz")
var v = 0
for _ in 0..<count {
let i = x.firstIndex(where: { $0 == 77 && $1 == "m" })!
let d = x.distance(from: x.startIndex, to: i)
v &+= d
}
return v
},
Benchmark(name: "sample", default: 1000) { count in
let x = 1...10000
var v = 0
for _ in 0..<count {
let r = x.randomSample(count: 20)
v &+= r.reduce(0, +)
}
return v
},
Benchmark(name: "stable sample", default: 1000) { count in
let x = 1...10000
var v = 0
for _ in 0..<count {
let r = x.randomStableSample(count: 20)
v &+= r.reduce(0, +)
}
return v
},
Benchmark(name: "uniqued", default: 1000) { count in
let x = repeatElement(1...1000, count: 1000)
var v = 0
for _ in 0..<count {
let r = x.uniqued()
v &+= r.count
}
return v
},
]
func printChoices() -> Never {
print(benchmarks.enumerated().map { "\($0): \($1.name)" }.joined(separator: "\n"))
exit(0)
}
if CommandLine.arguments.count <= 1 {
printChoices()
} else {
guard let choice = Int(CommandLine.arguments[1]), benchmarks.indices.contains(choice) else {
print("Invalid choice:")
printChoices()
}
let bench = benchmarks[choice]
let count: Int
if CommandLine.arguments.count > 2, let c = Int(CommandLine.arguments[2]) {
count = c
} else {
count = bench.default
}
print(bench.body(count))
}
@@ -0,0 +1,23 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Algorithms open source project
//
// Copyright (c) 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
import XCTest
import Algorithms
final class FirstNonNilTests: XCTestCase {
func testFirstNonNil() {
XCTAssertNil([].firstNonNil { $0 })
XCTAssertNil(["A", "B", "C"].firstNonNil { Int($0) })
XCTAssertNil(["A", "B", "C"].firstNonNil { _ in nil })
XCTAssertEqual(["A", "B", "10"].firstNonNil { Int($0) }, 10)
XCTAssertEqual(["20", "B", "10"].firstNonNil { Int($0) }, 20)
}
}
@@ -64,14 +64,17 @@ final class PartitionTests: XCTestCase {
func testStablePartitionWithSubrange() {
for length in 10...20 {
let a = Array(0..<length)
for j in 0..<length {
var b = a
let partitionRange = 0..<j
let condition = { $0 < j - 1 }
let p = b.stablePartition(subrange: partitionRange, by: condition)
XCTAssertEqual(p, partitionRange.count > 0 ? 1 : 0)
XCTAssertEqualSequences(b[partitionRange.lowerBound..<p], a[partitionRange].filter { !condition($0) })
XCTAssertEqualSequences(b[p..<partitionRange.upperBound], a[partitionRange].filter(condition))
for i in 0..<length {
for j in 0...i {
var b = a
let partitionRange = j..<i
let condition = { $0 < i - 1 }
let p = b.stablePartition(subrange: partitionRange, by: condition)
XCTAssertEqual(p, partitionRange.count == 0 ? j : j + 1)
XCTAssertEqualSequences(b[partitionRange.lowerBound..<p], a[partitionRange].filter { !condition($0) })
XCTAssertEqualSequences(b[p..<partitionRange.upperBound], a[partitionRange].filter(condition))
}
}
}
}
@@ -88,4 +91,46 @@ final class PartitionTests: XCTestCase {
}
}
}
func testPartitionWithSubrangeBidirectionalCollection() {
for length in 10...20 {
let a = Array(0..<length)
for i in 0..<length {
for j in 0...i {
var b = a
let partitionRange = j..<i
let condition = { $0 < i - 1 }
let p = b.partition(subrange: partitionRange, by: condition)
XCTAssertEqual(p, partitionRange.count == 0 ? j : j + 1)
XCTAssertEqualSequences(b[partitionRange.lowerBound..<p], a[partitionRange].filter { !condition($0) })
XCTAssertUnorderedEqualSequences(b[p..<partitionRange.upperBound], a[partitionRange].filter(condition))
}
}
}
}
func testPartitionWithSubrangeMutableCollection() {
for length in 10...20 {
let a = Array(0..<length)
for i in 0..<length {
for j in 0...i {
var b = a.eraseToAnyMutableCollection()
var bdc = a
let partitionRange = j..<i
let condition = { $0 < i - 1 }
let p = b.partition(subrange: partitionRange, by: condition)
let bdcp = bdc.partition(subrange: partitionRange, by: condition)
XCTAssertEqual(p, partitionRange.count == 0 ? j : j + 1)
XCTAssertEqualSequences(b[partitionRange.lowerBound..<p], a[partitionRange].filter { !condition($0) })
XCTAssertUnorderedEqualSequences(b[p..<partitionRange.upperBound], a[partitionRange].filter(condition))
// Must produce the same result as the `BidirectionalCollection` specialized overload.
XCTAssertEqualSequences(b[partitionRange.lowerBound..<p], bdc[partitionRange.lowerBound..<bdcp])
XCTAssertUnorderedEqualSequences(b[p..<partitionRange.upperBound], bdc[bdcp..<partitionRange.upperBound])
}
}
}
}
}
+82 -2
View File
@@ -46,13 +46,69 @@ struct SplitMix64: RandomNumberGenerator {
}
}
// An eraser helper to any mutable collection
struct AnyMutableCollection<Base> where Base: MutableCollection {
var base: Base
}
extension AnyMutableCollection: MutableCollection {
typealias Index = Base.Index
typealias Element = Base.Element
var startIndex: Base.Index { base.startIndex }
var endIndex: Base.Index { base.endIndex }
func index(after i: Index) -> Index {
return base.index(after: i)
}
subscript(position: Base.Index) -> Base.Element {
_read { yield base[position] }
set { base[position] = newValue }
}
}
extension MutableCollection {
func eraseToAnyMutableCollection() -> AnyMutableCollection<Self> {
AnyMutableCollection(base: self)
}
}
func XCTAssertEqualSequences<S1: Sequence, S2: Sequence>(
_ expression1: @autoclosure () throws -> S1,
_ expression2: @autoclosure () throws -> S2,
_ message: @autoclosure () -> String = "",
file: StaticString = #file, line: UInt = #line
) rethrows where S1.Element: Equatable, S1.Element == S2.Element {
try XCTAssert(expression1().elementsEqual(expression2()), message(), file: file, line: line)
try XCTAssertEqualSequences(expression1(), expression2(), by: ==,
message(), file: file, line: line)
}
// Two sequences contains exactly the same element but not necessarily in the same order.
func XCTAssertUnorderedEqualSequences<S1: Sequence, S2: Sequence>(
_ expression1: @autoclosure () throws -> S1,
_ expression2: @autoclosure () throws -> S2,
file: StaticString = #file, line: UInt = #line
) rethrows where S1.Element: Equatable, S1.Element == S2.Element {
var s1 = Array(try expression1())
var missing: [S1.Element] = []
for elt in try expression2() {
guard let idx = s1.firstIndex(of: elt) else {
missing.append(elt)
continue
}
s1.remove(at: idx)
}
XCTAssertTrue(
missing.isEmpty, "first sequence missing '\(missing)' elements from second sequence",
file: file, line: line
)
XCTAssertTrue(
s1.isEmpty, "first sequence contains \(s1) missing from second sequence",
file: file, line: line
)
}
func XCTAssertEqualSequences<S1: Sequence, S2: Sequence>(
@@ -62,7 +118,31 @@ func XCTAssertEqualSequences<S1: Sequence, S2: Sequence>(
_ message: @autoclosure () -> String = "",
file: StaticString = #file, line: UInt = #line
) rethrows where S1.Element == S2.Element {
try XCTAssert(expression1().elementsEqual(expression2(), by: areEquivalent), message(), file: file, line: line)
func fail(_ reason: String) {
let message = message()
XCTFail(message.isEmpty ? reason : "\(message) - \(reason)",
file: file, line: line)
}
var iter1 = try expression1().makeIterator()
var iter2 = try expression2().makeIterator()
var idx = 0
while true {
switch (iter1.next(), iter2.next()) {
case let (e1?, e2?) where areEquivalent(e1, e2):
idx += 1
continue
case let (e1?, e2?):
fail("element \(e1) on first sequence does not match element \(e2) on second sequence at position \(idx)")
case (_?, nil):
fail("second sequence shorter than first")
case (nil, _?):
fail("first sequence shorter than second")
case (nil, nil): break
}
return
}
}
func XCTAssertLazySequence<S: LazySequenceProtocol>(_: S) {}