1
1
mirror of https://github.com/github/semantic.git synced 2024-11-30 06:07:23 +03:00
semantic/prototype/Doubt/Matrix.swift
2015-10-06 12:19:59 -04:00

44 lines
1.0 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/// 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.
struct Matrix<A> {
init(width: Int, height: Int, compute: (Int, Int) -> A) {
var values: [Memo<A>] = []
values.reserveCapacity(width * height)
for i in 0..<width {
for j in 0..<height {
values[i + j * height] = Memo<A> { compute(i, j) }
}
}
self.init(width: width, height: height, values: values)
}
let width: Int
let height: Int
let values: [Memo<A>]
subscript (i: Int, j: Int) -> Memo<A>? {
guard i < width && j < height else { return nil }
return values[i + j * height]
}
// MARK: Functor
func map<Other>(transform: A -> Other) -> Matrix<Other> {
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
}
}