Skip to content

Commit e96bf94

Browse files
committed
Added closure-based initializer function for Matrix and corresponding unit test
1 parent 8384756 commit e96bf94

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

Sources/Surge/Linear Algebra/Vector.swift

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,17 @@ public struct Vector<Scalar> where Scalar: FloatingPoint, Scalar: ExpressibleByF
4646
self.dimensions = scalars.count
4747
self.scalars = scalars
4848
}
49+
50+
public init(dimensions: Int, _ closure: (Int) throws -> Scalar) rethrows {
51+
var scalars: [Scalar] = []
52+
scalars.reserveCapacity(dimensions)
53+
54+
for index in 0..<dimensions {
55+
scalars.append(try closure(index))
56+
}
57+
58+
self.init(scalars)
59+
}
4960
}
5061

5162
// MARK: - ExpressibleByArrayLiteral

Tests/SurgeTests/VectorTests.swift

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,19 @@ import XCTest
2727
class VectorTests: XCTestCase {
2828
// MARK: - Initialization
2929

30+
func test_init_dimensions_repeatedValue() {
31+
typealias Scalar = Double
32+
33+
let dimensions = 5
34+
let repeatedValue: Scalar = 42
35+
36+
let actual: Vector<Scalar> = Vector(dimensions: dimensions, repeatedValue: repeatedValue)
37+
38+
let expected: Vector<Scalar> = [42, 42, 42, 42, 42]
39+
40+
XCTAssertEqual(actual, expected)
41+
}
42+
3043
func test_init() {
3144
typealias Scalar = Double
3245

@@ -36,6 +49,17 @@ class VectorTests: XCTestCase {
3649
XCTAssertEqual(lhs.scalars, values)
3750
}
3851

52+
func test_init_dimensions_closure() {
53+
typealias Scalar = Double
54+
55+
let dimensions = 5
56+
let actual: Vector<Scalar> = Vector(dimensions: dimensions) { Scalar($0)
57+
}
58+
let expected: Vector<Scalar> = [0, 1, 2, 3, 4]
59+
60+
XCTAssertEqual(actual, expected)
61+
}
62+
3963
// MARK: - Subscript
4064

4165
func test_subscript() {

0 commit comments

Comments
 (0)