Skip to content

Instantly share code, notes, and snippets.

@brecert
Created February 10, 2022 04:56
Show Gist options
  • Save brecert/fa4a95d9afae1d470f43e56f4c0058d4 to your computer and use it in GitHub Desktop.
Save brecert/fa4a95d9afae1d470f43e56f4c0058d4 to your computer and use it in GitHub Desktop.
type Tuple<V, N extends number, T extends V[] = []> =
N extends T['length'] ? T : Tuple<V, N, [...T, V]>;
type Nat = Nat[]
type ToNumber<N extends Nat> = N['length']
type FromNumber<N extends number> = Tuple<Nat, N>
type Zero = []
type One = [Nat]
type N2 = Add<One, One>
type N4 = Add<N2, N2>
type N8 = Add<N4, N4>
type N16 = Add<N8, N8>
type N32 = Add<N16, N16>
type N64 = Add<N32, N32>
type N128 = Add<N64, N64>
type Add<A extends Nat, B extends Nat> = [...A, ...B]
type LessThan<A extends Nat, B extends Nat> = B[A['length']] extends undefined ? false : true
type Fib<
N extends Nat,
I extends Nat = Zero,
Prev extends Tuple<Nat, 2> = [Zero, One],
PrevSum extends Nat = Add<Prev[0], Prev[1]>,
> =
LessThan<I, N> extends true
? Fib<N, Add<I, One>, [Prev[1], PrevSum]>
: PrevSum
type Result = ToNumber<Fib<N16>>
// the first three numbers are precalculated, so this is actually the number for the 19th place.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment