1
1
mirror of https://github.com/github/semantic.git synced 2024-12-28 09:21:35 +03:00
semantic/prototype/Doubt/Matrix.swift

49 lines
1.4 KiB
Swift
Raw Normal View History

2015-10-06 19:19:59 +03:00
/// A two-dimensional matrix of memoized values.
///
/// These values are populated by a function from the coordinates of a given cell to the matrixs element type.
///
/// Values are retrieved by subscripting with row/column indices. Out-of-bound indices produce `nil` values, rather than asserting.
2015-10-06 20:00:07 +03:00
public struct Matrix<A> {
public init(width: Int, height: Int, compute: (Int, Int) -> A) {
self.init(width: width, height: height, values: constructRowMajor(width, height: height, forEach: { i, j in Memo { compute(i, j) } }))
}
2015-10-06 20:00:07 +03:00
public let width: Int
public let height: Int
2015-10-06 00:11:56 +03:00
2015-10-06 20:00:01 +03:00
private let values: [Memo<A>]
2015-10-06 00:11:56 +03:00
2015-10-06 20:00:07 +03:00
public subscript (i: Int, j: Int) -> Memo<A>? {
2015-10-06 00:11:56 +03:00
guard i < width && j < height else { return nil }
2015-10-06 21:11:36 +03:00
return values[i + j * width]
2015-10-06 00:11:56 +03:00
}
2015-10-06 00:18:40 +03:00
// MARK: Functor
2015-10-06 20:00:07 +03:00
public func map<Other>(transform: A -> Other) -> Matrix<Other> {
2015-10-06 00:18:40 +03:00
return Matrix<Other>(width: width, height: height, values: values.map { $0.map(transform) })
}
// MARK: Implementation details
private init(width: Int, height: Int, values: [Memo<A>]) {
self.width = width
self.height = height
self.values = values
}
2015-10-06 00:11:56 +03:00
}
2015-10-06 21:17:14 +03:00
/// Constructs a row-major ordering of values produced with `forEach`.
private func constructRowMajor<A>(width: Int, height: Int, @noescape forEach: (Int, Int) -> A) -> [A] {
var values: [A] = []
values.reserveCapacity(width * height)
for j in 0..<height {
for i in 0..<width {
values.append(forEach(i, j))
}
}
return values
}