Skip to content
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
25 changes: 25 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -82,3 +82,28 @@ print( 0.clamping(within: 2...7)) // Prints 2
print( 5.clamping(within: 2...7)) // Prints 5
print(99.clamping(within: 2...7)) // Prints 7
```



# Additive Reduction #

This introduces a `.reduce(_:)` function to sequences whose elements conform to `AdditiveArithmetic` which assumes you're reducing into `.zero`:

```swift
// Before
bunchaNumbers.reduce(into: 0) { $0 = max($0, $1) }

// After
bunchaNumbers.reduce { $0 = max($0, $1) }
```


This also adds a convenience function `.sum()`, build on this new reducer:

```swift
// Before
bunchaNumbers.reduce(into: 0, +=)

// After
bunchaNumbers.sum()
```
31 changes: 31 additions & 0 deletions Sources/BasicMathTools/additive reductions.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
//
// additive reductions.swift
//
//
// Created by The Northstar✨ System on 2023-11-30.
//

import Foundation



public extension Sequence where Element: AdditiveArithmetic {

/// Reduces this collection to a single value, assuming the result should be of the same type as each element, and that the starting value for reduction is `.zero`
///
/// - Parameters:
/// - reducer: Processes each element and reduces this collection to a single value
/// - result: The running result of reduction (starts with `.zero`)
/// - each: Each element of the sequence
///
/// - Returns: The whole collection, reduced down to a single value
func reduce(_ reducer: (_ result: inout Element, _ each: Element) -> Void) -> Element {
reduce(into: .zero, reducer)
}


/// Returns the sum of all elements in this sequence
func sum() -> Element {
reduce(+=)
}
}
31 changes: 31 additions & 0 deletions Tests/BasicMathToolsTests/additive reductions tests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
//
// additive reductions tests.swift
//
//
// Created by The Northstar✨ System on 2023-11-30.
//

import XCTest
import BasicMathTools



final class additive_reductions_tests: XCTestCase {
func testSum() {
XCTAssertEqual(29, [1, 2, 3, 5, 7, 11].sum())
XCTAssertEqual(0, [1, -1, 1, -1, 1, -1].sum())
}


func testReduce() {
XCTAssertEqual(-58, [1, 2, 3, 5, 7, 11].reduce { result, each in
result = (result - (each * 2))
})

XCTAssertEqual(-29, [1, 2, 3, 5, 7, 11].reduce(-=))

XCTAssertEqual(0, [1, 2, 3, 5, 7, 11].reduce(*=))

XCTAssertEqual(56, [8, -31, 11, -13, 56, 27, -2].reduce { $0 = max($0, $1) })
}
}