Skip to content

Instantly share code, notes, and snippets.

@bergwerf
Created March 22, 2025 23:02
Show Gist options
  • Save bergwerf/f40dff95b4dfe6bbd4819c39783179a7 to your computer and use it in GitHub Desktop.
Save bergwerf/f40dff95b4dfe6bbd4819c39783179a7 to your computer and use it in GitHub Desktop.
Arbitrary numeric tensors in TypeScript
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