Anonymous recursion

Anonymous recursion
You are encouraged to solve this task according to the task description, using any language you may know.

While implementing a recursive function, it often happens that we must resort to a separate helper function to handle the actual recursion.

This is usually the case when directly calling the current function would waste too many resources (stack space, execution time), causing unwanted side-effects, and/or the function doesn't have the right arguments and/or return values.

So we end up inventing some silly name like foo2 or foo_helper. I have always found it painful to come up with a proper name, and see some disadvantages:

You have to think up a name, which then pollutes the namespace

Function is created which is called from nowhere else

The program flow in the source code is interrupted

Some languages allow you to embed recursion directly in-place. This might work via a label, a local gosub instruction, or some special keyword.

The first solution uses macro substitution. In an expression headed by an apostrophe operator with an empty lhs all subexpressions headed by a dollar operator with empty lhs are replaced by the values that the rhs are bound to, without otherwise evaluating the expression. Example: if (x=7) & (y=4) then '($x+3+$y) becomes =7+3+4. Notice that the solution below utilises no other names than arg, the keyword that always denotes a function's argument. The test for negative or non-numeric arguments is outside the recursive part. The function fails if given negative input.

In C++ (as of the 2003 version of the standard, possibly earlier), we can declare class within a function scope. By giving that class a public static member function, we can create a function whose symbol name is only known to the function in which the class was derived.

# This is a rather obscure technique to have an anonymous# function call itself.fibonacci = (n)->throw"Argument cannot be negative"if n <0 do (n)->return n if n <= 1 arguments.callee(n-2)+ arguments.callee(n-1)

This puts a function in a local label. The function is not anonymous, but not only is it local, so that its name does not pollute the global namespace, but the name can be chosen to be identical to that of the surrounding function, so it is not a newly invented name

Although name space polution isn't an issue, in recognition of the obvious convenience of anonymous recursive helpers, here is another solution: add the language feature for anonymously recursive blocks: the operator RECURSIVE, with a built-in local operator RECURSE to make recursive calls.

RECURSIVE works by generating a local function with LABELS, but with a machine-generated unique name. Furthermore, it provides syntactic sugar so that the initial call to the recursive function takes place implicitly, and the initial values are specified using LET-like syntax. Of course, if RECURSIVE blocks are nested, each RECURSE refers to its own function. There is no way for an inner RECURSIVE to specify recursion to an other RECURSIVE. That is what names are for!

Exercises for reader:

In the original fib, the recursive local function can obtain a reference to itself using #'fib. This would allow it to, for instance, (apply #'fib list-of-args). Add a way for RECURSIVE blocks to obtain a reference to themselves.

Add support for &optional and &rest parameters. Optional: also &key and &aux.

Add LOOPBACK operator whose syntax resembles RECURSE, but which simply assigns the variables and performs a branch back to the top rather than a recursive call.

Tail recursion optimization is compiler-dependent in Lisp. Modify RECURSIVE so that it walks the expressions and identifies tail-recursive RECURSE calls, rewriting these to use looping code. Be careful that unevaluated literal lists which resemble RECURSE calls are not rewritten, and that RECURSE calls belonging to any nested RECURSIVE invocation are not accidentally treated.

In this version anonymous class is created, and by using opCall member function, the anonymous class object can take arguments and act like an anonymous function. The recursion is done by calling opCall inside itself.

The name q in the stack effect has no significance; call( x x -- x ) would still work.

The recursive quotation has 2 significant disadvantages:

To enable the recursion, a reference to the quotation stays on the stack. This q impedes access to other things on the stack. This solution must use dip and swap to move q out of the way. To simplify the code, one might move q to a local variable, but then the recursion would not be anonymous.

Factor cannot infer the stack effect of a recursive quotation. The last line must have call( n q -- m ) instead of plain call; but call( n q -- m ) defers the stack effect check until runtime. So if the quotation has a wrong stack effect, the compiler would miss the error; only a run of fib would detect the error.

Recursion is always anonymous in Forth, allowing it to be used in anonymous functions. However, definitions can't be defined during a definition (there are no 'local functions'), and the data stack can't be portably used to get data into a definition being defined.

The following solution works in both languages. A cache is used to improve performance.

This example is more a case of can it even be done, and just because we CAN do something - doesn't mean we should do it. The use of co-expressions for this purpose was probably never intended by the language designers and is more than a little bit intensive and definitely NOT recommended.

This example does accomplish the goals of hiding the procedure inside fib so that the type and value checking is outside the recursion. It also does not require an identifier to reference the inner procedure; but, it requires a local variable to remember our return point. Also, each recursion will result in the current co-expression being refreshed, essentially copied, placing a heavy demand on co-expression resources.

The double curly brace syntax after makeProc serves two different purposes, the outer set is used in the call to create a co-expression. The inner one binds all the expressions together as a single unit.

At #1 we remember where we came from and receive n from our caller

At #2 we transmit the new parameters to refreshed copies of the current co-expression setup to act as a normal procedure and cache the result.

At #3 we transmit the result back to our caller.

The procedure makeProc consumes the the first transmission to the co-expression which is ignored. Essentially this primes the co-expression to behave like a regular procedure.

The performance of this second version is 'truly impressive'. And I mean that in a really bad way. By way of example, using default memory settings on a current laptop, a simple recursive non-cached fib out distanced the non-cached fib above by a factor of 20,000. And a simple recursive cached version out distanced the cached version above by a factor of 2,000.

which is an anonymous form matches the "tail recursion" pattern is not automatically transformed to satisfy the classic "tail recursion optimization". That optimization would be implemented as transforming this particular example of recursion to the non-recursive

basis @: (g^:test^:_)

Of course, that won't work here, because we are adding two recursively obtained results where tail recursion requires that the recursive result is the final result.

Creates an anonymous inner class to do the dirty work. While it does keep the recursive function out of the namespace of the class, it does seem to violate the spirit of the task in that the function is still named.

Another way is to use the Java Y combinator implementation (the following uses the Java 8 version for better readability).
Note that the fib method below is practically the same as that of the version above, with less fibInner.

The "recurse" filter supports a type of anonymous recursion, e.g. to generate a stream of integers starting at 0:

0 | recurse(. + 1)

Also, as is the case for example with Julia, jq allows you to define an inner/nested function (in the follow example, aux) that is only defined within the scope of the surrounding function (here fib). It is thus invisible outside the function:

In Maple, the keyword thisproc refers to the currently executing procedure (closure), which need not be named. The following defines a procedure Fib, which uses a recursive, anonymous (unnamed) procedure to implement the Fibonacci sequence. For better efficiency, we use Maple's facility for automatic memoisation ("option remember").

> Fib( -1 );Error, invalid input: Fib expects its 1st argument, n, to be of typenonnegint, but received -1

The check for a negative argument could be put either on the outer Fib procedure, or the anonymous inner procedure (or both). As it wasn't completely clear what was intended, I put it on Fib, which results in a slightly better error message in that it does not reveal how the procedure was actually implemented.

An anonymous reference to a function from within itself is named #0, arguments to that function are named #1,#2..#n, n being the position of the argument. The first argument may also be referenced as a # without a following number, the list of all arguments is referenced with ##. Anonymous functions are also known as pure functions in Mathematica.

One can also use caller to get the name of the current subroutine as a string, then call the sub with that string. But this won't work if the current subroutine is anonymous: caller will just return '__ANON__' for the name of the subroutine. Thus, the below program must check the sign of the argument every call, failing the task. Note that under stricture, the line no strict 'refs'; is needed to permit using a string as a subroutine.

However, using any of these methods is insane, when Perl 6 provides a sort of inside-out combinator that lets you define lazy infinite constants, where the demand for a particular value is divorced from dependencies on more primitive values. This operator, known as the sequence operator, does in a sense provide anonymous recursion to a closure that refers to more primitive values.

constant@fib=0,1,*+*...*;say@fib[10];

Here the closure, *+*, is just a quick way to write a lambda, -> $a, $b { $a + $b }. The sequence operator implicitly maps the two arguments to the -2nd and -1st elements of the sequence. So the sequence operator certainly applies an anonymous lambda, but whether it's recursion or not depends on whether you view a sequence as iteration or as simply a convenient way of memoizing a recursion. Either view is justifiable.

At this point someone may complain that the solution is doesn't fit the specified task because the sequence operator doesn't do the check for negative. True, but the sequence operator is not the whole of the solution; this check is supplied by the subscripting operator itself when you ask for @fib[-1]. Instead of scattering all kinds of arbitrary boundary conditions throughout your functions, the sequence operator maps them quite naturally to the boundary of definedness at the start of a list.

In this solution, the function is always called using call_user_func() rather than using function call syntax directly. Inside the function, we get the function itself (without having to refer to the function by name) by relying on the fact that this function must have been passed as the first argument to call_user_func() one call up on the call stack. We can then use debug_backtrace() to get this out.

<?phpfunction fib($n){if($n<0)thrownew Exception('Negative numbers not allowed');$f=function($n){// This function must be called using call_user_func() onlyif($n<2)return1;else{$g=debug_backtrace()[1]['args'][0];returncall_user_func($g,$n-1)+call_user_func($g,$n-2);}};returncall_user_func($f,$n);}echo fib(8),"\n";?>

Use of anonymous recursive functions is not common in Qi. The philosophy of Qi
seems to be that using a "silly name" like "foo2" or "foo_helper" makes the code clearer than using anonymous recursive functions.

Here 'fib2' is a local variable of the fib() method. Only the fib() method, or a block inside the fib() method, can call this 'fib2'. The rest of this program cannot call this 'fib2', but it can use the name 'fib2' for other things.

The fib() method has two local variables 'fib2' and 'n'.

The block has a local variable 'm' and closes on both 'fib2' and 'n'.

Caution! The recursive block has a difference from Ruby 1.8 to Ruby 1.9. Here is the same method, except changing the block parameter from 'm' to 'n', so that block 'n' and method 'n' have the same name.

Ruby 1.9 still shows the correct answer, but Ruby 1.8 shows the wrong answer. With Ruby 1.9, 'n' is still a local variable of the block. With Ruby 1.8, 'n' of the block closes on 'n' of the fib() method. All calls to the block share the 'n' of one call to the method. So fib2[n - 1] changes the value of 'n', and fib2[n - 2] uses the wrong value of 'n', thus the wrong answer.

Our recursive block now lives in the 'block' variable of the Kernel#function method. Another block 'f' wraps our original block and sets up the 'arguments' array. Kernel#function returns this wrapper block. Kernel#arguments plays a trick to get the array of arguments from 'f'; this array has an extra singleton method #callee which returns 'f'.

In this example the local function has the same name as the outer function. This is fine: the local definition shadows
the outer definition, so the line "fib n" will refer to our helper function.

Another variation is possible. Instead, we could define the recursive "fib" at top-level, then shadow it with a non-recursive wrapper. To force the wrapper to be non-recursive, we use the "val" syntax instead of "fun":

This solution uses Tcl 8.5's lambda terms, extracting the current term from the call stack using introspection (storing it in a local variable only for convenience, with that not in any way being the name of the lambda term; just what it is stored in, and only as a convenience that keeps the code shorter). The lambda terms are applied with the apply command.

The shell does not have anonymous functions. Every function must have a name. However, one can create a subshell such that some function, which has a name in the subshell, is effectively anonymous to the parent shell.

~&izZB?( # test the sign bit of the argument <'fib of negative'>!%, # throw an exception if it's negative {0,1}^?<a( # test the argument to a recursively defined function ~&a, # if the argument was a member of {0,1}, return it sum^|W( # otherwise return the sum of two recursive calls ~&, # to the function thus defined predecessor^~( # with the respective predecessors of ~&, # the given argument predecessor)))) # and the predecessor thereof

Anonymous recursion is often achieved using the recursive conditional operator, ( _ )^?( _ , _ ), which takes a predicate on the left and a pair of functions on the right, typically one for the base and one for the inductive case in a recursive definition. The form ^?< can be used if the relevant predicate is given by membership of the argument in a constant set, in which case only the set needs to be specified rather than the whole predicate.

The recursive conditional operator ^? differs from the ordinary conditional ? seen at the outermost level by arranging for its predicate and component functions to be given an input of the form (f,a){\displaystyle (f,a)} where a{\displaystyle a} is the original argument, and f{\displaystyle f} is a copy of the whole function. Code within the function body may then access itself anonymously according to all the usual language idioms pertaining to deconstruction of tuples, and call itself by any of several recursion combinators, such as the pairwise recursion form W seen above.