Combination of Recursive Functions

Theorem
Let $f: \N^k \to \N$ and $g: \N^k \to \N$ be recursive functions (not necessarily total), where $k \ge 1$.

Let $\mathcal R$ be a $k$-ary relation such that:
 * if $\mathcal R \left({n_1, n_2, \ldots, n_k}\right)$ holds, then $f \left({n_1, n_2, \ldots, n_k}\right)$ is defined
 * if $\mathcal R \left({n_1, n_2, \ldots, n_k}\right)$ does not hold, then $g \left({n_1, n_2, \ldots, n_k}\right)$ is defined.

Let $h: \N^k \to \N$ be the function defined as:
 * $h \left({n_1, n_2, \ldots, n_k}\right) = \begin{cases}

f \left({n_1, n_2, \ldots, n_k}\right) & : \text{if } \mathcal R \left({n_1, n_2, \ldots, n_k}\right) \text { holds} \\ g \left({n_1, n_2, \ldots, n_k}\right) & : \text{otherwise} \end{cases}$ so that $h$ is total.

Then $h$ is recursive.

Proof
Let $P_f, P_g, P_\mathcal R$ be the URM programs computing, respectively, the functions $f$ and $g$ and the characteristic function $\chi_\mathcal R$.

These programs are guaranteed to exist as all recursive functions are URM computable.

An informal algorithm for computing $h$ is as follows.


 * 1) Input $\left({n_1, n_2, \ldots, n_k}\right)$.
 * 2) Use $P_\mathcal R$ to determine whether $\mathcal R \left({n_1, n_2, \ldots, n_k}\right)$ holds.
 * 3) If it holds, use $P_f$ to compute $f \left({n_1, n_2, \ldots, n_k}\right)$.
 * 4) If it does not hold, use $P_g$ to compute $g \left({n_1, n_2, \ldots, n_k}\right)$.

The result follows from URM Computable Function is Recursive.

Fallacious Proof
We might attempt to show that $h$ is recursive by using the equation:

where $\overline{\operatorname{sgn}}$ is the signum bar function, known to be primitive recursive.

Then the RHS is obtained by substitution from known recursive functions, so is recursive, and hence $h$ is recursive.

However, this fails as follows.

Although $h \left({n_1, n_2, \ldots, n_k}\right)$ is always defined,

might not be.

$f$ and $g$ might not be total, in which case there may be some $\left({n_1, n_2, \ldots, n_k}\right)$ for which at least one of $f \left({n_1, n_2, \ldots, n_k}\right)$ and $g \left({n_1, n_2, \ldots, n_k}\right)$ is not defined.

This means $(1)$ is not defined for those values of $\left({n_1, n_2, \ldots, n_k}\right)$.

Note that $(1)$ does define a recursive function, but its domain consists only of those $\left({n_1, n_2, \ldots, n_k}\right)$ for which $f \left({n_1, n_2, \ldots, n_k}\right)$ and $g \left({n_1, n_2, \ldots, n_k}\right)$ are both defined.

Thus we establish the result by means of the indirect approach requiring the use of the results concerning the equivalence of recursive functions and URM computable functions.