Sequencing a CPS factorial

The following Python-style function computes a factorial in continuation-passing style:


Python
def fact_k(n, k):
    if n == 0:
        return k(1)
    return fact_k(n - 1, lambda v: k(n * v))


The program evaluates fact_k(3, ident), where ident is lambda v: v. Call the continuation built during the call with n=3n = 3 k1, the one built with n=2n = 2 k2, and the one built with n=1n = 1 k3. Put the events of this evaluation in the order they happen, earliest first.

  1. 1.

    fact_k(2, k1) builds k2 and calls fact_k(1, k2).

  2. 2.

    k1 computes 3×23 \times 2 and applies ident to 6, which returns 6.

  3. 3.

    k2 computes 2×12 \times 1 and applies k1 to 2.

  4. 4.

    k3 computes 1×11 \times 1 and applies k2 to 1.

  5. 5.

    fact_k(3, ident) builds k1 and calls fact_k(2, k1).

  6. 6.

    fact_k(0, k3) reaches the base case and applies k3 to 1.

  7. 7.

    fact_k(1, k2) builds k3 and calls fact_k(0, k3).

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

More Continuation Passing Style Questions: