Created
March 22, 2025 23:02
-
-
Save bergwerf/f40dff95b4dfe6bbd4819c39783179a7 to your computer and use it in GitHub Desktop.
Arbitrary numeric tensors in TypeScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type Array_Element<A> = A extends (infer T)[] ? T : never | |
type Fixed_Array<A, X> = | |
[A] extends [[]] ? [] : | |
[A] extends [[X, ...infer T]] ? [X, ...Fixed_Array<T, X>] : never | |
type Vector<V> = Fixed_Array<V, Vector_Car<V>> | |
type Vector_Car<V> = [V] extends [number[]] ? number : Vector<Array_Element<V>> | |
class Vec<V extends Vector<V>> { | |
constructor(public readonly _: V) { } | |
plus(v: V): Vec<V> { | |
return new Vec(this._.map((x, i) => | |
typeof x === 'number' ? x + v[i] : | |
new Vec(x).plus(v[i]) | |
) as V) | |
} | |
} | |
function vec<V extends Vector<V>>(x: V) { | |
return new Vec(x) | |
} | |
console.log(vec([1, 2, 3]).plus([6, 4, 2])._) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment