Tail Call - Syntactic Form

Syntactic Form

A tail call can be located just before the syntactical end of a subroutine:

function foo(data) { a(data); return b(data); }

Here, both a(data) and b(data) are calls, but b is the last thing the procedure executes before returning and is thus in tail position. However, not all tail calls are necessarily located at the syntactical end of a subroutine. Consider:

function bar(data) { if ( a(data) ) { return b(data); } return c(data); }

Here, both calls to b and c are in tail position. This is because each of them lies in the end of if-branch respectively, even though the first one is not syntactically at the end of bar's body.

Now consider this code:

function foo1(data) { return a(data) + 1; } function foo2(data) { var ret = a(data); return ret; } function foo3(data) { var ret = a(data); return (ret === 0) ? 1 : ret; }

Here, the call to a(data) is in tail position in foo2, but it is not in tail position either in foo1 or in foo3, because control must return to the caller to allow it to inspect or modify the return value before returning it.

Read more about this topic:  Tail Call

Famous quotes containing the words syntactic and/or form:

    “The syntactic component of a grammar must specify, for each sentence, a deep structure that determines its semantic interpretation and a surface structure that determines its phonetic interpretation.”
    —Noam Chomsky (b. 1928)

    “Natural selection, the blind, unconscious, automatic process which Darwin discovered, and which we now know is the explanation for the existence and apparently purposeful form of all life, has no purpose in mind. It has no mind and no mind’s eye. It does not plan for the future. It has no vision, no foresight, no sight at all. If it can be said to play the role of the watchmaker in nature, it is the blind watchmaker.”
    —Richard Dawkins (b. 1941)