Function makeTrampoline

  • Wraps a recursive function inside a trampoline executor.

    This function transforms a potentially recursive function (that returns a Trampoline) into a stack-safe function that executes iteratively using the trampoline runner.

    In other words, it allows you to write functions that look recursive, but actually run in constant stack space.

    Type Parameters

    • Args extends any[]

      The tuple type representing the argument list of the original function.

    • Result

      The final return type after all trampoline steps are resolved.

    Parameters

    • fn: ((...args: Args) => Trampoline<Result>)

      A function that performs a single step of computation and returns a Trampoline (either a final value or a deferred thunk).

        • (...args): Trampoline<Result>
        • Parameters

          Returns Trampoline<Result>

    Returns ((...args: Args) => Result)

    A new function with the same arguments, but which automatically runs the trampoline process and returns the final result instead of a Trampoline.

    // Example: Computing factorial in a stack-safe way
    const factorial = makeTrampoline(function fact(n: number, acc: number = 1): Trampoline<number> {
    return n === 0
    ? acc
    : makeTrampolineThunk(() => fact(n - 1, acc * n));
    });

    console.log(factorial(100000)); // Works without stack overflow