[go: up one dir, main page]

Skip to content

Commit

Permalink
Add exclusive eager version of reductions(into:_:)
Browse files Browse the repository at this point in the history
  • Loading branch information
danielctull committed Nov 29, 2020
1 parent 25665e4 commit 7cbff5c
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 3 deletions.
16 changes: 13 additions & 3 deletions Sources/Algorithms/Reductions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -47,14 +47,24 @@ extension Sequence {
_ transform: (Result, Element) throws -> Result
) rethrows -> [Result] {

var result = initial
return try reductions(into: &result) { result, element in
result = try transform(result, element)
}
}

public func reductions<Result>(
into initial: inout Result,
_ transform: (inout Result, Element) throws -> Void
) rethrows -> [Result] {

var output = [Result]()
output.reserveCapacity(underestimatedCount + 1)
output.append(initial)

var result = initial
for element in self {
result = try transform(result, element)
output.append(result)
try transform(&initial, element)
output.append(initial)
}

return output
Expand Down
8 changes: 8 additions & 0 deletions Tests/SwiftAlgorithmsTests/ReductionsTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,14 @@ final class ReductionsTests: XCTestCase {
XCTAssertEqual([1].reductions(0, +), [0, 1])
XCTAssertEqual(EmptyCollection<Int>().reductions(0, +), [0])

var value0 = 0
var value1 = 0
var value2 = 0
func add(lhs: inout Int, rhs: Int) { lhs += rhs }
XCTAssertEqual([1, 2, 3, 4].reductions(into: &value0, add), [0, 1, 3, 6, 10])
XCTAssertEqual([1].reductions(into: &value1, add), [0, 1])
XCTAssertEqual(EmptyCollection<Int>().reductions(into: &value2, add), [0])

XCTAssertNoThrow(try [].reductions(0) { _, _ in throw TestError() })
XCTAssertThrowsError(try [1].reductions(0) { _, _ in throw TestError() })
}
Expand Down

0 comments on commit 7cbff5c

Please sign in to comment.