<p>In writing recursive functions (functional style), I often need to refer to the current function (depending on the context).
e.g.</p>
<pre><code>f 0  = 0
f (S n) = f n + 2
</code></pre>
<p><em>Are there any functional languages that allow using a generic name such as <code>this_function</code> or <code>self</code> to be used instead of the specific function name <code>f</code>?</em></p>
<p>So, hypothetically, the above would be rewritten as</p>
<pre><code>f 0  = 0
f (S n) = self n + 2
</code></pre>
<p>It seems to make the spot of recursion easier to identify and the intention clearer. Also, it seems to allow one to <a href="https://stackoverflow.com/questions/7141229">write recursive anonymous functions</a>, e.g. a function to double a number in pseudo-code:</p>
<pre><code>\n r -&gt; if n &gt; 0 then self (n - 1) (r + 2) else r
</code></pre>
<p><em>Does such facility exist or is it possible?</em></p>

<functional-programming><recursion><lambda>
Is there a generic way to refer to the current function in recursion?
CC BY-SA 4.0
2024-02-08T17:03:44.240Z
I actually think this obfuscates the meaning more than clarifies it. I don't generally make a recursive call *because* it's a recursive call. For instance, when I write `append`, I make a call to `append` because I've done some of the work and now I need to append two lists. The fact that it happens to be the same function is almost a coincidence. If it were a different fn that also appended it'd still work. I just need to ensure I make progress. This is often how I think about recursion: "do some of the work, then treat the function 'as though it already works' when making recursive calls"
David Young
CC BY-SA 4.0
2024-02-08T17:36:08.487Z
That perspective also naturally extends to mutually recursive functions, even when there are more than two functions involved.
David Young
CC BY-SA 4.0
2024-02-08T18:16:00.307Z
I can only see this being useful for anonymous functions, e.g. `(n) => n <= 1 ? n : this_function(n-1) + this_function(n-2)` in Javascript. Otherwise making "the spot of recursion easier to identify" just isn't that important; IDE's can already highlight uses of a function's name when you hover over one of them (including the name in the function definition).
kaya3
CC BY-SA 4.0
2024-02-08T18:37:51.217Z
One issue is that you have to be very careful about a sort of dual of scoping. In many languages, `\n r -> ...` can best be understood as syntactic sugar for `\n -> \r -> ...`. But your example, `\n r -> ... self (n-1) (r+2) ...` relies critically on `\n r -> ...` and `\n -> \r -> ...` having distinct meanings. Or consider `f x = if x > 0 then (\n -> ...self...) else (\n -> 3)`; here you must decide whether `self` should refer to just the inner `\n -> ...` or to the entire `f x = ...`. Of course all of these decisions *can* be made, it just may be more complicated than you first think.
Daniel Wagner
CC BY-SA 4.0
2024-02-09T02:15:45.153Z
I agree with all these potential limitations, e.g. on mutual recursion, scoping and the implicitness. It's just an idea that occurred to me, and I was wondering it's being around.
tinlyx
CC BY-SA 4.0
2024-02-09T19:14:25.670Z
New here, so please forgive my ignorance and with no disrespect to OP who obviously knows a lot more than me, but I don't understand the question. Every language I code in has implicit ways to identify the methods being called. Happy for comments here or PM / chat if someone can help explain. Thanks.
Absinthe
CC BY-SA 4.0
2024-02-11T04:14:37.397Z
Possibly relevant: https://qntm.org/y
Karl Knechtel
CC BY-SA 4.0
2024-02-11T04:19:03.240Z
@Absinthe by definition, a recursive function is one that calls itself. But in order to specify what "itself" is, the code for that function will typically include a *name* for itself, which then has to be *looked up in an enclosing scope* (possibly the global scope). In OP's example in Haskell syntax, the recursively-defined `f` has code that includes the symbol `f` itself. The goal is to make this recursive call *without relying on* the name. So, for example, it should be possible to rename the function and still have it work and make those recursive calls, without changing the code inside.
Karl Knechtel
CC BY-SA 4.0
2024-02-15T17:15:21.737Z
@KarlKnechtel I agree. The function name should be a single point of truth, there should be no need to repeat it everywhere. It should also be optional: anonymous functions should be able to recurse.
Matheus Moreira
<h3>C++</h3>
<p>Since C++23 you can add an <a href="https://en.cppreference.com/w/cpp/language/function#Parameter_list" rel="nofollow noreferrer">explicit object parameter</a> to member functions and lambdas. You still have to give the parameter a name, but you would typically use <code>self</code> for that argument:</p>
<pre><code>auto factorial = [](this auto self, int n) -&gt; int {
    return n &gt; 1 ? n * self(n - 1) : 1;
}
</code></pre>

CC BY-SA 4.0
2024-02-18T16:35:37.803Z
2024-02-18T16:35:37.803Z
G. Sliepen
<p>In <code>R</code> we have <code>Recall</code>. From the docs we see (calling <code>?Recall</code>):</p>
<blockquote>
<p><code>Recall</code> is used as a placeholder for the name of the function in which it is called. It allows the definition of recursive functions which still work after being renamed, see example below.</p>
</blockquote>
<pre class="lang-r prettyprint-override"><code>## A trivial (but inefficient!) example:
fib &lt;- function(n)
   if(n&lt;=2) { if(n&gt;=0) 1 else 0 } else Recall(n-1) + Recall(n-2)
fibonacci &lt;- fib; rm(fib)
## renaming wouldn't work without Recall
fibonacci(10) # 55
</code></pre>

CC BY-SA 4.0
2024-02-09T16:15:33.563Z
2024-02-09T16:15:33.563Z
Joseph Wood
<p>In JavaScript, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments/callee" rel="nofollow noreferrer"><code>arguments.callee</code></a> could be used, but it is now deprecated and invalid in strict mode.</p>
<pre class="lang-js prettyprint-override"><code>function f(n) { return n === 0 ? 0 : arguments.callee(n-1) + 2; }
</code></pre>

CC BY-SA 4.0
2024-02-09T14:20:39.010Z
2024-02-09T14:20:39.010Z
corvus_192
CC BY-SA 4.0
2024-02-11T04:20:53.873Z
Doesn't this work by inspecting the runtime stack, rather than being an actual syntactic feature?
Karl Knechtel
CC BY-SA 4.0
2024-02-11T11:48:08.587Z
I think so, but I still wanted to comment because JS is widely-used.
corvus_192
<h3>APL</h3>
<p>A few APL dialects support the glyph <code>∇</code> inside a dfn (which is pretty much a lambda) which refers to the dfn itself. See <a href="https://help.dyalog.com/latest/#Language/Defined%20Functions%20and%20Operators/DynamicFunctions/Recursion.htm" rel="noreferrer">Dyalog documentation on recursion</a>.</p>
<p>(I guess it depends if you consider APL a functional language or not, tbf it doesn't have a lot of features standard FP languages are supposed to have)</p>

CC BY-SA 4.0
2024-02-08T17:08:38.870Z
2024-02-08T17:29:20.590Z
2024-02-08T17:29:20.590Z
RubenVerg
CC BY-SA 4.0
2024-02-09T02:21:42.597Z
Thanks. The `Implicit self-reference using '∇' ` APL counts though I don't know the language.
tinlyx
<h3>Forth</h3>
<p>Recursion in Forth actually requires a construct like this, as a word is not visible inside its own definition.  In order to recurse, you need to use the <a href="http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/Calls-and-returns.html#index-recurse-_0040var_007b-compilation-_002d_002d-_003b-run_002dtime-_003f_003f-_002d_002d-_003f_003f---_007d--core-1143" rel="noreferrer"><code>recurse</code></a> word, like so:</p>
<pre><code>: factorial ( n -- n! )
    dup 0&gt; if
        dup 1- recurse *
    else
        drop 1
    endif
;
</code></pre>

CC BY-SA 4.0
2024-02-11T13:51:06.663Z
2024-02-11T13:51:06.663Z
jwodder
<p>In Perl — which is not <em>primarily</em> a functional language, but does <em>support</em> functional programming styles — the keyword <code>__SUB__</code> is a reference to the current subroutine; your last example could be written as</p>
<pre><code>sub { my ($n, $r) = @_; $n &gt; 0 ? __SUB__-&gt;($n-1, $r+2) : $r }
</code></pre>
<p>Wikipedia refers to this as <em><a href="https://en.wikipedia.org/wiki/Anonymous_recursion#Examples" rel="noreferrer">anonymous recursion</a></em>, and in addition to Perl and APL, it also mentions equivalent features in JavaScript and R.</p>

CC BY-SA 4.0
2024-02-09T02:18:19.693Z
2024-02-09T02:18:19.693Z
ruakh
CC BY-SA 4.0
2024-02-10T17:11:53.867Z
Thanks for the link. I just noticed it today and it covers all of the languages mentioned thus far except for Mathematica. Maybe we can update the Wiki page?
Joseph Wood
<p>Mathematica, a definition of the factorial function:</p>
<pre><code>If[#1 == 1, 1, #1 #0[#1 - 1]]&amp;
</code></pre>
<p>(The ampersand indicates a definition of an anonymous function; <code>#0</code> is the anonymous function itself, and <code>#1</code> is the first argument to that function.)</p>

CC BY-SA 4.0
2024-02-09T11:17:46.240Z
2024-02-09T11:17:46.240Z
Patrick Stevens
# Is there a generic way to refer to the current function in recursion?
Posted by: username_0 on 2024-02-08
In writing recursive functions (functional style), I often need to refer to the current function (depending on the context).
e.g.
f 0  = 0
f (S n) = f n + 2

Are there any functional languages that allow using a generic name such as this_function or self to be used instead of the specific function name f?
So, hypothetically, the above would be rewritten as
f 0  = 0
f (S n) = self n + 2

It seems to make the spot of recursion easier to identify and the intention clearer. Also, it seems to allow one to write recursive anonymous functions, e.g. a function to double a number in pseudo-code:
\n r -> if n > 0 then self (n - 1) (r + 2) else r

Does such facility exist or is it possible?
**Tags:** functional-programming recursion lambda
> **Comments:**
> **username_1**: I actually think this obfuscates the meaning more than clarifies it. I don't generally make a recursive call *because* it's a recursive call. For instance, when I write `append`, I make a call to `append` because I've done some of the work and now I need to append two lists. The fact that it happens to be the same function is almost a coincidence. If it were a different fn that also appended it'd still work. I just need to ensure I make progress. This is often how I think about recursion: "do some of the work, then treat the function 'as though it already works' when making recursive calls"  
> **username_1**: That perspective also naturally extends to mutually recursive functions, even when there are more than two functions involved.  
> **username_2**: I can only see this being useful for anonymous functions, e.g. `(n) => n <= 1 ? n : this_function(n-1) + this_function(n-2)` in Javascript. Otherwise making "the spot of recursion easier to identify" just isn't that important; IDE's can already highlight uses of a function's name when you hover over one of them (including the name in the function definition).  
> **username_3**: One issue is that you have to be very careful about a sort of dual of scoping. In many languages, `\n r -> ...` can best be understood as syntactic sugar for `\n -> \r -> ...`. But your example, `\n r -> ... self (n-1) (r+2) ...` relies critically on `\n r -> ...` and `\n -> \r -> ...` having distinct meanings. Or consider `f x = if x > 0 then (\n -> ...self...) else (\n -> 3)`; here you must decide whether `self` should refer to just the inner `\n -> ...` or to the entire `f x = ...`. Of course all of these decisions *can* be made, it just may be more complicated than you first think.  
> **username_0**: I agree with all these potential limitations, e.g. on mutual recursion, scoping and the implicitness. It's just an idea that occurred to me, and I was wondering it's being around.  
> **username_4**: New here, so please forgive my ignorance and with no disrespect to OP who obviously knows a lot more than me, but I don't understand the question. Every language I code in has implicit ways to identify the methods being called. Happy for comments here or PM / chat if someone can help explain. Thanks.  
> **username_5**: Possibly relevant: https://qntm.org/y  
> **username_5**: @Absinthe by definition, a recursive function is one that calls itself. But in order to specify what "itself" is, the code for that function will typically include a *name* for itself, which then has to be *looked up in an enclosing scope* (possibly the global scope). In OP's example in Haskell syntax, the recursively-defined `f` has code that includes the symbol `f` itself. The goal is to make this recursive call *without relying on* the name. So, for example, it should be possible to rename the function and still have it work and make those recursive calls, without changing the code inside.  
> **username_6**: @KarlKnechtel I agree. The function name should be a single point of truth, there should be no need to repeat it everywhere. It should also be optional: anonymous functions should be able to recurse.  
---
## 7 answers
### Answer by username_10 on 2024-02-08. Score: 10 | Accepted answer
### APL

A few APL dialects support the glyph `∇` inside a dfn (which is pretty much a lambda) which refers to the dfn itself. See [Dyalog documentation on recursion](https://help.dyalog.com/latest/#Language/Defined%20Functions%20and%20Operators/DynamicFunctions/Recursion.htm).

(I guess it depends if you consider APL a functional language or not, tbf it doesn't have a lot of features standard FP languages are supposed to have)
> **Comments:**
> **username_0** (2024-02-09): Thanks. The `Implicit self-reference using '∇' ` APL counts though I don't know the language.  
---
### Answer by username_11 on 2024-02-11. Score: 7
Forth
Recursion in Forth actually requires a construct like this, as a word is not visible inside its own definition.  In order to recurse, you need to use the recurse word, like so:
: factorial ( n -- n! )
    dup 0> if
        dup 1- recurse *
    else
        drop 1
    endif
;
---
### Answer by username_12 on 2024-02-09. Score: 5
In Perl — which is not primarily a functional language, but does support functional programming styles — the keyword __SUB__ is a reference to the current subroutine; your last example could be written as
sub { my ($n, $r) = @_; $n > 0 ? __SUB__->($n-1, $r+2) : $r }

Wikipedia refers to this as anonymous recursion, and in addition to Perl and APL, it also mentions equivalent features in JavaScript and R.
> **Comments:**
> **username_8** (2024-02-10): Thanks for the link. I just noticed it today and it covers all of the languages mentioned thus far except for Mathematica. Maybe we can update the Wiki page?  
---
### Answer by username_13 on 2024-02-09. Score: 5
Mathematica, a definition of the factorial function:
If[#1 == 1, 1, #1 #0[#1 - 1]]&

(The ampersand indicates a definition of an anonymous function; #0 is the anonymous function itself, and #1 is the first argument to that function.)
---
### Answer by username_7 on 2024-02-18. Score: 3
C++
Since C++23 you can add an explicit object parameter to member functions and lambdas. You still have to give the parameter a name, but you would typically use self for that argument:
auto factorial = [](this auto self, int n) -> int {
    return n > 1 ? n * self(n - 1) : 1;
}
---
### Answer by username_8 on 2024-02-09. Score: 3
In R we have Recall. From the docs we see (calling ?Recall):

Recall is used as a placeholder for the name of the function in which it is called. It allows the definition of recursive functions which still work after being renamed, see example below.

## A trivial (but inefficient!) example:
fib <- function(n)
   if(n<=2) { if(n>=0) 1 else 0 } else Recall(n-1) + Recall(n-2)
fibonacci <- fib; rm(fib)
## renaming wouldn't work without Recall
fibonacci(10) # 55
---
### Answer by username_9 on 2024-02-09. Score: 3
In JavaScript, arguments.callee could be used, but it is now deprecated and invalid in strict mode.
function f(n) { return n === 0 ? 0 : arguments.callee(n-1) + 2; }
> **Comments:**
> **username_5** (2024-02-11): Doesn't this work by inspecting the runtime stack, rather than being an actual syntactic feature?  
> **username_9** (2024-02-11): I think so, but I still wanted to comment because JS is widely-used.  
---
